I wrote a simple card game in JavaScript and I wonder if anyone could give me some advice and make some improvements on my code.
Here is the demo that I build: https://codesandbox.io/s/cardgame-his95?file=/src/index.js
So it is a 2 person card game. Every card has a number and also has a pattern. The game goes like this: we have a set of pre-defined rules, and these rules have a ranking. The player that satisfies the highest-ranked rule will win. And there could be tie if they end up with the same ranking. The goal here is not just to make the game work, also I wanted to account for maintainability. For example, we can easily add new rules and swap the ranking and re-define the rule if possible.
There are mainly a couple of classes.
First is the Game
class
class Game {
constructor({ play1, play2, rules, messages }) {
this.play1 = play1;
this.play2 = play2;
this.rules = rules;
this.messages = messages;
}
play() {
let rankOfP1 = Infinity;
let rankOfP2 = Infinity;
for (const rule of this.rules) {
if (rule.validator(this.play1)) {
rankOfP1 = rule.rank;
break;
}
}
for (const rule of this.rules) {
if (rule.validator(this.play2)) {
rankOfP2 = rule.rank;
break;
}
}
return rankOfP1 === rankOfP2
? this.messages.tie
: rankOfP1 < rankOfP2
? this.messages.win.player1
: this.messages.win.player2;
}
}
Here the rules
are an array of rule
object where every object looks like this
{
description: "Six Cards of the same pattern",
rank: 1,
validator: cards => {
return hasSamePattern(cards, 6);
}
The lower the rank gets, the more important this rule is. So If player1
satisfies a rule
with rank 1
, and player1
satisfies a rule
with rank 2
, then we say player1
won.
And validator
is the function that takes an array of card
object and returns a boolean to determine if the set of cards satisfy the rule.
And lastly we have a Card
class which is pretty simple
class Card {
constructor({ pattern, number }) {
this.pattern = pattern;
this.number = number;
}
}
Please take a look and feel free to make some improvements on it. Also please suggest some better naming for variables if possible, I am not a native English speaker so some of the names of the variables would be a bit weird.
Finally I wrote this game in a OOP style. I know that JavaScript is not the best language out there when it comes to OOP. Also I am not really good at Object Oriented Design. I wonder if anyone knows how to rewrite the game in functional programming style. That would be super cool!