GameBoard.tsx
2.62 KB
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
import React, { useCallback, useContext, useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import SocketContext from '../../contexts/SocketContext';
import { MessageType, RawMessage } from '../common/types';
import { Canvas } from './Canvas';
import { RoundInfo } from './RoundInfo';
import { Role, RoundData } from './types';
import { Word } from './Word';
interface GameBoardLocation {
state: { username: string }
}
interface GameBoardProps {
isInGame: boolean
}
export const GameBoard: React.FC<GameBoardProps> = ({ isInGame }) => {
const socket = useContext(SocketContext);
const location: GameBoardLocation = useLocation();
const [ isDrawer, setIsDrawer ] = useState(false);
const [ words, setWords ] = useState<string[]>([]);
const [ wordChosen, setWordChosen ] = useState('');
const [ round, setRound ] = useState(0);
const handleWordSet = useCallback((rawMessage: RawMessage) => {
if (rawMessage.type === MessageType.GAME_WORDSET) {
console.log('단어 도착');
const { words } = rawMessage.message as { words: string[] };
setWords(words);
}
}, []);
const handleStart = useCallback((rawMessage: RawMessage) => {
if (rawMessage.type === MessageType.GAME_START) {
setWords([]);
const data = rawMessage.message as RoundData;
console.log('테스트 location ', location.state.username);
console.log('테스트 rolse ', data.roles);
const index = data.roles.findIndex(x => x.username === location.state.username);
setIsDrawer(data.roles[index].role === 'drawer');
setWordChosen('');
setRound(data.round);
}
}, []);
const handleGetWordLength = useCallback((rawMessage: RawMessage) => {
if (rawMessage.type === MessageType.GAME_WORD) {
if (wordChosen === '') {
const { length } = rawMessage.message as { length: number };
setWordChosen('_' + ' _'.repeat(length-1));
}
}
}, [wordChosen]);
useEffect(() => {
socket.on('msg', handleStart);
socket.on('msg', handleGetWordLength);
socket.on('msg', handleWordSet);
return () => {
socket.off('msg', handleStart);
socket.off('msg', handleGetWordLength);
socket.off('msg', handleWordSet);
}
}, []);
return (
<div className={`w-auto ${isInGame ? '' : 'hidden'}`}>
<div className='w-full flex flex-col justify-center items-center'>
{words.map((word, i) => (<Word key={word} index={i} word={word} setWordChosen={setWordChosen} setWords={setWords} />))}
</div>
<RoundInfo round={round} wordChosen={wordChosen}/>
<Canvas isDrawer={isDrawer && wordChosen !== ''}/>
</div>
);
}