diff --git a/src/mancala.ts b/src/mancala.ts index 5a8ea23..7eea963 100644 --- a/src/mancala.ts +++ b/src/mancala.ts @@ -65,6 +65,7 @@ export class Game { eachHole.ballCount++ } }) + hole.ballCount = holeEndBallCount console.log((stopIndex)); console.log(checkIsOwnHole(stopIndex, circleSize)); @@ -73,7 +74,7 @@ export class Game { //check if it was 0 before if (stopHole.ballCount == 1) { const ownStore = getOwnStore(circle) - const opponentHole = getOpponentHoleByIndex(stopIndex, circle) + const opponentHole = getOpponentHoleByIndex(stopIndex%16, circle) if (opponentHole.ballCount > 0) { ownStore.ballCount++ @@ -125,9 +126,31 @@ export class Game { } } + //todo throw expection + public getPlayerKeyByName(key: "player1" | "player2"): string { + if (this.player1 == key) { + return "player1" + } else { + return "player2" + } + } + public checkGameTurn(user: string): boolean { return this.getPlayerNameByKey(user) == this.turn } + + public getWonPlayer() : string | undefined { + const player1BallCount = this.board.player1Store.ballCount + const player2BallCount = this.board.player2Store.ballCount + + if(player1BallCount < player2BallCount){ + return this.getPlayerKeyByName("player1") + }else if(player1BallCount > player2BallCount) { + return this.getPlayerKeyByName("player2") + }else{ + return undefined + } + } } export function createGame(player1: string, player2: string) { @@ -182,6 +205,14 @@ export class Board { public player2Circle(): Array { return [...this.player2Holes, this.player2Store, ...this.player1Holes, this.player1Store] } + + public getBallCount(holes : Array ) : number { + let ballCount = 0 + for (let hole of holes) { + ballCount += hole.ballCount; + } + return ballCount + } } function iterateHoles(holes: Array, start: number, stop: number, callback: (hole: Hole, index: number) => void) { diff --git a/tests/mancala.test.ts b/tests/mancala.test.ts index dc74109..1f3ed69 100644 --- a/tests/mancala.test.ts +++ b/tests/mancala.test.ts @@ -33,4 +33,18 @@ describe('mancala', function () { expect(game.board.player1Holes[game.board.player1Holes.length / 2].ballCount).toBe(0) expect(game.state).toBe("ended") }) + + it('game end won user 1', function () { + const board = new Board( + [new Hole(0), new Hole(0), new Hole(0), new Hole(0), new Hole(4), new Hole(4)], + [new Hole(0), new Hole(0), new Hole(0), new Hole(0), new Hole(0), new Hole(1)], + new Store(0), new Store(0)) + const game = new Game(player1, player2, board, "player2", "playing") + game.moveByIndex(5, "player2") + expect(game.turn).toBe("player2") + expect(game.board.player2Store.ballCount).toBe(9) + expect(game.board.player1Holes[game.board.player1Holes.length / 2].ballCount).toBe(0) + expect(game.state).toBe("ended") + expect(game.getWonPlayer()).toBe("player2") + }) }) \ No newline at end of file