Skip to content

Instantly share code, notes, and snippets.

@morintd
Created March 14, 2024 18:13
Show Gist options
  • Save morintd/00c707c1d979a181adaa07a81e3236ff to your computer and use it in GitHub Desktop.
Save morintd/00c707c1d979a181adaa07a81e3236ff to your computer and use it in GitHub Desktop.
import { Response, NextFunction } from "express";
import { JumpTo } from "./use-cases/jump-to.use-case";
import { Play } from "./use-cases/play.use-case";
import { Initialize } from "./use-cases/initialize.use-case";
import {
CellAlreadyTakenException,
StepDoesNotExistException,
} from "./exceptions";
import { BadRequestException } from "../common/exceptions/bad-request.exception";
export class TicTacToeController {
constructor(
private initialize: Initialize,
private play: Play,
private jumpTo: JumpTo
) {}
handleInitialize(res: Response) {
const game = this.initialize.execute();
res.status(201).json({
moves: this.getMoves(game.history),
status: this.getStatus(game.winner, game.xIsNext),
squares: game.history[game.step],
});
}
handlePlay(res: Response, next: NextFunction, step: number, square: number) {
try {
const game = this.play.execute({ step, square });
res.status(201).json({
moves: this.getMoves(game.history),
status: this.getStatus(game.winner, game.xIsNext),
squares: game.history[game.step],
});
} catch (e) {
if (e instanceof StepDoesNotExistException) {
return next(
new BadRequestException({
error: "step does not exist",
})
);
}
if (e instanceof CellAlreadyTakenException) {
return next(
new BadRequestException({
error: "cell already taken",
})
);
}
next(e);
}
}
handleJumpTo(res: Response, next: NextFunction, step: number) {
try {
const game = this.jumpTo.execute({ step });
res.status(201).json({
moves: this.getMoves(game.history),
status: this.getStatus(game.winner, game.xIsNext),
squares: game.history[game.step],
});
} catch (e) {
if (e instanceof StepDoesNotExistException) {
return next(
new BadRequestException({
error: "step does not exist",
})
);
}
next(e);
}
}
private getMoves(history: string[][]) {
const moves = history.map((_, move: number) => {
return {
move,
description: move > 0 ? "Go to move #" + move : "Go to game start",
};
});
return moves;
}
private getStatus(winner: string | null, xIsNext: boolean) {
const status = winner
? winner === "draw"
? "Draw"
: "Winner: " + winner
: "Next player: " + (xIsNext ? "X" : "O");
return status;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment