JavaScript Game Learn how to apply JavaScript to make a Battle Card Game no Libraries DOM code array

Get the course Today

https://www.udemy.com/course/javascript-dom-course/?referralCode=184A9BA60ABD50E82338

JavaScript Battle Cards Game using Array methods

Using JavaScript to create an interactive game, this exercise will demonstrate how to build a deck of cards.  How to track players and create the output for the game play.  Applying logic to determine which player wins and how many cards are left for each.

By using various array methods this will enable the application to  track player status, and provide output for the game.  

Objective of the game is to draw the highest card in the round, the player that draws the highest card from their deck wins.  The winner of the round collects all the cards that were played in that round.  Ties will happen, this results in a run off between the winners for the pot of cards in play.  The players who tied, will go additional rounds drawing the next card in their deck until one player wins the round.   That player will win and collect all the cards played in the round including the tie game cards.

The game will be dynamic, where the number of players will be set in the game values, and the game will work the same regardless of how many players are in the game.  You can use the HTML and CSS as starting code, or customize the CSS and page styling as desired.  The CSS will enhance the appearance of the game, and not designed to change the actual game play.   JavaScript will be used to create page elements, and add the various classes to those elements.  Within the HTML we only have the one container element with a class of game.

In this coding example we will be adding array values into other arrays, and selecting the highest value from an array of numbers.  Using the 3 dots or spread operator will give us a way to pass the array into the argument and have the results be treated as the array was a set of values not contained in an array.  When three dots (…) is used it expands an array into a list.  This allows a function to accept an indefinite number of arguments as an array providing a way to use an array like a set of values.   The example below will outline the different outputs in function a and function b for the arguments with and without the 3 dots.

const arr = [1,2,4,5];

function a(…vals){

   console.log(vals);

};

a(…arr);

function b(vals){

   console.log(vals);

};

b(…arr);

The code will use many array methods and several Math methods.  Math.max() function will return the largest of the numbers given as input parameters, or NaN if the parameter isn’t a number and cannot be converted into a number.

const arr = [1,2,4,5];

console.log(Math.max(1,2,4,5));

console.log(Math.max(…arr));

console.log(Math.max(arr));

<!doctype html>

<html>

<head>

  <title>JavaScript</title>

  <style>

     * {

        box-sizing: border-box;

     }

     .gameArea {

        width: 80vw;

        margin: auto;

        text-align: center;

     }

     .info {

        background-color: blue;

        color: white;

     }

     .card {

        min-height: 60px;

        background-color: #eee;

        border: 1px solid #111;

        margin: 5px;

        line-height: 60px;

        font-size: 1.5em;

     }

     .mes {

        text-align: center;

        padding: 10px;

        border: 1px solid #ccc;

        clear: both;

     }

     .btn {

        display: block;

        clear: both;

        margin: auto;

     }

     .player {

        width: 33%;

        border: 1px solid #ddd;

        min-height: 100px;

        float: left;

        padding: 10px;

        margin-bottom: 20px;

     }

  </style>

</head>

<body>

  <div class=”game”></div>

  <script src=”code11.js”></script>

</body>

</html>

Card deck data, as the suits will repeat, and the numbers will repeat.  This can be used to construct the cards with values.

const cardData = {suits:[‘spades’,’hearts’,’diams’,’clubs’],val:[‘A’,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’10’,’J’,’Q’,’K’]} 

function buildDeck() {

   cardData.suits.forEach((suit) => {

       cardData.val.forEach((v, ind) => {

           const bgC = (suit == ‘hearts’) || (suit == ‘diams’) ? ‘red’ : ‘black’;

           const card = {

               suit: suit,

               icon: `&${suit};`,

               clr: bgC,

               cardNum: v,

               cardValue: ind + 1

           }

           deck.push(card);

       })

   })

   deck.sort(() => {

       return Math.random() – 0.5;

   })

}

