War Project

This lesson is tons of review. We’re adding the draw function, what happens when you click on the Draw button. It takes the number and suit of the first card in each player’s array (hand) and writes them on the page. To put the suit on the page, it assigns an html image to each suit number and appends as many times as the number on the card. It then takes those cards, compares them to find the winner, puts the playedCards in an array and pushes them to the winner. The winner and the number of cards in each player’s hand is written on the page.

Why put the played cards into an array before I push? I could just push each player’s cards. I was thinking ahead to when there is a tie and then there will be more cards played. This code doesn’t deal with face cards or ties yet.

Here’s the code for the draw function.

$draw.on('click', function() { $firstPlayerSuit.empty(); $secondPlayerSuit.empty(); var number1=firstPlayer[0][0]; //need to put in Jack, Queen, King $firstPlayerNumber.html(number1); $secondPlayerNumber.html(number2); suit1 = firstPlayer[0][1]; suit2 = secondPlayer[0][1];

You click on the draw box and the function runs.

We empty out whatever is in the players’ card boxes on the screen.

We define number one and two and suit one and two based on the first card in each player’s array. Think of that as picking up the top card in their pile.

We write on the screen the player’s numbers in their card boxes. Instead of just writing in the player’s suit, I define each suit number as an image. Then that image is appended the number of times as the player’s number. If I use html, it will just put the image on top of itself nine times, or however many. Append tags each image onto the one before. That’s what’s happening in the code to follow.

We take the two cards played and put them in an array and remove them from the players’ hands by splicing off the first card in each of their arrays.

We then check for the winner and give the winner the played cards. Finally, we empty out the playedCards array since we’ve given away those cards and write the length of each player’s array on the page to show how many cards each player has.

You can watch this lesson as well.