|
| 1 | +import { SHIP_DATA, Ships } from '@/ps/games/battleship/constants'; |
| 2 | +import { render, renderMove, renderSelection, renderSummary } from '@/ps/games/battleship/render'; |
| 3 | +import { type BaseContext, BaseGame } from '@/ps/games/game'; |
| 4 | +import { createGrid } from '@/ps/games/utils'; |
| 5 | +import { ChatError } from '@/utils/chatError'; |
| 6 | +import { type Point, parsePointA1, pointToA1, rangePoints, sameRowOrCol, taxicab } from '@/utils/grid'; |
| 7 | + |
| 8 | +import type { ToTranslate, TranslatedText } from '@/i18n/types'; |
| 9 | +import type { ShipType } from '@/ps/games/battleship/constants'; |
| 10 | +import type { Log } from '@/ps/games/battleship/logs'; |
| 11 | +import type { RenderCtx, SelectionInProgressState, ShipBoard, State, Turn, WinCtx } from '@/ps/games/battleship/types'; |
| 12 | +import type { ActionResponse, BaseState, EndType, Player } from '@/ps/games/types'; |
| 13 | +import type { User } from 'ps-client'; |
| 14 | +import type { ReactElement } from 'react'; |
| 15 | + |
| 16 | +export { meta } from '@/ps/games/battleship/meta'; |
| 17 | + |
| 18 | +const HITS_TO_WIN = Ships.map(ship => ship.size).sum(); |
| 19 | + |
| 20 | +export class Battleship extends BaseGame<State> { |
| 21 | + winCtx?: WinCtx | { type: EndType }; |
| 22 | + constructor(ctx: BaseContext) { |
| 23 | + super(ctx); |
| 24 | + super.persist(ctx); |
| 25 | + |
| 26 | + if (ctx.backup) return; |
| 27 | + this.state.ready = { A: false, B: false }; |
| 28 | + this.state.allReady = false; |
| 29 | + this.state.board = { |
| 30 | + ships: { A: createGrid(10, 10, () => null), B: createGrid(10, 10, () => null) }, |
| 31 | + attacks: { A: createGrid(10, 10, () => null), B: createGrid(10, 10, () => null) }, |
| 32 | + }; |
| 33 | + } |
| 34 | + |
| 35 | + onAfterAddPlayer(player: Player): void { |
| 36 | + this.update(player.id); |
| 37 | + } |
| 38 | + onReplacePlayer(_turn: BaseState['turn'], withPlayer: User): ActionResponse { |
| 39 | + this.update(withPlayer.id); |
| 40 | + return { success: true, data: null }; |
| 41 | + } |
| 42 | + |
| 43 | + onStart(): ActionResponse { |
| 44 | + this.turns.shuffle(this.prng); |
| 45 | + return { success: true, data: null }; |
| 46 | + } |
| 47 | + onAfterStart() { |
| 48 | + this.clearTimer(); |
| 49 | + } |
| 50 | + |
| 51 | + action(user: User, input: string) { |
| 52 | + const [action, ctx] = input.lazySplit(' ', 1); |
| 53 | + const player = this.getPlayer(user)! as Player & { turn: Turn }; |
| 54 | + switch (action) { |
| 55 | + case 'set': { |
| 56 | + if (this.state.ready[player.turn] === true) throw new ChatError("Hi you've already set your ships!" as ToTranslate); |
| 57 | + const set = ctx.split('|').map(coords => coords.split('-').map(parsePointA1)); |
| 58 | + const input = set.flatMap(row => row.map(point => (point ? pointToA1(point) : ''))); |
| 59 | + try { |
| 60 | + this.state.ready[player.turn] = { ...this.validateShipPositions(set), input }; |
| 61 | + } catch (err) { |
| 62 | + if (err instanceof ChatError) { |
| 63 | + this.state.ready[player.turn] = { type: 'invalid', input, message: err.message }; |
| 64 | + this.update(player.id); |
| 65 | + } else throw err; |
| 66 | + } |
| 67 | + this.update(player.id); |
| 68 | + this.backup(); |
| 69 | + break; |
| 70 | + } |
| 71 | + case 'confirm-set': { |
| 72 | + const currentSet = this.state.ready[player.turn]; |
| 73 | + if (currentSet === true) throw new ChatError("Hi you've already set your ships!" as ToTranslate); |
| 74 | + if (!currentSet || currentSet?.type === 'invalid') throw new ChatError('Set your ships first -_-' as ToTranslate); |
| 75 | + this.state.board.ships[player.turn] = currentSet.board; |
| 76 | + this.state.ready[player.turn] = true; |
| 77 | + const logEntry: Log = { action: 'set', ctx: currentSet.input, time: new Date(), turn: player.turn }; |
| 78 | + this.log.push(logEntry); |
| 79 | + this.room.sendHTML(...renderMove(logEntry, this)); |
| 80 | + if (this.state.ready.A === true && this.state.ready.B === true) { |
| 81 | + this.state.allReady = true; |
| 82 | + this.nextPlayer(); |
| 83 | + } else { |
| 84 | + this.update(player.id); |
| 85 | + } |
| 86 | + this.backup(); |
| 87 | + break; |
| 88 | + } |
| 89 | + case 'hit': { |
| 90 | + if (!this.state.allReady) this.throw('GAME.NOT_STARTED'); |
| 91 | + const targeted = parsePointA1(ctx); |
| 92 | + if (!targeted) this.throw(); |
| 93 | + const [x, y] = targeted; |
| 94 | + if (player.turn !== this.turn) this.throw(); |
| 95 | + const opponent = this.getNext(); |
| 96 | + let hit: ShipType | false | null; |
| 97 | + try { |
| 98 | + hit = this.state.board.ships[opponent].access([x, y]) ?? false; |
| 99 | + } catch { |
| 100 | + throw new ChatError('Invalid range given.' as ToTranslate); |
| 101 | + } |
| 102 | + this.state.board.attacks[player.turn][x][y] = hit; |
| 103 | + |
| 104 | + const point = pointToA1([x, y]); |
| 105 | + const logEntry: Log = { |
| 106 | + ...(hit |
| 107 | + ? { |
| 108 | + action: 'hit', |
| 109 | + ctx: { ship: SHIP_DATA[hit].name, point }, |
| 110 | + } |
| 111 | + : { |
| 112 | + action: 'miss', |
| 113 | + ctx: { point }, |
| 114 | + }), |
| 115 | + time: new Date(), |
| 116 | + turn: player.turn, |
| 117 | + }; |
| 118 | + this.log.push(logEntry); |
| 119 | + this.room.sendHTML(...renderMove(logEntry, this)); |
| 120 | + if (this.state.board.attacks[player.turn].flat().filter(hit => hit).length >= HITS_TO_WIN) { |
| 121 | + // Game ends |
| 122 | + this.winCtx = { type: 'win', winner: player, loser: this.players[opponent] }; |
| 123 | + this.end(); |
| 124 | + } |
| 125 | + this.nextPlayer(); |
| 126 | + this.update(); |
| 127 | + break; |
| 128 | + } |
| 129 | + default: |
| 130 | + this.throw(); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + onEnd(type?: EndType): TranslatedText { |
| 135 | + if (type) { |
| 136 | + this.winCtx = { type }; |
| 137 | + if (type === 'dq') return this.$T('GAME.ENDED_AUTOMATICALLY', { game: this.meta.name, id: this.id }); |
| 138 | + return this.$T('GAME.ENDED', { game: this.meta.name, id: this.id }); |
| 139 | + } |
| 140 | + if (this.winCtx && this.winCtx.type === 'win') |
| 141 | + return this.$T('GAME.WON_AGAINST', { |
| 142 | + winner: this.winCtx.winner.name, |
| 143 | + game: this.meta.name, |
| 144 | + loser: this.winCtx.loser.name, |
| 145 | + ctx: '', |
| 146 | + }); |
| 147 | + throw new Error(`winCtx not defined for BS - ${JSON.stringify(this.winCtx)}`); |
| 148 | + } |
| 149 | + |
| 150 | + render(side: Turn | null): ReactElement { |
| 151 | + if (side) { |
| 152 | + const readyState = this.state.ready[side]; |
| 153 | + if (readyState === false) return renderSelection.bind(this.renderCtx)(); |
| 154 | + if (readyState && typeof readyState !== 'boolean') return renderSelection.bind(this.renderCtx)(readyState); |
| 155 | + if (!this.state.allReady) |
| 156 | + return renderSelection.bind(this.renderCtx)({ type: 'valid', board: this.state.board.ships[side], input: [] }, true); |
| 157 | + } |
| 158 | + |
| 159 | + let ctx: RenderCtx; |
| 160 | + if (side) { |
| 161 | + ctx = { |
| 162 | + type: 'player', |
| 163 | + id: this.id, |
| 164 | + attack: this.state.board.attacks[side], |
| 165 | + defense: this.state.board.attacks[this.getNext(side)], |
| 166 | + actual: this.state.board.ships[side], |
| 167 | + active: side === this.turn, |
| 168 | + }; |
| 169 | + } else { |
| 170 | + ctx = { |
| 171 | + type: 'spectator', |
| 172 | + id: this.id, |
| 173 | + boards: this.state.board.attacks, |
| 174 | + players: this.players, |
| 175 | + }; |
| 176 | + } |
| 177 | + |
| 178 | + if (this.winCtx) { |
| 179 | + return renderSummary.bind(this.renderCtx)({ |
| 180 | + boards: this.state.board, |
| 181 | + players: this.players, |
| 182 | + winCtx: this.winCtx, |
| 183 | + }); |
| 184 | + } else if (side === this.turn) { |
| 185 | + ctx.header = this.$T('GAME.YOUR_TURN'); |
| 186 | + } else if (side) { |
| 187 | + ctx.header = this.$T('GAME.WAITING_FOR_OPPONENT'); |
| 188 | + ctx.dimHeader = true; |
| 189 | + } else if (this.turn) { |
| 190 | + const current = this.players[this.turn]; |
| 191 | + ctx.header = this.$T('GAME.WAITING_FOR_PLAYER', { player: current.name }); |
| 192 | + } |
| 193 | + |
| 194 | + return render.bind(this.renderCtx)(ctx as RenderCtx); |
| 195 | + } |
| 196 | + |
| 197 | + update(user?: string): void { |
| 198 | + if (!this.started) { |
| 199 | + if (user) { |
| 200 | + const asPlayer = this.getPlayer(user); |
| 201 | + if (!asPlayer) this.throw('GAME.IMPOSTOR_ALERT'); |
| 202 | + return this.sendHTML(asPlayer.id, this.render(asPlayer.turn as Turn)); |
| 203 | + } |
| 204 | + // TODO: Add ping to ps-client HTML opts |
| 205 | + Object.entries(this.players).forEach(([side, player]) => { |
| 206 | + if (!player.out) this.sendHTML(player.id, this.render(side as Turn)); |
| 207 | + }); |
| 208 | + return; |
| 209 | + } |
| 210 | + super.update(user); |
| 211 | + } |
| 212 | + |
| 213 | + validateShipPositions(input: (Point | null)[][]): Omit<SelectionInProgressState, 'input'> { |
| 214 | + if (input.length !== Ships.length) this.throw(); |
| 215 | + if (!input.every(points => points.length === 2 && !points.some(point => point === null))) this.throw(); |
| 216 | + const positions = Ships.map((ship, index) => ({ ship, from: input[index][0]!, to: input[index][1]! })); |
| 217 | + |
| 218 | + const occupied: Record<string, string> = {}; |
| 219 | + const shipBoard: ShipBoard = createGrid(10, 10, () => null); |
| 220 | + |
| 221 | + positions.forEach(({ ship, from, to }) => { |
| 222 | + if (!sameRowOrCol(from, to)) { |
| 223 | + throw new ChatError( |
| 224 | + `Cannot place ${ship.name} between given points ${pointToA1(from)} and ${pointToA1(to)} (not in line)` as ToTranslate |
| 225 | + ); |
| 226 | + } |
| 227 | + const givenSize = taxicab(from, to) + 1; |
| 228 | + if (givenSize !== ship.size) |
| 229 | + throw new ChatError(`${ship.name} has size ${ship.size} but you put it in ${givenSize} cells!` as ToTranslate); |
| 230 | + rangePoints(from, to).forEach(pointInRange => { |
| 231 | + const point = pointToA1(pointInRange); |
| 232 | + if (occupied[point]) { |
| 233 | + throw new ChatError(`${point} would be occupied by both ${ship.name} and ${occupied[point]}` as ToTranslate); |
| 234 | + } else { |
| 235 | + occupied[point] = ship.name; |
| 236 | + shipBoard[pointInRange[0]][pointInRange[1]] = ship.id; |
| 237 | + } |
| 238 | + }); |
| 239 | + }); |
| 240 | + |
| 241 | + // Ship positions should be valid now |
| 242 | + return { type: 'valid', board: shipBoard }; |
| 243 | + } |
| 244 | +} |
0 commit comments