Skip to content

Commit ed0d2c7

Browse files
committed
Implementing Time Travel
1 parent 7d761dc commit ed0d2c7

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

react_learn/src/main/scala/tutorial/webapp/TutorialApp.scala

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -86,23 +86,25 @@ object Game {
8686

8787
case class State(
8888
history: List[Squares],
89+
stepNumber: Int,
8990
xIsNext: Boolean,
9091
)
9192

9293
class Backend(bs: BackendScope[Unit, State]) {
9394

9495
def render(state: State) = {
95-
val current = state.history.last
96+
val current = state.history(state.stepNumber)
9697
val status = calculateWinner(current) match {
9798
case Some(s) => "Winner is " + s
9899
case None => "Next player: " + {if (state.xIsNext) "X" else "O"}
99100
}
100-
val moves = state.history.zipWithIndex.map{
101+
val moves = state.history.slice(0, state.stepNumber).zipWithIndex.map{
101102
case (step, move) => {
102103
val desc = if (move > 0) "Go to move #%s".format(move) else "Go to game start"
103104
<.li(
105+
^.key := move,
104106
<.button(
105-
^.onClick --> Callback{/* TODO */},
107+
^.onClick --> jumpTo(move),
106108
desc
107109
)
108110
)
@@ -147,21 +149,30 @@ object Game {
147149

148150
def handleClick(i: Int) = bs.modState(
149151
s => {
150-
val latest = s.history.last
151-
if (!latest(i).isEmpty || !calculateWinner(latest).isEmpty) {
152+
val history = s.history.slice(0, s.stepNumber+1)
153+
val current = history.last
154+
if (!current(i).isEmpty || !calculateWinner(current).isEmpty) {
152155
s
153156
} else {
154157
s.copy(
155-
history=s.history:+latest.updated(i, Some(if (s.xIsNext) "X" else "O")),
156-
xIsNext= !s.xIsNext
158+
history=history:+current.updated(i, Some(if (s.xIsNext) "X" else "O")),
159+
xIsNext= !s.xIsNext,
160+
stepNumber=history.size
157161
)
158162
}
159163
}
160164
)
165+
166+
def jumpTo(step: Int) = bs.modState(
167+
s => s.copy(
168+
stepNumber=step,
169+
xIsNext=step % 2 == 0,
170+
)
171+
)
161172
}
162173

163174
val component = ScalaComponent.builder[Unit]("Board")
164-
.initialState(State(List(List.fill(9)(None)), true))
175+
.initialState(State(List(List.fill(9)(None)), 0, true))
165176
.renderBackend[Backend]
166177
.build
167178

0 commit comments

Comments
 (0)