A standalone, framework-free JavaScript module for memory card game logic.
- Deck Creation: Automatically generates card pairs
- Shuffling: Fisher-Yates algorithm for random card placement
- Card Flipping: Handles flip logic with validation
- Matching Logic: Detects and tracks matched pairs
- Move Counting: Tracks player moves
- Game-Over Detection: Automatically detects when all pairs are matched
const engine = new GameEngine();Initialize and start a new game.
- Parameters:
pairCount- Number of card pairs (default: 8) - Returns: Game state object
const state = engine.start(8); // Start with 8 pairs (16 cards)Flip a card and handle matching logic.
- Parameters:
cardId- Unique card identifier - Returns: Updated game state object
const state = engine.flip('card-0-a');Get current game state as plain JSON.
- Returns: Game state object
const state = engine.getState();Reset the game to initial state.
- Returns: Initial game state object
const state = engine.reset();Reset non-matched flipped cards (call after mismatch delay).
- Returns: Updated game state object
// After showing mismatch for 1 second
setTimeout(() => {
const state = engine.resetFlippedCards();
}, 1000);{
cards: [
{ id: 'card-0-a', value: 0, flipped: false, matched: false },
// ...
],
moves: 0,
gameStarted: false,
gameOver: false,
flippedCount: 0,
matchedPairs: 0,
isMatching: false,
isMismatched: false
}const engine = new GameEngine();
// Start game
let state = engine.start(8);
// Flip first card
state = engine.flip('card-0-a');
// Flip second card
state = engine.flip('card-3-b');
// Check if they match
if (state.isMismatched) {
// Wait then reset
setTimeout(() => {
state = engine.resetFlippedCards();
}, 1000);
}
// Check game over
if (state.gameOver) {
console.log(`Won in ${state.moves} moves!`);
}
// Reset game
state = engine.reset();Open example.html in a browser to see a working demo.
The module supports CommonJS exports:
// Node.js
const GameEngine = require('./GameEngine.js');Or use directly in browser:
<script src="GameEngine.js"></script>