Exercise :

  1. Create a function that can be used to make page elements with parameters of element tag, parent element, content of element, and class of element.  This can now be used to create elements quickly within the code.
  2. Setup the game board, with elements for the game area, a button for the game play and a message area for player communication from the game.
  3. Create a global game object that will hold the number of players, the card decks for each player, and the elements in an array that the player will need for visuals in the game play.  (card view and score action feedback)
  4. Create a data array with card details, all of the suits and the values to be used in the main deck of cards.  If you use the suits HTML character values, these can then be reused when outputting the visuals in the application. (&spades; &hearts; &diams; &clubs;)
  5. Create a main deck array that will be populated with the card deck.  Create a function to build the deck of cards.  buildDeck()
  6. In the buildDeck() function, loop through all the card data, loop through the suits as well as the values of the cards in order to construct a typical deck of 52 cards.  Create a card object with data that can then be used to output visuals for the card and make the calculations of the card values.
  7. Shuffle the deck once it’s built, you can use the array sort method.  

   deck.sort(() => {

       return Math.random() – 0.5;

   })

  1. Add the players to the game.   Create a function to add players.  addPlayers()
  2. In the ​​addPlayers() function, calculate the number of cards each player will get from the main deck.  
  3. Using a for loop, loop through each player to add them to the page, and add the player data to them including the deck of cards for that player.  Add the page elements, player info, card display area, score and feedback on the round.  Add these elements into arrays contained within the game object.  The arrays can then be selected for each player as by using the index value of the player.  The index values will be inline with the array starting at 0 for the first player index.
  4. Using slice() select from the main deck the start and end position for that player’s cards.  This can be calculated using the last end position, setting that as start. Use that start and add the number of cards for each player to get the end value for the slice.
  5. Add an event listener for the main button, this will start the game play.  
  6. Within the main click event, loop through all the players, check the number of cards in their decks.  If they have more than 1 then add them into a temporary array of players that have cards and are still in the game.  If they don’t have cards then apply styling to indicate visually that the player is out.  Once all the active players are in an array, create a new function and send that array, and an empty array to the function gamer()  The empty array will be used to hold all the cards that are in play, so that they can be awarded to the round winner.  This is setup so that within the gamer() function we can invoke the function again if needed.
  7. Within the gamer() function loop through all the players in play.   Check if the player has cards left, if they do then select the card view element for the player.  Using shift() remove the first item from the player card deck array.  
  8. Create a function to show the card on the page, invoke the function and send the card data and the element that needs to be updated.  

function showCard(cc, ele) {

   ele.innerHTML = `<div>${cc.cardNum}${cc.icon}</div>`;

   ele.style.color = cc.clr;

}

  1. Add the played card to the holder array, add the value of the played card to the vals array.  Update the game score for the player with the card value that was played.
  2. Create a new array to hold the winners of this round.   
  3. From the vals array get the highest value from the items in the vals array.  

   const highValue = Math.max(…vals);

  1. Using the vals array, loop through all the players checking for the player that played the high value card.  Add the players into the winners array.  This will also pick up ties and could add multiple winners for this round into the winners array.
  2. Apply logic to check if there are more than one player in the winners array.  If there are more than one player then this is a tie, and a second draw of players cards is needed.  Output the tied feedback to the page.  Use return to invoke the gamer array, adding only the tied players into the round players, and add the holder array so that more cards can be added.
  3. If there is only one winner, that player is now the winner of the round and will collect all the cards in the holding array.   You can use push to update the players card deck with the new won cards from the holder array.   To add the array as items use the Spread operator to add them as a list.  .push(…holder);
  4. Create a function to update the scores for the players on the page.  Loop through all the game score elements for the players, using the index select the associated player and get that player’s card deck length.  If they have a value then output the cards remaining for that player.  If no cards remain, apply a style of opacity to the player element. 

el.parentNode.style.opacity = 0.4;

  1. For the game end, within the score update function create an array that can hold the players that are left in the game.  If the length of the player’s length in the game array is one, then end the game and announce the winner.  You can disabled the main play button and provide text that the game is over.

JavaScript Card Game final source code : 

const main = document.querySelector(‘.game’);

//main.innerHTML = `&spades; &hearts; &diams; &clubs; `;

const gameArea = maker(main, ‘div’, ‘gameArea’, ”);

const btn = maker(main, ‘button’, ‘btn’, ‘Next Round’);

const mes = maker(main, ‘div’, ‘mes’, ‘Click to Play’);

const game = {

   players: 3,

   cards: [],

   view: [],

   s: []

};

const cardData = {suits:[‘spades’,’hearts’,’diams’,’clubs’],val:[‘A’,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’10’,’J’,’Q’,’K’]} 

/*const cardData = {

   suits: [‘spades’, ‘hearts’, ‘diams’, ‘clubs’],

   val: [‘A’, ‘2’, ‘3’, ‘4’, ‘5’]

}

*/

const deck = [];

buildDeck();

addPlayers();

