Skip to content

Commit 624f781

Browse files
committed
adding time travel function
1 parent caa100e commit 624f781

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

public/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
name="description"
1010
content="Web site created using create-react-app"
1111
/>
12-
<link rel="apple-touch-icon" href="logo192.png" />
12+
<link rel="apple-touch-icon" href="" />
1313
<!--
1414
manifest.json provides metadata used when your web app is installed on a
1515
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/

src/index.js

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,13 @@ class Game extends React.Component {
105105
history: [{
106106
squares: Array(9).fill(null)
107107
}],
108-
xIsNext: true
108+
xIsNext: true,
109+
stepNumber: 0
109110
};
110111
}
111112

112113
handleClick(i) {
113-
const history = this.state.history;
114+
const history = this.state.history.slice(0, this.state.stepNumber + 1);
114115
const current = history[history.length - 1];
115116
const squares = current.squares.slice();
116117

@@ -123,15 +124,32 @@ class Game extends React.Component {
123124
history: history.concat([{
124125
squares: squares,
125126
}]),
127+
stepNumber: history.length,
126128
xIsNext: !this.state.xIsNext,
127129
});
128130
}
129131

132+
jumpTo(step) {
133+
this.setState({
134+
stepNumber: step,
135+
xIsNext: (step % 2) === 0,
136+
})
137+
}
138+
130139
render() {
131140
const history = this.state.history;
132-
const current = history[history.length - 1];
141+
const current = history[this.state.stepNumber];
133142
const winner = calculateWinner(current.squares);
134143

144+
const moves = history.map((step, move) => {
145+
const desc = move ? 'Go to move #' + move : 'Go to game start';
146+
return (
147+
<li key={move}>
148+
<button onClick={() => this.jumpTo(move)}> {desc} </button>
149+
</li>
150+
)
151+
})
152+
135153
let status;
136154
if (winner) {
137155
status = 'Winner: ' + winner;
@@ -148,8 +166,8 @@ class Game extends React.Component {
148166
/>
149167
</div>
150168
<div className="game-info">
151-
<div>{/* status */}</div>
152-
<ol>{/* TODO */}</ol>
169+
<div>{status}</div>
170+
<ol>{moves}</ol>
153171
</div>
154172
</div>
155173
);

0 commit comments

Comments
 (0)