Skip to content

Instantly share code, notes, and snippets.

@djrosenbaum
Created March 10, 2021 05:28
Show Gist options
  • Save djrosenbaum/732724893725f69fb05532fb4c90445e to your computer and use it in GitHub Desktop.
Save djrosenbaum/732724893725f69fb05532fb4c90445e to your computer and use it in GitHub Desktop.
Someone on reddit asked about creating a card game of war with javascript
/*
Original Reddit Thread
https://www.reddit.com/r/learnjavascript/comments/m1fwq5/im_learning_javascript_and_desperately_need_help/
*/
// The child’s game, War, consists of two players each having a deck of cards.
// For each play, each person turns over the top card in his or her deck.
// The higher card wins that round of play and the winner takes both cards.
// The game continues until one person has all the cards and the other has none.
// Create a program that simulates a modified game of War.
// The computer will play both hands, as PlayerOne and PlayerTwo, and, for each round will generate two random numbers and compare them.
// If the first number is higher, PlayerOne’s score is increased by 1 and if the second number is higher, PlayerTwo’s score is increased by 1.
// If there is a tie, no score is incremented. When one “player” reaches a score of 10, that player should be deemed the winner and the game ends.
// The range of numbers should be 1-13 to simulate the values of cards in the deck.
function playWar() {
let winningScore = 10;
const player1 = new player();
const player2 = new player();
while(!haveWinner()) {
player1.getCard();
player2.getCard();
console.log('\n');
console.log('player1 card:', player1.card + 1);
console.log('player2 card:', player2.card + 1);
if (player1.card === player2.card) {
console.log('tie round');
continue;
}
if (player1.card > player2.card) {
console.log('player1 scored');
player1.score++;
} else {
console.log('player2 scored');
player2.score++;
}
}
console.log('\n');
console.log('==== FINAL SCORES ====');
console.log('player1:', player1.score);
console.log('player2:', player2.score);
const winner = player1.score > player2.score ? 'player1' : 'player2';
console.log(winner, 'won! 🏆');
function haveWinner() {
return player1.score >= winningScore || player2.score >= winningScore;
}
}
function player() {
let deck = getShuffledDeck();
// console.log('player', deck);
return {
getCard() {
if (!deck.length) {
deck = getShuffledDeck();
}
this.card = deck.pop();
},
score: 0,
card: 0,
}
}
function getShuffledDeck() {
const deck = [...Array(4)].map(i => [...Array(13).keys()]).flat();
return shuffle(deck);
}
function shuffle(arr) {
return arr.sort(() => Math.random() - 0.5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment