-
Notifications
You must be signed in to change notification settings - Fork 0
/
587136ba2eefcb92a9000027.ts
148 lines (131 loc) · 2.91 KB
/
587136ba2eefcb92a9000027.ts
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Solution for the 587136ba2eefcb92a9000027 problem in CodeWars: Snakes and Ladders (5 kyu)
export class SnakesLadders {
private players: Player[] = [new Player(1), new Player(2)]
private currentPlayer: 1 | 2 = 1
private readonly jumps: Jump[] = [
{
value: 2,
jumpValue: 38
},
{
value: 7,
jumpValue: 14
},
{
value: 8,
jumpValue: 31
},
{
value: 15,
jumpValue: 26
},
{
value: 16,
jumpValue: 6
},
{
value: 21,
jumpValue: 42
},
{
value: 28,
jumpValue: 84
},
{
value: 36,
jumpValue: 44
},
{
value: 46,
jumpValue: 25
},
{
value: 49,
jumpValue: 11
},
{
value: 51,
jumpValue: 67
},
{
value: 62,
jumpValue: 19
},
{
value: 64,
jumpValue: 60
},
{
value: 71,
jumpValue: 91
},
{
value: 74,
jumpValue: 53
},
{
value: 78,
jumpValue: 98
},
{
value: 87,
jumpValue: 94
},
{
value: 89,
jumpValue: 68
},
{
value: 92,
jumpValue: 88
},
{
value: 95,
jumpValue: 75
},
{
value: 99,
jumpValue: 80
}
]
private gameOver: boolean = false
play(die1: number, die2: number): string {
if(this.gameOver){
return 'Game over!'
}
const player = this.players.find(player => player.id === this.currentPlayer)
if(!player){
throw new Error('Player not found')
}
player.position = this.move(player.position + die1 + die2)
console.log(player)
if(die1 !== die2){
this.switchPlayer()
}
if(player.position === 100){
this.gameOver = true
return `Player ${player.id} Wins!`
}
return `Player ${player.id} is on square ${player.position}`
}
private move(position: number): number {
const jump = this.jumps.find(jump => jump.value === position)
const value = jump ? jump.jumpValue : position
return value > 100 ? this.move(100 - (value - 100)) : value
}
private switchPlayer(){
this.currentPlayer = this.currentPlayer === 1 ? 2 : 1
}
}
export interface Jump {
value: number
jumpValue: number
}
export class Player {
id: 1 | 2
position: number
constructor(id: 1 | 2){
this.id = id
this.position = 0
}
}