added color choice for computer game and fixed bug of computer not making move when player chooses black

This commit is contained in:
Moon Patel
2023-10-15 23:20:46 +05:30
parent 69f950c48f
commit fc1d5d4143
4 changed files with 88 additions and 32 deletions
+26
View File
@@ -18,6 +18,19 @@ const {
// roomID => { timeLimit,gameHistory , players:{'b': {username,userid}, 'w':{username,userid} } }
let activeRooms = new Map();
// chess - chess object
// moveData - {from,to} => lan notation
function isValidMove(chess,moveData) {
let newChess = new Chess();
newChess.loadPgn(chess.pgn());
try {
newChess.move(moveData);
return true;
} catch(err) {
return false;
}
}
function createRoom(roomID, timeLimit) {
console.log(roomID, "created");
activeRooms.set(roomID, { timeLimit, players: {}, gameHistory: [] });
@@ -73,12 +86,25 @@ function socketIOServerInit(server) {
console.log(evt);
});
socket.on('INIT', async (data) => {
if(data.color === 'b') {
console.log(data.color);
const botMove = await nextMove({position:chess.fen()});
console.log({ from: botMove.substring(0, 2), to: botMove.substring(2) });
chess.move({from:botMove.substring(0,2),to:botMove.substring(2)});
setTimeout(() => {
socket.emit("CHESS_BOT_MOVE",{from:botMove.substring(0,2),to:botMove.substring(2)})
}, 500);
}
});
socket.on("disconnect", (reason) => {
console.log(id, "disconnected due to", reason);
});
socket.on(CHESS_MOVE, async (roomID, moveData) => {
console.log("CHESS_MOVE");
if(!isValidMove(chess,moveData)) return;
chess.move(moveData);
let move = moveData.from + moveData.to;
console.log(move);
+2 -2
View File
@@ -13,7 +13,7 @@ import AuthenticationPage from './pages/Authentication/Authentication'
import ChallengeFriend, { playFriendAction } from './pages/Play/ChallengeFriend'
import Profile, { action as profileAction } from './pages/Settings/Profile'
import { getAuthToken, getUserData } from './utils/auth'
import Computer from './pages/Play/Computer'
import Computer, { playComputerAction } from './pages/Play/Computer'
import ComputerGame from './pages/Play/ComputerGame'
import MultiplayerGame from './pages/Play/MultiplayerGame'
@@ -29,7 +29,7 @@ const router = createBrowserRouter([{
{ index: true, element: <Play /> },
{ path: 'friend/:friend_username', element: <ChallengeFriend />, action: playFriendAction },
{ path: 'friend', element: <PlayFriend /> },
{ path: 'computer', element: <Computer /> },
{ path: 'computer', element: <Computer />, action: playComputerAction },
{ path: 'online', element: <div>Online</div> }
]
},
+13 -12
View File
@@ -3,7 +3,7 @@ import React, { useContext, useEffect } from 'react'
import { ChessGameContext } from '../../context/chess-game-context';
import { socketBot as socket } from '../../socket';
import { getUserData } from '../../utils/auth';
import { Avatar, Button, Flex, Image, MediaQuery, Modal, NavLink, Text, Title } from '@mantine/core';
import { Avatar, Button, Flex, MediaQuery, Modal, NavLink, Text, Title } from '@mantine/core';
import ChessBoard from '../Chess/ChessBoard';
import GameHistory from '../../components/GameHistory';
import { useNavigate } from 'react-router-dom';
@@ -22,6 +22,7 @@ const ChessGameComputer = () => {
useEffect(() => {
socket.connect();
socket.emit('INIT', {color});
socket.onAny(evt => {
console.log("event", evt);
@@ -42,11 +43,11 @@ const ChessGameComputer = () => {
const exitGame = () => {
console.log("Ending game");
socket.disconnect();
localStorage.removeItem('myColor');
navigate("/play/computer");
}
const pieceDropCallback = (moveData) => {
console.log("Hello");
socket.emit(CHESS_MOVE, roomID, moveData);
}
const pieceClickCallback = (moveData) => {
@@ -83,16 +84,16 @@ const ChessGameComputer = () => {
</div>
{
// TODO: handle isWaiting state
false ?
<>
<MediaQuery smallerThan="sm" styles={{ display: 'none' }}>
<Image width={600} miw={480} src="/src/assets/images/chess_board.png" />
</MediaQuery>
<MediaQuery largerThan="sm" styles={{ display: 'none' }}>
<Image width="100%" maw={540} src="/src/assets/images/chess_board.png" />
</MediaQuery>
</>
:
// false ?
// <>
// <MediaQuery smallerThan="sm" styles={{ display: 'none' }}>
// <Image width={600} miw={480} src="/src/assets/images/chess_board.png" />
// </MediaQuery>
// <MediaQuery largerThan="sm" styles={{ display: 'none' }}>
// <Image width="100%" maw={540} src="/src/assets/images/chess_board.png" />
// </MediaQuery>
// </>
// :
<ChessBoard callbacks={{ pieceDropCallback, pieceClickCallback }} />
}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+47 -18
View File
@@ -1,31 +1,60 @@
import { Button, Card, Flex, Image, TextInput, Title } from '@mantine/core'
import { IconSearch } from '@tabler/icons-react'
import React from 'react'
import { Link } from 'react-router-dom'
import React from "react";
import { Button, Card, Flex, Image, Select, Text, Title } from "@mantine/core";
import { Form, redirect } from "react-router-dom";
const Computer = () => {
return (
<Card
maw={450} sx={{
width: '100%',
height: '600px',
textAlign: 'center',
backgroundColor: '#262523'
maw={450}
sx={{
width: "100%",
height: "600px",
textAlign: "center",
backgroundColor: "#262523",
}}
>
<Flex align="center" justify="center" gap="xs" my="lg">
<Image width="30px" src="https://www.chess.com/bundles/web/images/color-icons/computer.2318c3b4.svg" />
<Image
width="30px"
src="https://www.chess.com/bundles/web/images/color-icons/computer.2318c3b4.svg"
/>
<Title order={2}>Play with Computer</Title>
</Flex>
<Flex direction='column' gap='10px'>
<Link to='/game/computer'>
<Button color='lime'>
Play
</Button>
</Link>
<Flex direction="column" gap="10px">
<Form action={`/play/computer`} method='POST'>
<Select
defaultValue="w"
my="20px"
color="lime"
name="color"
label={
<Text mx="auto" order={3}>
Select your color
</Text>
}
placeholder="choose your color"
data={[
{ value: "w", label: "White" },
{ value: "b", label: "Black" },
]}
/>
<Button color="lime" type="submit">
Play
</Button>
</Form>
</Flex>
</Card>
)
);
};
export const playComputerAction = async ({request}) => {
const formData = await request.formData();
let color = formData.get('color');
localStorage.setItem('myColor',color);
return redirect('/game/computer');
}
export default Computer
export default Computer;