Skip to content

Instantly share code, notes, and snippets.

@sudip-mondal-2002
Last active March 28, 2023 17:22
Show Gist options
  • Save sudip-mondal-2002/fcb8fe9c56d4c66813adc0d9d1a22fd3 to your computer and use it in GitHub Desktop.
Save sudip-mondal-2002/fcb8fe9c56d4c66813adc0d9d1a22fd3 to your computer and use it in GitHub Desktop.
Low level Design of Snake Game
class Dice {
noDice: number;
min: number = 1;
max: number = 6;
constructor(pNoDice: number = 1) {
this.noDice = pNoDice
}
rollDice(): number {
let diceUsed = 0
let ret = 0
while (diceUsed < this.noDice) {
ret += Math.floor(Math.random() * this.max) + this.min;
diceUsed++
}
return ret
}
}
class Player {
name: string;
position: number = 0;
id: number;
static lastId: number = 0
constructor(name: string) {
this.name = name
Player.lastId++
this.id = Player.lastId
}
}
class Jump {
end: number;
constructor(pEnd: number) {
this.end = pEnd
}
}
class Cell {
jump: Jump | null
constructor(pJump: Jump | null = null) {
this.jump = pJump
}
}
class Board {
cells: Cell[]
constructor(size: number) {
this.cells = (new Array<Cell>(size))
for (let i=0; i<size; i++){
this.cells[i] = new Cell()
}
}
addJump(pStart: number, pEnd: number) {
if (pStart === this.cells.length - 1) {
throw Error("Can't add jumps at last position")
}
this.cells[pStart].jump = new Jump(pEnd)
}
addJumps(jumps: [pStart: number, pEnd: number][]) {
jumps.forEach((jump) => {
this.addJump(jump[0], jump[1])
})
}
}
class GameManager {
private board: Board
private dice: Dice
private players: Player[] = []
winner: Player | null = null
constructor() {
this.dice = new Dice(1)
this.board = new Board(100)
this.board.addJumps([
[6, 10],
[36, 95],
[75, 81],
[35, 13],
[64, 22],
[98, 3]
])
}
addPlayer(name: string) {
this.players.push(new Player(name))
}
playNextMove() {
const currentPlayer = this.players[0]
this.players = [...this.players.slice(1), currentPlayer]
const move = this.dice.rollDice()
if (currentPlayer.position + move < this.board.cells.length) {
currentPlayer.position += move
const jump = this.board.cells[currentPlayer.position]?.jump
if (jump) {
currentPlayer.position = jump.end
}
if (currentPlayer.position === this.board.cells.length - 1) {
this.winner = currentPlayer
}
}
}
}
const client = () => {
const gameManager: GameManager = new GameManager()
gameManager.addPlayer("Sudip")
gameManager.addPlayer("Player1")
gameManager.addPlayer("Player2")
gameManager.addPlayer("Player3")
while (!gameManager.winner) {
gameManager.playNextMove()
}
console.log(`${gameManager.winner.name} Wins!!`)
}
client()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment