11import { get } from "svelte/store" ;
2- import { printCells } from "./grid.ts" ;
32import type { Context , StateSnapshot } from "./public-types.ts" ;
43
54// History については、 `docs/history-stack.png` を参照のこと
@@ -15,22 +14,21 @@ export function record(cx: Context) {
1514 return prev ;
1615 } ) ;
1716}
17+
1818export function undo ( cx : Context ) : { x : number ; y : number } | undefined {
1919 const history = get ( cx . history ) ;
20- if ( history . index <= 0 ) return undefined ;
2120 const grid = cx . grid ;
22- history . index -- ;
23- const snapshot = history . tree [ history . index ] ;
2421
25- printCells ( snapshot . game . cells , "undo" ) ;
26- if ( history . index === 0 ) {
27- console . log ( "undo to last" , snapshot ) ;
28- }
22+ // {*記録* -> Action -> *記録*} -> 移動 -> {*記録* -> Action -> *記録*}
23+ // ^ Snapshot はここのを使いたい
24+ // ^ index は整合性のためここに置きたい ^ 最新の index はここ
25+ const snapshot = history . tree [ history . index - 1 ] ;
26+ if ( ! snapshot ) return undefined ; // ゲームが開始する前
27+ history . index -= 2 ;
2928
3029 // 状態を巻き戻す
3130 cx . state . set ( snapshot . game ) ;
3231 grid . diffAndUpdateTo ( cx , snapshot . game . cells ) ;
33-
3432 cx . dynamic . player . x = snapshot . playerX ;
3533 cx . dynamic . player . y = snapshot . playerY ;
3634
@@ -43,17 +41,23 @@ export function undo(cx: Context): { x: number; y: number } | undefined {
4341}
4442
4543export function redo ( cx : Context ) : { x : number ; y : number } | undefined {
46- // TODO: プレイヤーの座標の履歴を「いい感じ」にするため、 history を二重管理する
4744 const history = get ( cx . history ) ;
48- if ( history . index >= history . tree . length - 1 ) return undefined ;
49- history . index ++ ; // redo は、巻き戻し前の index
50- const snapshot = history . tree [ history . index ] ;
51- printCells ( snapshot . game . cells , "redo" ) ;
45+
46+ // {*記録* -> Action -> *記録*} -> 移動 -> {*記録* -> Action -> *記録*}
47+ // ^ Snapshot はここのを使いたい
48+ // ^ 現在の index はここ ^ 最新の index はここ
49+ // ちなみにこの実装だと ctrl + Z でスタート地点に戻れない
50+ const snapshot = history . tree [ history . index + 2 ] ;
51+ if ( ! snapshot ) return undefined ; // 最新の先;
52+ history . index += 2 ;
53+
5254 const grid = cx . grid ;
5355
5456 // 状態を巻き戻す
5557 cx . state . set ( snapshot . game ) ;
5658 grid . diffAndUpdateTo ( cx , snapshot . game . cells ) ;
59+ cx . dynamic . player . x = snapshot . playerX ;
60+ cx . dynamic . player . y = snapshot . playerY ;
5761
5862 console . log ( `history: ${ history . index } / ${ history . tree . length - 1 } ` ) ;
5963 cx . history . set ( history ) ;
0 commit comments