From a75c2ec5addc65acd8bcb288b5fb89507bf8884c Mon Sep 17 00:00:00 2001 From: nea Date: Sun, 27 Nov 2022 21:32:34 +0100 Subject: allow ending games --- index.html | 17 +++++++++++++---- server.py | 7 +++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 7673b63..7a0c7c9 100644 --- a/index.html +++ b/index.html @@ -77,11 +77,11 @@ class Board { constructor(elem) { this.socket = new WebSocket(`${location.protocol.includes('s') ? 'wss' : 'ws'}://${window.location.host}/socket`) - this.exiting = false + this.ended = false this.boardState = {} this.lastMove = '' window.addEventListener('beforeunload', () => { - this.exiting = true + this.ended = false }) this.socket.addEventListener('message', ev => { const message = JSON.parse(ev.data) @@ -89,10 +89,12 @@ this.playerColor = message.player_color || this.playerColor this.boardState = parseFEN(message.board) this.lastMove = message.lastmove || '' + this.ended ||= message.event === 'game_over' + this.result = message.result this.synchronizeBoard() }) this.socket.addEventListener('close', () => { - if (!this.exiting) + if (!this.ended) document.getElementById('warn').classList.remove('invisible') }) let board = document.createElement("table") @@ -138,12 +140,19 @@ })) } + get canPlay() { + return this.isPlayerTurn && !this.ended + } + get isPlayerTurn() { return this.playerColor === this.boardState.turn } synchronizeBoard() { this.turnIndicator.innerHTML = `${capitalize(this.boardState.turn)}s turn` + if (this.ended) { + this.turnIndicator.innerHTML += `

${this.result}

` + } for (let field in this.fields) { const fieldDOM = this.fields[field] fieldDOM.innerHTML = "" @@ -153,7 +162,7 @@ piece.addEventListener("dragstart", ev => { ev.dataTransfer.setData("text", field) }) - piece.draggable = this.isPlayerTurn + piece.draggable = this.canPlay fieldDOM.appendChild(piece) } fieldDOM.classList.remove('lastmove') diff --git a/server.py b/server.py index 8a6b896..2c19026 100644 --- a/server.py +++ b/server.py @@ -66,6 +66,10 @@ async def handle_socket(request: web.Request): numscore = score.relative.score(mate_score=100000) return abs(numscore) + if board.is_game_over(): + await send_to_user(dict(event="game_over", result=board.result())) + break + most_drawy_move: chess.engine.InfoDict = min(candidates, key=appraise) my_move: chess.Move = (most_drawy_move['pv'][0]) board.push(my_move) @@ -73,6 +77,9 @@ async def handle_socket(request: web.Request): event="computer_moved", lastmove=my_move.uci(), )) + if board.is_game_over(claim_draw=True): + await send_to_user(dict(event="game_over", result=board.result(claim_draw=True))) + break finally: if not ws.closed: -- cgit