Skip to content

Instantly share code, notes, and snippets.

@morintd
Created March 10, 2024 21:20
Show Gist options
  • Save morintd/9612cb0670002fc873a3c94e523c841c to your computer and use it in GitHub Desktop.
Save morintd/9612cb0670002fc873a3c94e523c841c to your computer and use it in GitHub Desktop.
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