-
-
Save morintd/9612cb0670002fc873a3c94e523c841c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useState } from "react"; | |
import { GameDomainModel } from "./game.domain-model"; | |
import { JumpTo } from "./use-cases/jump-to.use-case"; | |
import { Play } from "./use-cases/play.use-case"; | |
export function useGameController(defaultGame: GameDomainModel.GameState) { | |
const [currentGame, setCurrentGame] = | |
useState<GameDomainModel.GameState>(defaultGame); | |
const jumpTo = new JumpTo(); | |
const play = new Play(); | |
const onPlay = useCallback( | |
(square: number) => { | |
play | |
.execute({ step: currentGame.step, square }) | |
.then((game) => setCurrentGame(game)); | |
}, | |
[currentGame.step, play] | |
); | |
const onJumpTo = useCallback( | |
(step: number) => { | |
jumpTo.execute({ step }).then((game) => setCurrentGame(game)); | |
}, | |
[jumpTo] | |
); | |
const moves = currentGame.history.map((_, move: number) => { | |
return { | |
move, | |
description: move > 0 ? "Go to move #" + move : "Go to game start", | |
}; | |
}); | |
const status = currentGame.winner | |
? currentGame.winner === "draw" | |
? "Draw" | |
: "Winner: " + currentGame.winner | |
: "Next player: " + (currentGame.xIsNext ? "X" : "O"); | |
return { | |
squares: currentGame.history[currentGame.step], | |
status, | |
moves, | |
onPlay, | |
onJumpTo, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment