Mostly for the experience (but also so I could waste hours playing it), I made a simple memory card game in JavaScript. I built it so it has a backbone framework that could be easily extended by stripping off my actual implementation. It's the backbone I'd like reviewed here, and mostly:
- My OO - anything wrong; anything that could be improved on?
- Obvious code efficiency: is there anything that could make it more efficient?
- Structure: Is the structure of the game a good idea?
var Card = (function() {
var self = Object.create({}, {
val: {
value: -1
},
index: {
value: -1
},
addTo: {
value: function(game) {
var random = -1;
counter = 0; //break counter to stop infinite loop. :)
while ((game.cards[random] !== undefined && counter <= 100) | random === -1) {
random = Math.round(game.cards.length * Math.random());
counter++;
}
this.index = random;
game.cards[random] = this;
}
},
isMatch: {
value: function(game) {
if (this.val == game.selected.val) {
game.matches++;
return true;
}
return false;
}
}
});
return self;
})();
var Game = (function() {
var self = Object.create({}, {
cards: {
value: new Array(30)
},
matches: {
value: 0
},
init: {
value: function(func) {
for (i = 0; i < this.cards.length / 2; i++) {
var card = Object.create(Card, {
val: {
value: i
}
});
var card2 = Object.create(Card, {
val: {
value: i
}
});
card.addTo(this);
card2.addTo(this);
}
if (typeof func === 'function') {
func();
}
}
},
selected: {
value: null
}
});
return self;
})();
Sorry about the length; that's partly why I want it reviewed.
To see how to implement it and the full code, see here
EDIT: FYI, I realize the game isn't currently extensible. For example, if I wanted there to be multiple types of matches, I can't do that quite yet. I'm pretty sure I know how to add that in, but I wanted to make sure my design structure was solid first.