Created
February 1, 2025 18:01
-
-
Save carefree-ladka/e1a20d4ba94d2498ea558e461fe2bccb to your computer and use it in GitHub Desktop.
Snake Ladder Game
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Dice { | |
roll() { | |
return Math.floor(Math.random() * 6) + 1; | |
} | |
} | |
class Board { | |
constructor(size, snakes, ladders) { | |
this.size = size; | |
this.snakes = new Map(snakes); // {start: end} | |
this.ladders = new Map(ladders); // {start: end} | |
} | |
getNewPosition(position) { | |
if (this.snakes.has(position)) { | |
console.log(`Oops! Snake at ${position}, sliding down to ${this.snakes.get(position)}`); | |
return this.snakes.get(position); | |
} | |
if (this.ladders.has(position)) { | |
console.log(`Yay! Ladder at ${position}, climbing up to ${this.ladders.get(position)}`); | |
return this.ladders.get(position); | |
} | |
return position; | |
} | |
isWinningPosition(position) { | |
return position === this.size; | |
} | |
} | |
class Player { | |
constructor(name) { | |
this.name = name; | |
this.position = 1; | |
} | |
move(steps, board) { | |
let newPosition = this.position + steps; | |
if (newPosition > board.size) { | |
console.log(`${this.name} rolled ${steps}, but can't move beyond ${board.size}.`); | |
return; | |
} | |
console.log(`${this.name} rolled a ${steps} and moved from ${this.position} to ${newPosition}`); | |
this.position = board.getNewPosition(newPosition); | |
} | |
} | |
class SnakeLadderGame { | |
constructor(players, boardSize, snakes, ladders) { | |
this.players = players.map(name => new Player(name)); | |
this.board = new Board(boardSize, snakes, ladders); | |
this.dice = new Dice(); | |
this.winner = null; | |
} | |
playTurn(player) { | |
const diceRoll = this.dice.roll(); | |
player.move(diceRoll, this.board); | |
if (this.board.isWinningPosition(player.position)) { | |
console.log(`π ${player.name} wins the game! π`); | |
this.winner = player; | |
} | |
} | |
start() { | |
console.log("π² Starting Snake and Ladder Game! π²"); | |
let turn = 0; | |
while (!this.winner) { | |
this.playTurn(this.players[turn % this.players.length]); | |
turn++; | |
} | |
} | |
} | |
// Example Game | |
const snakes = [[14, 7], [31, 19], [37, 3], [46, 23], [62, 18], [74, 53], [87, 36], [94, 71], [98, 79]]; | |
const ladders = [[4, 14], [9, 31], [20, 38], [28, 84], [40, 59], [51, 67], [63, 81], [71, 91]]; | |
const players = ["Alice", "Bob"]; | |
const game = new SnakeLadderGame(players, 100, snakes, ladders); | |
game.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment