File size: 7,131 Bytes
ece5841 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
import React, { useContext, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useDisclosure } from '@mantine/hooks'
import { Avatar, Button, Flex, Image, MediaQuery, Modal, NavLink, Text, Title } from '@mantine/core'
import { socket, socketBot } from '../../socket'
import { getUserData } from '../../utils/auth'
import { ChessGameContext } from '../../context/chess-game-context'
import ChessBoard from '../Chess/ChessBoard'
import GameHistory from '../../components/GameHistory'
import MainLoader from '../../components/MainLoader'
import { SOCKET_EVENTS } from '../../constants'
import Timer from '../Chess/Timer'
const { CONNECT, DISCONNECT, CHESS_OPPONENT_MOVE, USER_RESIGNED, JOIN_ROOM, JOIN_ROOM_ERROR, JOIN_ROOM_SUCCESS, ROOM_FULL, USER_JOINED_ROOM, CHESS_MOVE } = SOCKET_EVENTS;
const ChessGameMultiplayer = () => {
const { setGameHistory, hasGameEnded, gameEndedReason, endGame, handleOpponentMove, isTimerOn } = useContext(ChessGameContext);
const [gameEndedModalOpen, modalFunctions] = useDisclosure(true);
const user = getUserData();
let username = user.username;
let userid = user.id;
let color = localStorage.getItem('myColor');
const [hasJoinedRoom, setHasJoinedRoom] = useState(localStorage.getItem('socketid'));
const [isWaiting, setIsWaiting] = useState(true);
const roomID = localStorage.getItem('roomID');
const navigate = useNavigate();
const opponent = localStorage.getItem('opponent');
const exitGame = () => {
// cleanup game related data
localStorage.removeItem('socketid');
localStorage.removeItem('roomID');
localStorage.removeItem('opponent');
localStorage.removeItem('myColor');
localStorage.removeItem('timeLimit');
socket.disconnect();
navigate('/play/friend');
}
const resign = () => {
socket.emit(USER_RESIGNED, roomID, username);
endGame('RESIGN');
exitGame();
}
const pieceDropCallback = (moveData) => {
socket.emit(CHESS_MOVE, roomID, moveData);
}
const pieceClickCallback = (moveData) => {
// moveData contains fen string, from, to squares of the move
socket.emit(CHESS_MOVE, roomID, moveData);
}
useEffect(() => {
socket.connect();
socket.on(CONNECT, () => {
console.log('Connected');
});
socket.on(JOIN_ROOM_SUCCESS, (fetchedGameHistory) => {
setGameHistory(fetchedGameHistory);
setHasJoinedRoom(true);
});
socket.on(ROOM_FULL, () => {
console.log('Room is full');
})
socket.on(JOIN_ROOM_ERROR, (err) => {
console.error("Error:", err);
})
socket.emit(JOIN_ROOM, roomID, { username, color, userid })
socket.on(DISCONNECT, (reason) => {
console.log('Socket disconnected due to', reason);
});
socket.on(CHESS_OPPONENT_MOVE, (data) => {
handleOpponentMove(data, () => {
socket.emit(GAME_END, roomID);
})
})
socket.on(USER_JOINED_ROOM, () => {
setIsWaiting(false);
});
socket.on(USER_RESIGNED, () => {
endGame('RESIGN');
});
return () => {
socket.offAny();
socket.disconnect();
}
}, []);
if (!hasJoinedRoom) return (
<MainLoader />
)
return (
<React.Fragment>
<Modal onClose={modalFunctions.close} opened={hasGameEnded && gameEndedModalOpen} centered>
<Text>Game ended due to {gameEndedReason}</Text>
<Button color='lime' onClick={exitGame}>Go back</Button>
<Button mx='md' color='lime' onClick={modalFunctions.close}>OK</Button>
</Modal>
<Flex gap="xl" justify='center' align='center' wrap='nowrap' mt={{ base: '50px', sm: '0px' }} direction={{ base: 'column', lg: 'row' }}>
<Flex gap="xs" justify='center' h='100vh' align='start' wrap='nowrap' direction='column' >
<div style={{ width:"100%", height:'6vh', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<NavLink
p="2px"
label={isWaiting ? "Waiting for opponent..." : opponent}
icon={<Avatar radius="3px" >
{opponent?.at(0)?.toUpperCase}
</Avatar>}
description={"description"}
/>
<Timer on={!isTimerOn} />
</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>
// </>
// :
<ChessBoard callbacks={{ pieceDropCallback, pieceClickCallback }} />
}
<div style={{ width:"100%", height:'6vh', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<NavLink
style={{ width: "500px" }}
p="2px"
label={username}
icon={<Avatar radius="3px" >
{username[0].toUpperCase()}
</Avatar>}
description={"description"}
/>
<Timer on={isTimerOn} />
</div>
</Flex>
<MediaQuery smallerThan="lg" styles={{ display: 'none' }}>
<Flex maw={600} sx={{
width: '100%',
height: '840px',
textAlign: 'center',
borderRadius: '10px',
backgroundColor: '#272623'
}} bg='gray' justify='start' py='md' align='center' direction='column' h="600px">
<Title my='20px'>Game Data</Title>
<Flex direction='column' w='100%'>
<GameHistory />
</Flex>
<Flex>
<Button onClick={resign} color='red'>Exit Game</Button>
</Flex>
</Flex>
</MediaQuery>
</Flex>
</React.Fragment>
)
}
export default ChessGameMultiplayer |