Skip to main content
edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
Tweeted twitter.com/#!/StackCodeReview/status/543203132982198272
edited tags
Link
RubberDuck
  • 31.2k
  • 6
  • 74
  • 177
Source Link

Better card validity check in JS card game

I am writing a card game in Javascript. The game is played with a 32 card deck.

When a card is selected to be played by a user, i do a validity check on the server to check whether it matches the games rules.

These are

  • A card may be played when it matches either the color or the value of the last card on the stack
  • If a 7 is played, the next player must either draw 2 cards or counter with another 7. If he draws, he may play another card that complies the rule above.
  • A jack may be played anytime when there is no 7 to be countered or the player has drawn. It does not have to match the color or value of the last card. When a player plays a jack, he may decide the color of the next card to be played.

I created a class of game that, amongst others, implements a function iscardLegal()

Game.prototype.isCardLegal = function(card,player){ if(player.flags.forcedDraw > 0 && card.value !== '7'){ player.setTask('forced draw'); return false; } // A jack may be played anytime if there is no 7 on top of the stack if(card.value === 'J'){ return true; } if(this.forcedColor && this.forcedColor !== card.color){ player.setTask('color mismatch'); return false; } // If there is a forced color due to the playing of a jack, we must ignore the stack#s top card color if(this.forcedColor && this.forcedColor === card.color){ return true; } if(this.lastCardOnStack().color !== card.color && this.lastCardOnStack().value !== card.value){ player.setTask('invalid card'); return false; } return true; }; 

I am unhappy with this function because I end up with a chunk of if rules that need to be in a certain order to match all the rules. If I imagine writing a slightly more complex game, I think this would be unmaintainable.

I am looking for ideas and / or examples of better implemenations of this functionality.