btn.addEventListener(‘click’, (e) => {

   const temp = [];

   for (let i = 0; i < game.players; i++) {

       game.s[i].lastChild.innerHTML = ”;

       if (game.cards[i].length > 0) {

           temp.push(i);

       } else {

           const ele = game.view[i];

           ele.innerHTML = ‘X’;

           game.s[i].firstChild.innerHTML = ‘OUT’;

           ele.style.backgroundColor = ‘#bbb’;

       }

   }

   mes.innerHTML = ‘Battle has begun…’;

   gamer(temp, []);

})

function gamer(inPlay, holder) {

   const vals = [];

   console.log(inPlay);

   inPlay.forEach((i) => {

       if (game.cards[i].length > 0) {

           const ele = game.view[i];

           const first = game.cards[i].shift();

           showCard(first, ele);

           vals.push(first.cardValue);

           holder.push(first);

           game.s[i].lastChild.innerHTML += `${first.cardNum}${first.icon} `;

       }

   })

   const winners = [];

   const highValue = Math.max(…vals);

   console.log(highValue);

   vals.forEach((e, i) => {

       if (e >= highValue) winners.push(inPlay[i]);

   })

   console.log(winners);

   if (winners.length > 1) {

       mes.innerHTML += `Tie:`;

       winners.forEach(v => {

           mes.innerHTML += `P${v+1} `;

       })

       mes.innerHTML += `…`;

       return gamer(winners, holder);

   } else if (winners.length == 0) {

       mes.innerHTML += ‘No winner’;

   } else {

       const temp = winners[0];

       game.cards[temp].push(…holder);

       mes.innerHTML += `Winner is Player ${temp+1}!`;

   }

   updateScores();

}

function updateScores() {

   let tempPlay = [];

   game.s.forEach((el, i) => {

       const cardCount = game.cards[i].length;

       if (cardCount) {

           el.firstChild.innerHTML = `${cardCount} left`;

           tempPlay.push(i);

       } else {

           el.parentNode.style.opacity = 0.4;

       }

   })

   if (tempPlay.length <= 1) {

       mes.innerHTML = `Game Over! Player ${tempPlay[0]+1} Wins`;

       btn.disabled = true;

       btn.textContent = ‘GAME OVER’;

   }

}

function showCard(cc, ele) {

   ele.innerHTML = `<div>${cc.cardNum}${cc.icon}</div>`;

   ele.style.color = cc.clr;

}

function addPlayers() {

   let start = 0;

   let num = Math.floor(deck.length / game.players);

   let end = start + num;

   for (let i = 0; i < game.players; i++) {

       const el = maker(gameArea, ‘div’, ‘player’, “);

       const ele = maker(el, ‘div’, ‘info’, `${i+1} Player`);

       const card = maker(el, ‘div’, ‘card’, “);

       game.view.push(card);

       game.cards[i] = deck.slice(start, end);

       const score = maker(el, ‘div’, ‘score’, “);

       const cardLeft = maker(score, ‘div’, ‘box’, `${game.cards[i].length} left`);

       const cardPlayed = maker(score, ‘div’, ‘box’, ”);

       game.s.push(score);

       start = end;

       end = end + num;

   }

   console.log(game.cards);

}

function buildDeck() {

   cardData.suits.forEach((suit) => {

       cardData.val.forEach((v, ind) => {

           const bgC = (suit == ‘hearts’) || (suit == ‘diams’) ? ‘red’ : ‘black’;

           const card = {

               suit: suit,

               icon: `&${suit};`,

               clr: bgC,

               cardNum: v,

               cardValue: ind + 1

           }

           deck.push(card);

       })

   })

   deck.sort(() => {

       return Math.random() – 0.5;

   })

}

function maker(par, eleType, cla, html) {

   const ele = document.createElement(eleType);

   ele.classList.add(cla);

   ele.innerHTML = html;

   return par.appendChild(ele);

}

