Skip to content

Commit

Permalink
Merge branch 'develop' into feature/#3
Browse files Browse the repository at this point in the history
  • Loading branch information
suehub committed Nov 14, 2023
2 parents 55b2277 + 69514ee commit 8d4e343
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 92 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"husky": "^8.0.0",
"husky": "^8.0.3",
"terser": "^5.24.0",
"typescript": "^5.0.2",
"vite": "^4.4.5"
Expand Down
25 changes: 16 additions & 9 deletions src/components/Game/GameChat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const GameChat: React.FC<GameChatProps> = ({ gameId, gameData }) => {
console.log("users: ", users);
const [showVoteModal, setShowVoteModal] = useState(false);
const [selectedUser, setSelectedUser] = useState<string | null>("");
const [voteResult, setVoteResult] = useState<string | null>(null);

const handleOpenVoteModal = () => {
setShowVoteModal(true);
Expand All @@ -59,12 +60,9 @@ const GameChat: React.FC<GameChatProps> = ({ gameId, gameData }) => {
setSelectedUser(selectedUser);
};

// const handleCalculateVoteClose = (finalLiar: string) => {
// // finalLiar를 이용하여 특정 동작 수행 (SystemChat)

// // 선택한 결과 초기화
// setSelectedUser("");
// };
const handleVoteResult = (result: string | null) => {
setVoteResult(result);
};

useEffect(() => {
socket.on("message-to-client", (messageObject) => {
Expand Down Expand Up @@ -96,7 +94,7 @@ const GameChat: React.FC<GameChatProps> = ({ gameId, gameData }) => {
setUsers(responseData.users);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [setMessages, socket]);

// 메시지 값 변화시(소켓 통신 시) 콘솔에 메시지 데이터 출력
useEffect(() => {
Expand Down Expand Up @@ -136,10 +134,19 @@ const GameChat: React.FC<GameChatProps> = ({ gameId, gameData }) => {
투표하기
</Button>
{showVoteModal && (
<Vote gameData={gameData} onClose={handleCloseVoteModal} />
<Vote
gameData={gameData}
onClose={handleCloseVoteModal}
onVoteResult={handleVoteResult}
/>
)}
{selectedUser && (
<SystemChat text={`${selectedUser}님이 라이어로 선택되었습니다.`} />
<SystemChat text={`${selectedUser}님을 라이어로 지목했습니다.`} />
)}
{voteResult !== null && (
<SystemChat
text={`${voteResult}님이 라이어로 최종 지목되었습니다.`}
/>
)}
</CardBody>
<InputGroup size="md">
Expand Down
109 changes: 34 additions & 75 deletions src/components/Game/Vote/CalculateVote.tsx
Original file line number Diff line number Diff line change
@@ -1,82 +1,41 @@
import React, { useState, useEffect } from "react";
import {
Button,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalCloseButton,
ModalBody,
ModalFooter,
Text,
} from "@chakra-ui/react";
import useFireFetch from "../../../hooks/useFireFetch";

interface CalculateVoteProps {
voteResults: string;
onClose: (finalLiar: string) => void;
gameId: string;
interface Vote {
by: string;
liar: string;
}

const CalculateVote: React.FC<CalculateVoteProps> = ({
voteResults,
onClose,
gameId,
}) => {
const [finalLiar, setFinalLiar] = useState<string>("");
const fireFetch = useFireFetch();

// 투표 결과 계산 로직
useEffect(() => {
const calculateFinalLiar = async () => {
const gameData = await fireFetch.useGetSome("game", "id", gameId);
const { users, votedFor } = gameData.data[0];

const votesCount: Record<string, number> = {};
users.forEach((user: string) => {
if (votedFor.includes(user)) {
votesCount[user] = (votesCount[user] || 0) + 1;
}
});

let maxVotes = 0;
for (const user in votesCount) {
if (votesCount[user] > maxVotes) {
maxVotes = votesCount[user];
setFinalLiar(user);
}
}
};

calculateFinalLiar();
}, [voteResults, gameId, fireFetch]);
interface GameData {
id: string;
users: string[];
votedFor: Vote[];
}

// 투표 결과 계산 후 최종 라이어를 부모 컴포넌트로 전달
useEffect(() => {
if (finalLiar) {
onClose(finalLiar);
const calculateVote = (gameData: GameData): string | null => {
if (gameData.votedFor.length !== gameData.users.length) {
console.log(
`투표가 진행중입니다: ${gameData.votedFor.length} / ${gameData.users.length}`,
);
return null;
}

const voteCount: Record<string, number> = {};
gameData.votedFor.forEach((vote) => {
const liarId = vote.liar;
console.log("liarId:" + liarId);
voteCount[liarId] = (voteCount[liarId] || 0) + 1;
});

let maxCount = 0;
let maxId: string | null = null;

for (const id in voteCount) {
if (voteCount[id] > maxCount) {
maxCount = voteCount[id];
maxId = id;
console.log("maxId", maxId, maxCount + "표");
}
}, [finalLiar, onClose]);
}

return (
<Modal isOpen={true} onClose={() => {}}>
<ModalOverlay />
<ModalContent>
<ModalHeader>투표 결과 계산 중</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Text>투표 결과 계산 중입니다...</Text>
</ModalBody>
<ModalFooter>
{finalLiar && (
<Button colorScheme="blue" onClick={() => onClose(finalLiar)}>
계산 완료
</Button>
)}
</ModalFooter>
</ModalContent>
</Modal>
);
return maxId;
};

export default CalculateVote;
export default calculateVote;
22 changes: 16 additions & 6 deletions src/components/Game/Vote/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@ import {
} from "@chakra-ui/react";
import useFireFetch from "../../../hooks/useFireFetch";
import { arrayUnion } from "firebase/firestore";
import calculateVote from "./CalculateVote";
import { useRecoilValue } from "recoil";
import { userState } from "../../../recoil/atoms/userState";

interface GameData {
id: string;
users: string[];
votedFor: { by: string; liar: string }[];
}

interface VoteProps {
onClose: (selectedUser: string) => void;
onVoteResult: (result: string | null) => void;
gameData: GameData;
}

Expand All @@ -31,21 +36,26 @@ const Vote: React.FC<VoteProps> = ({
}): React.ReactElement => {
const [selectedUser, setSelectedUser] = useState<string>("");
const fireFetch = useFireFetch();
const fetchData = fireFetch.useGetSome("game", "id", gameData.id)
.data[0] as GameData;

const storedToken = localStorage.getItem("token");
const tokenData = storedToken ? JSON.parse(storedToken) : null;
const user = useRecoilValue(userState);

const handleUserChange = (value: string) => {
setSelectedUser(value);
};

const handleVoteSubmit = () => {
if (selectedUser !== null) {
const myId = tokenData.id;
if (selectedUser !== "") {
fireFetch.updateData("game", gameData.id, {
votedFor: arrayUnion({ by: myId, liar: selectedUser }),
votedFor: arrayUnion({ by: user.id, liar: selectedUser }),
});
console.log(selectedUser + "에 투표했습니다.");

console.log("fetchData", fetchData);
const voteResult = calculateVote(fetchData);

console.log("Vote result: " + voteResult);

onClose(selectedUser);
}
};
Expand Down

0 comments on commit 8d4e343

Please sign in to comment.