-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
281 lines (233 loc) · 7.99 KB
/
index.js
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
Original URL from React tutorial: https://reactjs.org/tutorial/tutorial.html
This version was enhanced by Jorge Garifuna <[email protected]> on 1/1/18 with the following:
1) Display the location for each move in the format (col, row) in the move history list.
2) Bold the currently selected item in the move list.
3) Rewrite Board to use two loops to make the squares instead of hardcoding them.
4) Add a toggle button that lets you sort the moves in either ascending or descending order.
5) When someone wins, highlight the three squares that caused the win.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import classNames from 'classnames';
function Square(props) {
// CSS classes to include in button
let cssClass = classNames({
'square': true,
'square_current' : (props.currentButtonNumber === props.currentButtonIndex),
'square_winner': ((props.winnerButtons[1] && props.winnerButtons.indexOf(props.currentButtonIndex) !== -1) ? true: false)
});
return (
<button className={cssClass} onClick={props.onClick}>
{props.value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
currentButtonNumber={this.props.currentButtonNumber}
winnerButtons={this.props.winnerButtons}
currentButtonIndex={i}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
let lStrBoardSquares = '';
const numberOfSquares = Array(9).fill(null);
lStrBoardSquares = numberOfSquares.map((item, i) => {
let lStrData = null;
if ((i + 1) % 3 === 0) { // start a new row
lStrData = <br />
}
const lStrSquare = this.renderSquare(i);
return (<span key={i}>{lStrSquare}{lStrData}</span>)
})
return (
<div>
{lStrBoardSquares}
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
position: null,
buttonNumber: null,
winnerButtons: Array(3).fill(null)
}
],
stepNumber: 0,
xIsNext: true,
sortOrder: 0 // 0 asc, 1 desc
};
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
const position = calculateBoardPosition(i);
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
const winner = calculateWinner(squares); // check for winner, so we can highlight winner buttons
let winnerButtons = Array(3).fill(null);
if (winner) {
if (winner) { // get the winner buttons
winnerButtons = getWinnerButtons(squares);
}
}
this.setState({
history: history.concat([
{
squares: squares,
position: position,
buttonNumber: i,
winnerButtons: winnerButtons.slice()
}
]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0
});
}
/*
Sets state to trigger steps sorting
@author: Jorge Garifuna <[email protected]>
@date 1/1/18
@return void
*/
sortSteps() { // set state to sort steps
const currentSortOrder = this.state.sortOrder;
this.setState({
sortOrder: Math.abs(1 - currentSortOrder) // 0 = ascesding, 1 = descending
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const currentSortOrder = this.state.sortOrder;
const numberOfSteps = history.length;
let sortedHistory = history.slice();
if (currentSortOrder) { // reverse history if desceding order is selected
sortedHistory.reverse();
}
const moves = sortedHistory.map((step, move) => {
// reverse move if descending order is selected
move = currentSortOrder ? (numberOfSteps - move - 1) : move;
const desc = move ? 'Go to move #' + move + step.position : 'Go to game start';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
let status;
if (winner) {
status = "Winner: " + winner;
} else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
let sortAction;
if (numberOfSteps > 1) { // show steps action button
let sortLabel = this.state.sortOrder ? '\u2191' : '\u2193'; // up and down entities
sortAction = <button onClick={() => this.sortSteps()}>Sort Steps {sortLabel}</button>
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
currentButtonNumber={current.buttonNumber}
winnerButtons={current.winnerButtons}
onClick={i => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<div className="sort-action">{sortAction}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(<Game />, document.getElementById("root"));
function getLines() {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
return lines;
}
/*
Calculates board position
@author: Jorge Garifuna <[email protected]>
@date 1/1/18
@param int squareNumber
@return string | null
*/
function calculateBoardPosition(squareNumber) {
const lines = getLines();
for(let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squareNumber === a){
return ' (row ' + (i + 1) +', column 1)';
} else if (squareNumber === b){
return ' (row ' + (i + 1) +', column 2)';
} else if (squareNumber === c){
return ' (row ' + (i + 1) +', column 3)';
}
}
return null;
}
/*
Obtains the winner buttons numbers in an array.
@author: Jorge Garifuna <[email protected]>
@date 1/1/18
@param array squares
@return array
*/
function getWinnerButtons(squares) {
const lines = getLines();
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return lines[i];
}
}
return Array(3).fill(null);
}
function calculateWinner(squares) {
const lines = getLines();
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}