-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
snake_and_ladder_game.go
53 lines (44 loc) · 1.17 KB
/
snake_and_ladder_game.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package snakeandladdergame
import "fmt"
type SnakeAndLadderGame struct {
Board *Board
Players []*Player
Dice *Dice
CurrentPlayerIdx int
}
func NewSnakeAndLadderGame(playerNames []string) *SnakeAndLadderGame {
game := &SnakeAndLadderGame{
Board: NewBoard(),
Dice: NewDice(),
Players: []*Player{},
CurrentPlayerIdx: 0,
}
for _, name := range playerNames {
game.Players = append(game.Players, NewPlayer(name))
}
return game
}
func (g *SnakeAndLadderGame) Play() {
for !g.isGameOver() {
player := g.Players[g.CurrentPlayerIdx]
roll := g.Dice.Roll()
newPosition := player.Position + roll
if newPosition <= g.Board.Size {
player.Position = g.Board.GetNewPosition(newPosition)
fmt.Printf("%s rolled a %d and moved to position %d\n", player.Name, roll, player.Position)
}
if player.Position == g.Board.Size {
fmt.Printf("%s wins!\n", player.Name)
break
}
g.CurrentPlayerIdx = (g.CurrentPlayerIdx + 1) % len(g.Players)
}
}
func (g *SnakeAndLadderGame) isGameOver() bool {
for _, player := range g.Players {
if player.Position == g.Board.Size {
return true
}
}
return false
}