@@ -86,23 +86,25 @@ object Game {
86
86
87
87
case class State (
88
88
history : List [Squares ],
89
+ stepNumber : Int ,
89
90
xIsNext : Boolean ,
90
91
)
91
92
92
93
class Backend (bs : BackendScope [Unit , State ]) {
93
94
94
95
def render (state : State ) = {
95
- val current = state.history.last
96
+ val current = state.history(state.stepNumber)
96
97
val status = calculateWinner(current) match {
97
98
case Some (s) => " Winner is " + s
98
99
case None => " Next player: " + {if (state.xIsNext) " X" else " O" }
99
100
}
100
- val moves = state.history.zipWithIndex.map{
101
+ val moves = state.history.slice( 0 , state.stepNumber). zipWithIndex.map{
101
102
case (step, move) => {
102
103
val desc = if (move > 0 ) " Go to move #%s" .format(move) else " Go to game start"
103
104
< .li(
105
+ ^ .key := move,
104
106
< .button(
105
- ^ .onClick --> Callback { /* TODO */ } ,
107
+ ^ .onClick --> jumpTo(move) ,
106
108
desc
107
109
)
108
110
)
@@ -147,21 +149,30 @@ object Game {
147
149
148
150
def handleClick (i : Int ) = bs.modState(
149
151
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) {
152
155
s
153
156
} else {
154
157
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
157
161
)
158
162
}
159
163
}
160
164
)
165
+
166
+ def jumpTo (step : Int ) = bs.modState(
167
+ s => s.copy(
168
+ stepNumber= step,
169
+ xIsNext= step % 2 == 0 ,
170
+ )
171
+ )
161
172
}
162
173
163
174
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 ))
165
176
.renderBackend[Backend ]
166
177
.build
167
178
0 commit comments