Skip to content

Commit e22d69b

Browse files
committed
Added the functionality of realtime with fastAPI
1 parent c52ad73 commit e22d69b

File tree

4 files changed

+106
-53
lines changed

4 files changed

+106
-53
lines changed
1.34 KB
Binary file not shown.

FastAPI/main.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from fastapi import FastAPI, WebSocket
2+
from fastapi.middleware.cors import CORSMiddleware
3+
from typing import List
4+
5+
app = FastAPI()
6+
active_connections: List[WebSocket] = []
7+
8+
# Allow all origins
9+
app.add_middleware(
10+
CORSMiddleware,
11+
allow_origins=["*"], # Allows all origins
12+
allow_credentials=True,
13+
allow_methods=["*"], # Allows all HTTP methods
14+
allow_headers=["*"], # Allows all headers
15+
)
16+
17+
@app.websocket("/ws")
18+
async def websocket_endpoint(websocket: WebSocket):
19+
await websocket.accept()
20+
active_connections.append(websocket)
21+
22+
try:
23+
while True:
24+
data = await websocket.receive_text()
25+
for connection in active_connections:
26+
await connection.send_text(data)
27+
except:
28+
active_connections.remove(websocket)

frontend/chess/src/app/chess/page.jsx

Lines changed: 77 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,62 @@
1-
'use client'
2-
import React, { useState, useMemo } from 'react';
3-
import dynamic from 'next/dynamic'; // Import dynamic from Next.js
4-
import { Button } from "@/components/ui/button";
5-
import { Chess } from "chess.js";
6-
import { Chessboard } from 'react-chessboard'
7-
import { ModeToggle } from "@/components/ui/mode-toggle";
8-
import { ThemeProvider } from '@/components/theme-provider';
9-
10-
1+
"use client";
2+
import React, { useState, useMemo, useEffect, useRef } from "react";
3+
import { Chess } from "chess.js";
4+
import { Chessboard } from "react-chessboard";
5+
import { ThemeProvider } from "@/components/theme-provider";
6+
import { ModeToggle } from "@/components/ui/mode-toggle";
117

128
export default function Home() {
139
const [game, setGame] = useState(new Chess());
1410
const [position, setPosition] = useState(game.fen());
11+
const ws = useRef(null); // Ref for WebSocket
12+
13+
// Initialize WebSocket connection when the component mounts
14+
useEffect(() => {
15+
ws.current = new WebSocket("ws://localhost:8000/ws"); // Replace with your WebSocket server address
16+
17+
// Handle incoming messages
18+
ws.current.onmessage = (event) => {
19+
const { sourceSquare, targetSquare } = JSON.parse(event.data);
20+
const newMove = game.move({
21+
from: sourceSquare,
22+
to: targetSquare,
23+
promotion: "q",
24+
});
25+
26+
if (newMove) {
27+
setPosition(game.fen());
28+
}
29+
};
30+
31+
// Clean up WebSocket on component unmount
32+
return () => {
33+
ws.current.close();
34+
};
35+
}, [game]);
36+
37+
// Handle moves on the board
38+
function onDrop(sourceSquare, targetSquare) {
39+
const move = game.move({
40+
from: sourceSquare,
41+
to: targetSquare,
42+
promotion: "q",
43+
});
44+
45+
if (move === null) {
46+
return false;
47+
}
48+
49+
// Update board state and send the move to the WebSocket server
50+
setPosition(game.fen());
51+
52+
if (ws.current && ws.current.readyState === WebSocket.OPEN) {
53+
ws.current.send(
54+
JSON.stringify({ sourceSquare, targetSquare })
55+
);
56+
}
57+
58+
return true;
59+
}
1560

1661
const pieces = ["wP", "wN", "wB", "wR", "wQ", "wK", "bP", "bN", "bB", "bR", "bQ", "bK"];
1762

@@ -32,48 +77,28 @@ export default function Home() {
3277
return pieceComponents;
3378
}, []);
3479

35-
// Function to handle moves
36-
function onDrop(sourceSquare, targetSquare) {
37-
const move = game.move({
38-
from: sourceSquare,
39-
to: targetSquare,
40-
promotion: "q", // auto-promote to queen for simplicity
41-
});
42-
43-
if (move === null) {
44-
45-
return false;
46-
}
47-
48-
// Update position state if the move is valid
49-
setPosition(game.fen());
50-
return true;
51-
}
52-
5380
return (
54-
<ThemeProvider>
55-
56-
<ModeToggle/>
57-
<div className="m-10 w-screen max-w-xl flex justify-center items-center">
58-
<Chessboard
59-
id="StyledBoard"
60-
boardOrientation="white"
61-
position={position}
62-
onPieceDrop={onDrop}
63-
customBoardStyle={{
64-
borderRadius: "4px",
65-
boxShadow: "0 2px 10px rgba(0, 0, 0, 0.5)",
66-
}}
67-
customDarkSquareStyle={{
68-
backgroundColor: "#008B8B",
69-
}}
70-
customLightSquareStyle={{
71-
backgroundColor: "#FCEAC7",
72-
}}
73-
customPieces={customPieces}
74-
/>
75-
76-
</div>
77-
</ThemeProvider>
81+
<ThemeProvider>
82+
<ModeToggle />
83+
<div className="m-10 w-screen max-w-xl flex justify-center items-center">
84+
<Chessboard
85+
id="StyledBoard"
86+
boardOrientation="white"
87+
position={position}
88+
onPieceDrop={onDrop}
89+
customBoardStyle={{
90+
borderRadius: "4px",
91+
boxShadow: "0 2px 10px rgba(0, 0, 0, 0.5)",
92+
}}
93+
customDarkSquareStyle={{
94+
backgroundColor: "#008B8B",
95+
}}
96+
customLightSquareStyle={{
97+
backgroundColor: "#FCEAC7",
98+
}}
99+
customPieces={customPieces}
100+
/>
101+
</div>
102+
</ThemeProvider>
78103
);
79104
}

frontend/chess/tsconfig.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,6 @@
2222
"@/*": ["./src/*"]
2323
}
2424
},
25-
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "src/app/chess/page.jsx", "src/app/chess/page.jsx"],
25+
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "src/app/chess/page.jsx", "src/app/chess/page.jsx", "src/app/heatmap/page.jsx"],
2626
"exclude": ["node_modules"]
2727
}

0 commit comments

Comments
 (0)