War Project – Compare

We are going to start with the compare function since we already have that in existence, we just need to change how it’s being used.

The first thing I did was change player one to player and player two to computer. I just changed it in the HTML, the part that you see on the screen, not in the code.

I then created variables compare, chosen, and winner. I set them all to zero. I set compare to 1, compare = 1, when they choose the compare option. That’s my cue to use the compare code. Chosen is set to one or two depending on whether they click on “Winner” on the first or second card. Winner is the actual winning card, either one or two.

If the variable compare equals one, then we skip over the normal automatic checking and wait for the player to choose the winning card. When they make their choice, we see if they are correct. If they are, player gets the cards. If not, then the computer gets the cards. The player now wins, not by chance, but by skill.

Another way to do it is to set compare equal to false to start and then change it to true if the player chooses it. This is called a Boolean operator. Then you could say, “If compare, then do this.” My brain doesn’t like it. I use 0 and 1 i the same way, kind of like a light switch. 0 is off and 1 is on.

function compareMath(){ if (number1 > number2) { winner = 1; } else{ winner = 2; } } function compareCheck() { if (chosen == winner) { for (i=0; i<playedCards.length; i++) { firstPlayer.push(playedCards[i]); } $player1Count.html(firstPlayer.length); playedCards=[]; } else { for (i=0; i<playedCards.length; i++) { secondPlayer.push(playedCards[i]); } $player2Count.html(secondPlayer.length); playedCards=[]; } }

You can watch this lesson.