JavaScript Battle Cards Game using Array methods Using JavaScript to create an interactive game, this exercise will demonstrate how to build a deck of cards. How to track players and create the output for the game play. Applying logic to determine which player wins and how many cards are left for each. By using various array methods this will enable the application to track player status, and provide output for the game. Objective of the game is to draw the highest card in the round, the player that draws the highest card from their deck wins. The winner of the round collects all the cards that were played in that round. Ties will happen, this results in a run off between the winners for the pot of cards in play. The players who tied, will go additional rounds drawing the next card in their deck until one player wins the round. That player will win and collect all the cards played in the round including the tie game cards. The game will be dynamic, where the number of players will be set in the game values, and the game will work the same regardless of how many players are in the game. You can use the HTML and CSS as starting code, or customize the CSS and page styling as desired. The CSS will enhance the appearance of the game, and not designed to change the actual game play. JavaScript will be used to create page elements, and add the various classes to those elements. Within the HTML we only have the one container element with a class of game. In this coding example we will be adding array values into other arrays, and selecting the highest value from an array of numbers. Using the 3 dots or spread operator will give us a way to pass the array into the argument and have the results be treated as the array was a set of values not contained in an array. When three dots (…) is used it expands an array into a list. This allows a function to accept an indefinite number of arguments as an array providing a way to use an array like a set of values. The example below will outline the different outputs in function a and function b for the arguments with and without the 3 dots. const arr = [1,2,4,5]; function a(…vals){ console.log(vals); }; a(…arr); function b(vals){ console.log(vals); }; b(…arr); The code will use many array methods and several Math methods. Math.max() function will return the largest of the numbers given as input parameters, or NaN if the parameter isn’t a number and cannot be converted into a number. Exercise : Create a function that can be used to make page elements with parameters of element tag, parent element, content of element, and class of element. This can now be used to create elements quickly within the code. Setup the game board, with elements for the game area, a button for the game play and a message area for player communication from the game. Create a global game object that will hold the number of players, the card decks for each player, and the elements in an array that the player will need for visuals in the game play. (card view and score action feedback) Create a data array with card details, all of the suits and the values to be used in the main deck of cards. If you use the suits HTML character values, these can then be reused when outputting the visuals in the application. (&spades; &hearts; &diams; &clubs;) Create a main deck array that will be populated with the card deck. Create a function to build the deck of cards. buildDeck() In the buildDeck() function, loop through all the card data, loop through the suits as well as the values of the cards in order to construct a typical deck of 52 cards. Create a card object with data that can then be used to output visuals for the card and make the calculations of the card values. Shuffle the deck once it’s built, you can use the array sort method. deck.sort(() => { return Math.random() – 0.5; }) Add the players to the game. Create a function to add players. addPlayers() In the ​​addPlayers() function, calculate the number of cards each player will get from the main deck. Using a for loop, loop through each player to add them to the page, and add the player data to them including the deck of cards for that player. Add the page elements, player info, card display area, score and feedback on the round. Add these elements into arrays contained within the game object. The arrays can then be selected for each player as by using the index value of the player. The index values will be inline with the array starting at 0 for the first player index. Using slice() select from the main deck the start and end position for that player’s cards. This can be calculated using the last end position, setting that as start. Use that start and add the number of cards for each player to get the end value for the slice. Add an event listener for the main button, this will start the game play. Within the main click event, loop through all the players, check the number of cards in their decks. If they have more than 1 then add them into a temporary array of players that have cards and are still in the game. If they don’t have cards then apply styling to indicate visually that the player is out. Once all the active players are in an array, create a new function and send that array, and an empty array to the function gamer() The empty array will be used to hold all the cards that are in play, so that they can be awarded to the round winner. This is setup so that within the gamer() function we can invoke the function again if needed. Within the gamer() function loop through all the players in play. Check if the player has cards left, if they do then select the card view element for the player. Using shift() remove the first item from the player card deck array. Create a function to show the card on the page, invoke the function and send the card data and the element that needs to be updated. function showCard(cc, ele) { ele.innerHTML = `<div>${cc.cardNum}${cc.icon}</div>`; ele.style.color = cc.clr; } Add the played card to the holder array, add the value of the played card to the vals array. Update the game score for the player with the card value that was played. Create a new array to hold the winners of this round. From the vals array get the highest value from the items in the vals array. const highValue = Math.max(…vals); Using the vals array, loop through all the players checking for the player that played the high value card. Add the players into the winners array. This will also pick up ties and could add multiple winners for this round into the winners array. Apply logic to check if there are more than one player in the winners array. If there are more than one player then this is a tie, and a second draw of players cards is needed. Output the tied feedback to the page. Use return to invoke the gamer array, adding only the tied players into the round players, and add the holder array so that more cards can be added. If there is only one winner, that player is now the winner of the round and will collect all the cards in the holding array. You can use push to update the players card deck with the new won cards from the holder array. To add the array as items use the Spread operator to add them as a list. .push(…holder); Create a function to update the scores for the players on the page. Loop through all the game score elements for the players, using the index select the associated player and get that player’s card deck length. If they have a value then output the cards remaining for that player. If no cards remain, apply a style of opacity to the player element. el.parentNode.style.opacity = 0.4; For the game end, within the score update function create an array that can hold the players that are left in the game. If the length of the player’s length in the game array is one, then end the game and announce the winner. You can disabled the main play button and provide text that the game is over.

Leave a Comment