Skip to content

Instantly share code, notes, and snippets.

@stackola
Created September 11, 2019 17:34
Show Gist options
  • Save stackola/711ec8df4e42f23008cc63546a31a826 to your computer and use it in GitHub Desktop.
Save stackola/711ec8df4e42f23008cc63546a31a826 to your computer and use it in GitHub Desktop.
/**
* Define strategies here
*/
let rnd = (deck, enemyDeck) => {
//plays a random card
return deck[Math.floor(Math.random() * deck.length)];
};
let lowest = (deck, enemyDeck) => {
//plays the lowest card in own deck
return deck.sort((a, b) => a - b)[0];
};
class Game {
constructor(s1, s2, gameLength) {
this.s1 = s1;
this.s2 = s2;
this.gameLength = gameLength;
this.reset();
}
reset() {
this.score = { 1: 0, 2: 0 };
this.bonus = 0;
this.decks = {
1: Array.from(Array(this.gameLength), (x, index) => index + 1),
2: Array.from(Array(this.gameLength), (x, index) => index + 1)
};
}
runGame() {
this.reset();
for (let i = 0; i < this.gameLength; i++) {
this.runRound();
}
if (this.score[1] > this.score[2]) {
return 1;
}
if (this.score[1] < this.score[2]) {
return 2;
}
return 0;
}
runRound() {
let cards = {
1: this.s1(this.decks[1], this.decks[2]),
2: this.s2(this.decks[2], this.decks[1])
};
//filter cards form decks.
this.decks[1] = this.decks[1].filter(c => c !== cards[1]);
this.decks[2] = this.decks[2].filter(c => c !== cards[2]);
if (cards[1] > cards[2]) {
//p1 wins.
this.score[1] += 1;
this.score[1] += this.bonus;
this.bonus = 0;
}
if (cards[1] < cards[2]) {
this.score[2] += 1;
this.score[2] += this.bonus;
this.bonus = 0;
}
if (cards[1] == cards[2]) {
//increment bonus.
this.bonus++;
}
}
}
let globScore = { 0: 0, 1: 0, 2: 0 };
let gameCount = 100000000;
let updateEvery = 1000;
let cardsInHand = 11;
console.clear();
//Use strategies here
let g = new Game(rnd, lowest, cardsInHand);
for (let i = 0; i < gameCount; i++) {
let t = g.runGame();
globScore[t]++;
if ((i + 1) % updateEvery == 0) {
console.clear();
console.log(globScore);
console.log("After " + (i + 1) + " games");
console.log("Player 1 wins " + (globScore[1] / (i + 1)) * 100 + "%");
console.log("Player 2 wins " + (globScore[2] / (i + 1)) * 100 + "%");
}
}
console.clear();
console.log(globScore);
console.log("After " + gameCount + " games");
console.log("Player 1 wins " + (globScore[1] / gameCount) * 100 + "%");
console.log("Player 2 wins " + (globScore[2] / gameCount) * 100 + "%");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment