Lesson 70 – War Project – Global Variables

In the last lesson, we put three cards face down for a tie. Now, we need to put down one more card face up and see who wins all the cards.

We already have the code that takes the next card and shows it. The problem is that the code we need is in the function we’re using. We just put everything in the function draw. You pick a card and then show them, check who wins, and now deal with a tie. Calling a function from within itself is called a recursive function. You want to avoid it if you can at all. What might be a problem with recursive functions?

One thing that can happen is crashing your browser. Why? It might just call itself over and over and over again in an infinite loop.

So, in order to avoid a recursive function. I removed from our draw function the code that takes the next card and shows it. I put it in a function called assign and called it from inside draw. And then I ran into the same problem again.

I pulled out the code for looking for the winner and called it the function greater. I pulled out the code for a tie and called it the function war. When I did all that, I added all the variables first used in “Draw” to the list of variables at the top of the code. A variable introduced in a function is only available to that function; a variable introduced outside of a function is called a global variable and can be used anywhere. There is a way to pass variables around functions, but we don’t need to do that here.

Read your code like a book. Follow it through and see where it goes. You draw and it calls assign. Assign picks the cards and then checks who wins by calling greater. If the cards are equal, then it calls war. War puts down three cards and then calls assign to start the process over again with new cards.

Whenever I put cards into the player’s hands (using push), I had to make sure that the playedCards array was emptied and that the html was updated with the current number of cards. Another thing I had to change was adding “display”, “block” to the css of the first and second player suit areas. I put that right in assign. That combated having turned them off when we showed the card image instead.

Using console.log notes, you can track where your code is going. I like to put at the top of each function a note like console.log(“Assign running”). It helps track the flow of your code, especially if something doesn’t seem to be working.

To test out my code, I wanted ties to come up often. I changed 14 to 6 in my code that creates the cards (i=1; i<6; i++){  //should be 14. I left the suits alone. It creates 20 cards, enough that it didn’t run out constantly, but that ties would come up fairly frequently. We have one more step, what to do when the game is over and someone is out of cards.

You can watch this lesson as a video.