Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add analyze board #417

Merged
merged 5 commits into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions backend/chessLogic/chessLogic.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ def getBestMove(self, board):
self.last_move = best_move
return best_move

def getBoardAnalysis(self, board):
analysisDict = self.engine.analyse(board, chess.engine.Limit(time=0.3))
povScore = analysisDict["score"]
return povScore.white().score(mate_score=10000)

def getOutcome(self, board):
#.winner returns true for white win, false for black, None for draw
if board.outcome():
Expand Down
6 changes: 6 additions & 0 deletions backend/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def newGame(arg):
mycertabo.new_game()
emitFen()
startGame(arg)
emitAnalysis()

@socket_io.on('stop-game')
def stopGame():
Expand Down Expand Up @@ -145,11 +146,16 @@ def handleStockfishMove():
def doMove(move):
mycertabo.moves.append(move)
emitFen()
emitAnalysis()

def emitFen():
fen = mycertabo.chessboard.board_fen()
message = {"fen": fen, "color": mycertabo.color, 'moves': mycertabo.moves}
socket_io.emit("get-fen", message)

def emitAnalysis():
analysis = chess_logic.getBoardAnalysis(mycertabo.chessboard)
socket_io.emit("analysis", { "relativeScore": analysis })

if __name__ == '__main__':
socket_io.run(app, port=5000)
44 changes: 44 additions & 0 deletions frontend/src/Components/EvalGauge/EvalGauge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const toCentipawn = (score: number) => Math.round(score / 10) / 10;

interface EvalGaugeProps {
score: number
}

function clamp(num: number, min: number, max: number) {
return num <= min
? min
: num >= max
? max
: num
}

export const EvalGauge = ({ score }: EvalGaugeProps) => {

const nomalized = (((score ?? 0) + 1000) / 2000) * 100
const gaugePosition = clamp(nomalized, 0, 100);

return (
<div style={{
display: "flex",
flexFlow: "row nowrap",
width: "100%",
position: "relative",
paddingTop: "1em"
}}>
<div style={{ position: "absolute", width: "1.2em", height: "1.2em", background: "red", borderRadius: '0.6em', color: "#fff", padding: "2px", textAlign: 'center', transition: 'all 1s', verticalAlign: 'middle', top: "0", left: `calc(${gaugePosition}% - 0.6em)` }}>{toCentipawn(score)}</div>
<div style={{ width: "calc(100%/24)", background: "#ccc" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*2)", background: "#bbb" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*3)", background: "#aaa" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*4)", background: "#999" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*5)", background: "#888" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*6)", background: "#777" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*6)", background: "#666" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*5)", background: "#555" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*4)", background: "#444" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*3)", background: "#333" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*2)", background: "#222" }}>&nbsp;</div>
<div style={{ width: "calc(100%/24*1)", background: "#111" }}>&nbsp;</div>
</div>
)
}

9 changes: 3 additions & 6 deletions frontend/src/Components/PreGame/PreGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default function PreGame(props: alertProps) {
) => (
<Card
sx={{
width: 200,
width: "100%",
textAlign: "center",
border: "3px",
borderRadius: "16px",
Expand Down Expand Up @@ -139,17 +139,14 @@ export default function PreGame(props: alertProps) {
}
/>
</Box>
<Grid item sx={{ padding: "1em" }}>
{renderCard("assets/images/king_w.png", "White piece", "White", true)}
</Grid>
<Grid item sx={{ padding: "1em" }}>
<Box sx={{ width: "100%", textAlign: "center", padding: "1em" }}>
{renderCard(
"assets/images/king_b.png",
"Black piece",
"Black",
false
)}
</Grid>
</Box>
<Box sx={{ paddingTop: "1em" }}>
<Typography sx={{ textAlign: "center" }}>
Set stockfish level (1-20)
Expand Down
48 changes: 30 additions & 18 deletions frontend/src/pages/Game/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Box, Button } from "@mui/material";
import { Box, Button, Stack } from "@mui/material";
import { useEffect, useState } from "react";
import { Socket } from "socket.io-client";
import AlertComponent from "../../Components/Alert/Notification";
Expand All @@ -7,10 +7,15 @@ import GameStatus from "../../Components/GameStatus/GameStatus";
import { default as PreGame } from "../../Components/PreGame/PreGame";
import { useGameContext, GameState } from "./GameContext";
import "./index.css";
import { EvalGauge } from "../../Components/EvalGauge/EvalGauge.tsx";
interface gameProps {
socket: Socket;
}

interface Analysis {
relativeScore: number;
}

export default function Game(props: gameProps) {
const [FEN, setFEN] = useState<string>("start");
const [moves, setMoves] = useState<string[]>();
Expand All @@ -27,13 +32,15 @@ export default function Game(props: gameProps) {
const [promotion, setPromotion] = useState<string>("");
const [player, setPlayer] = useState<string>();
const [not_valid, setNotValid] = useState<boolean>(false);
const [relativeScore, setRelativeScore] = useState<number>(0);

useEffect(() => {
props.socket.on("invalid-move", handleInvalidMove);
props.socket.on("valid-moves", handleValidMoves);
props.socket.on("get-fen", handleFEN);
props.socket.on("game-over", handleResultMessage);
props.socket.on("promotion", handlePromotion);
props.socket.on("analysis", handleAnalysis);
return () => {
// Cleanup the props.socket listener when the component unmounts
props.socket.off("invalid-move", handleInvalidMove);
Expand Down Expand Up @@ -74,7 +81,11 @@ export default function Game(props: gameProps) {
}
};

function startGame() {
function handleAnalysis({ relativeScore }: Analysis): void {
setRelativeScore(relativeScore);
}

function startGame() {
if (props.socket.connected) {
const preferences = {
skill_level: stockfishlevel,
Expand Down Expand Up @@ -103,7 +114,7 @@ export default function Game(props: gameProps) {
}

const handleInvalidMove = () => {
setNotValid(true);
setNotValid(true);
};

const handleOK = () => {
Expand Down Expand Up @@ -185,8 +196,8 @@ export default function Game(props: gameProps) {
}
};

const handleValidMoves = (validMoves: string[]) => {
setValidMoves(validMoves);
const handleValidMoves = (validMoves: string[]) => {
setValidMoves(validMoves);
};

return (
Expand Down Expand Up @@ -225,9 +236,10 @@ export default function Game(props: gameProps) {
)}
</Box>
<Box className="chessboard-box">
<Box className="unclickable-area">
<Stack className="unclickable-area" direction="column">
<EvalGauge score={relativeScore} />
<MyChessboard socket={props.socket} FEN={FEN} />
</Box>
</Stack>
</Box>
{result === undefined && !gameState && (
<AlertComponent
Expand All @@ -252,17 +264,17 @@ export default function Game(props: gameProps) {
player={undefined}
/>
</Box>
)}
{(not_valid ) ? (
<Box className="not-valid-move">
<GameStatus
title="Invalid move!"
moves={valid_moves}
player={undefined}
/>
</Box>
) : <> </>
}
)}
{(not_valid) ? (
<Box className="not-valid-move">
<GameStatus
title="Invalid move!"
moves={valid_moves}
player={undefined}
/>
</Box>
) : <> </>
}
</Box>
)}
</Box>
Expand Down