Skip to content

Commit

Permalink
Merge pull request #45 from pepero-1/feature/#3
Browse files Browse the repository at this point in the history
Feat/#3: 게임 시작 소켓 연결
  • Loading branch information
2YH02 authored Nov 15, 2023
2 parents 0db9393 + f5b03a0 commit 47a803a
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 85 deletions.
15 changes: 14 additions & 1 deletion src/components/Game/GameChat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import { useEffect, useRef, useState } from "react";
import ChatBubble from "../../common/ChatBubble";
import SystemChat from "../../common/SystemChat";
import Vote from "../Vote";
import { Socket } from "../../Main/CreateGameModal";

interface Message {
id: string;
text: string;
}

interface GameChatProps {
socket: any;
socket: Socket;
gameData: any;
}

Expand Down Expand Up @@ -57,6 +58,18 @@ const GameChat: React.FC<GameChatProps> = ({ socket, gameData }) => {

useEffect(() => {
socket.on("message-to-client", (messageObject: any) => {
if (messageObject.text.split("~")[1] === "!@##") {
const gameInfo = JSON.parse(messageObject.text.split("~")[0]);
console.log("parseData:", gameInfo);
window.localStorage.setItem(
"shuffledUsers",
JSON.stringify(gameInfo.users),
);
window.localStorage.setItem("category", gameInfo.category);
window.localStorage.setItem("keyword", gameInfo.keyword);
window.localStorage.setItem("liar", gameInfo.liar);
return;
}
// 메시지 데이터, 작성 유저 상태 저장
const copy = { ...message };
copy.id = messageObject.userId;
Expand Down
62 changes: 28 additions & 34 deletions src/components/Game/GameStart/index.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
import {
Button,
useDisclosure,
Modal,
ModalOverlay,
ModalContent,
ModalBody,
ModalCloseButton,
Center,
Flex,
// Modal,
// ModalOverlay,
// ModalContent,
// ModalBody,
// ModalCloseButton,
// Center,
// Flex,
} from "@chakra-ui/react";
import { useEffect, useState } from "react";
import data from "../../../data/category.json";
import { useRecoilValue } from "recoil";
import { userState } from "../../../recoil/atoms/userState";
import { Socket } from "../../Main/CreateGameModal";

interface GameStartProps {
socket: any;
socket: Socket;
status: string;
users: string[];
host: string;
updateStatus: (newStatus: string) => void;
}

interface Categories {
category: string;
keyword: string[];
}
[];
// interface Categories {
// category: string;
// keyword: string[];
// }
// [];

interface UserWithSort {
value: string;
Expand All @@ -44,13 +45,11 @@ const GameStart: React.FC<GameStartProps> = ({

const categories = data.CategoryList;
const { isOpen, onClose, onOpen } = useDisclosure();
const [category, setCategory] = useState<Categories | null>(null);
const [keyword, setKeyword] = useState("");
const [liar, setLiar] = useState("");
// const [category, setCategory] = useState<Categories | null>(null);
// const [keyword, setKeyword] = useState("");
// const [liar, setLiar] = useState("");
const [showStartModal, setShowStartModal] = useState(false);

console.log(liar);

useEffect(() => {
if (showStartModal) {
onOpen();
Expand All @@ -65,7 +64,7 @@ const GameStart: React.FC<GameStartProps> = ({
if (isOpen) {
timer = setTimeout(() => {
onClose();
}, 3000);
}, 2500);
}
return () => clearTimeout(timer);
}, [isOpen, onClose]);
Expand Down Expand Up @@ -104,18 +103,12 @@ const GameStart: React.FC<GameStartProps> = ({
});

// 모든 클라이언트에게 게임 정보를 포함하는 이벤트 전송
socket.emit("message-to-server", gameInfo + "~!@");
socket.emit("message-to-server", gameInfo + "~!@##");

setCategory(selectedCategory);
setKeyword(ranKeyword);
setLiar(ranLiar);
// setCategory(selectedCategory);
// setKeyword(ranKeyword);
// setLiar(ranLiar);
setShowStartModal(true);

window.localStorage.setItem("shuffledUsers", JSON.stringify(shuffledUsers));
window.localStorage.setItem("category", selectedCategory.category);
window.localStorage.setItem("keyword", ranKeyword);
window.localStorage.setItem("liar", ranLiar);
// onOpen();
};

// 게임 종료
Expand All @@ -125,8 +118,9 @@ const GameStart: React.FC<GameStartProps> = ({
window.localStorage.setItem("category", "");
window.localStorage.setItem("keyword", "");
window.localStorage.setItem("liar", "false");
setCategory(null);
setKeyword("");
// setCategory(null);
// setKeyword("");
setShowStartModal(false);
};

return (
Expand All @@ -150,7 +144,7 @@ const GameStart: React.FC<GameStartProps> = ({
게임 종료
</Button>
)}
<Modal isOpen={isOpen} onClose={onClose} closeOnEsc={true}>
{/* <Modal isOpen={isOpen} onClose={onClose} closeOnEsc={true}>
<ModalOverlay />
<ModalContent>
<ModalCloseButton />
Expand All @@ -169,7 +163,7 @@ const GameStart: React.FC<GameStartProps> = ({
justifyContent="center"
>
<Center>주제는 {category?.category} 입니다.</Center>
{window.localStorage.getItem("liar") === "true" ? (
{window.localStorage.getItem("liar") === user.id ? (
<>
<Center>당신은 Liar 입니다.</Center>
<Center>키워드를 추리하세요.</Center>
Expand All @@ -182,7 +176,7 @@ const GameStart: React.FC<GameStartProps> = ({
</ModalBody>
)}
</ModalContent>
</Modal>
</Modal> */}
</>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/components/Main/CreateGameModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ interface UserType {
picture: string;
}

interface Socket {
export interface Socket {
on(event: string, callback: any): void;
emit(event: string, data: any): void;
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const Example = () => {

//팝업 변화 감지
useEffect(() => {
if (toastUser[0] !== "") {
if (toastUser[0] !== "" && user.id) {
if (toastUser.includes(user.id)) {
console.log(roomData);
setToast(true);
Expand Down
58 changes: 10 additions & 48 deletions src/pages/Game/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { useEffect, useState } from "react";
import GameChat from "../../components/Game/GameChat";
import useFireFetch from "../../hooks/useFireFetch";
import GameStart from "../../components/Game/GameStart";
import { io } from "socket.io-client";
import { useRecoilValue } from "recoil";
import { userState } from "../../recoil/atoms/userState";
import connect from "../../socket/socket";

interface ProfileCardProps {
userId: string;
Expand All @@ -21,11 +21,11 @@ const ProfileCard: React.FC<ProfileCardProps> = ({ userId }) => {
);
};

interface Categories {
category: string;
keyword: string[];
}
[];
// interface Categories {
// category: string;
// keyword: string[];
// }
// [];

const Game = () => {
const user = useRecoilValue(userState);
Expand All @@ -39,21 +39,13 @@ const Game = () => {
const [status, setStatus] = useState("");
const [users, setUsers] = useState([]);

const [category, setCategory] = useState<Categories | null>(null);
const [category, setCategory] = useState("");
const [keyword, setKeyword] = useState("");
const [liar, setLiar] = useState("");

console.log(category, keyword);

const token = JSON.parse(localStorage.getItem("token") as string);

// const socket = connect(gameId as string);
const socket = io(`https://fastcampus-chat.net/chat?chatId=${gameId}`, {
extraHeaders: {
Authorization: `Bearer ${token.accessToken}`,
serverId: import.meta.env.VITE_APP_SERVER_ID,
},
});
const socket = connect(gameId as string);

useEffect(() => {
if (gameData.data && gameData.data.length > 0) {
Expand All @@ -64,34 +56,6 @@ const Game = () => {
}
}, [gameData.data]);

useEffect(() => {
// 메시지 수신 리스너 설정
socket.on("messeage-to-client", (data) => {
console.log(data);
const [jsonString, delimiter] = data.text.split("~");

if (delimiter === "!@") {
console.log(delimiter);
try {
// JSON 문자열 객체로 변환
const gameInfo = JSON.parse(jsonString);
console.log("parseData:", gameInfo);
setCategory(gameInfo.category);
setKeyword(gameInfo.keyword);
setLiar(gameInfo.liar);
setUsers(gameInfo.users);

// 필요한 작업 수행...
} catch (error) {
console.error("JSON Parsing Error: ", error);
throw error;
}
}
});
// onOpen();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [socket]);

useEffect(() => {
if (status === "게임중") {
// 저장된 유저 순서 로컬 스토리지에서 가져오기
Expand All @@ -104,7 +68,7 @@ const Game = () => {
const currentKeyword = window.localStorage.getItem("keyword") ?? "";
const currentLiar = window.localStorage.getItem("liar") ?? "";

setCategory({ category: currentCategory, keyword: [currentKeyword] });
setCategory(currentCategory);
setKeyword(currentKeyword);
setLiar(currentLiar);
}
Expand Down Expand Up @@ -152,9 +116,7 @@ const Game = () => {
{liar === user.id ? (
<p>당신은 Liar 입니다. </p>
) : (
<p>
키워드는 {window.localStorage.getItem("keyword")} 입니다.
</p>
<p>키워드는 {keyword} 입니다.</p>
)}
</>
) : (
Expand Down

0 comments on commit 47a803a

Please sign in to comment.