1
|
|
|
/** |
2
|
|
|
* A module for the Nim game. |
3
|
|
|
* |
4
|
|
|
* @module |
5
|
|
|
*/ |
6
|
|
|
"use strict"; |
7
|
|
|
|
8
|
|
|
class Nim { |
9
|
|
|
/** |
10
|
|
|
* @constructor |
11
|
|
|
* |
12
|
|
|
* @param {object} options - Configure by sending options. |
13
|
|
|
*/ |
14
|
|
|
constructor(options = {}) { |
15
|
20 |
|
this.piles = options.piles || 3; |
16
|
20 |
|
this.matches = new Array(0); |
17
|
20 |
|
for (var i = 0; i < this.piles; i++) { |
18
|
60 |
|
var matches = 2*i+1; |
19
|
|
|
|
20
|
60 |
|
this.matches.push(matches); |
21
|
|
|
} |
22
|
|
|
|
23
|
20 |
|
this.playerOne = options.nameOfPlayerOne || "Player one"; |
24
|
20 |
|
this.playerTwo = null; |
25
|
|
|
|
26
|
20 |
|
this.playerInTurn = this.playerOne; |
27
|
20 |
|
this.winner = null; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
|
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Add player two to the game. |
34
|
|
|
* |
35
|
|
|
* @param {string} playerName - The name of the player. |
36
|
|
|
* |
37
|
|
|
* @returns {boolean} true |
38
|
|
|
*/ |
39
|
|
|
addPlayerTwo(playerName) { |
40
|
4 |
|
this.playerTwo = playerName; |
41
|
4 |
|
return true; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
|
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Change the player in turn. |
48
|
|
|
* |
49
|
|
|
* @returns {string} Which players turn it is. |
50
|
|
|
*/ |
51
|
|
|
changePlayer() { |
52
|
4 |
|
if (this.playerInTurn == this.playerOne) { |
53
|
2 |
|
this.playerInTurn = this.playerTwo; |
54
|
|
|
} else { |
55
|
2 |
|
this.playerInTurn = this.playerOne; |
56
|
|
|
} |
57
|
4 |
|
return `It's ${this.playerInTurn} drawing matches!`; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
|
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Remove matches from a pile. |
65
|
|
|
* |
66
|
|
|
* @param {integer} pile - The pile where to remove the matches. |
67
|
|
|
* @param {integer} matches - The number of matches to remove from pile. |
68
|
|
|
* |
69
|
|
|
* @returns {boolean} - true if possible to remove, false otherwise. |
70
|
|
|
*/ |
71
|
|
|
removeMatches(pile, matches) { |
72
|
12 |
|
if (pile <= this.piles && pile > 0) { |
73
|
10 |
|
if (this.matches[pile-1] >= matches) { |
74
|
8 |
|
this.matches[pile-1] = this.matches[pile-1] - matches; |
75
|
8 |
|
return true; |
76
|
|
|
} else { |
77
|
2 |
|
return false; |
78
|
|
|
} |
79
|
|
|
} else { |
80
|
2 |
|
return false; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Check if there is a winner. |
88
|
|
|
* |
89
|
|
|
* @returns {boolean} True if there is a winner, false otherwise. |
90
|
|
|
*/ |
91
|
|
|
checkForWinner() { |
92
|
4 |
|
var matchesLeft = null; |
93
|
|
|
|
94
|
4 |
|
for (var i = 0; i < this.matches.length; i++) { |
95
|
12 |
|
matchesLeft += this.matches[i]; |
96
|
|
|
} |
97
|
4 |
|
if (matchesLeft == 0) { |
98
|
2 |
|
return true; |
99
|
|
|
} else { |
100
|
2 |
|
return false; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
// Export module |
106
|
|
|
module.exports = Nim; |
107
|
|
|
|