Skip to content

Commit

Permalink
Merge pull request #62 from Joseonpaldo/leebang
Browse files Browse the repository at this point in the history
Leebang
  • Loading branch information
themerous authored Sep 10, 2024
2 parents 281ca8c + 0d8125f commit 2dcb9a0
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 22 deletions.
6 changes: 6 additions & 0 deletions src/components/friend-list/FriendList.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ export default function FriendList() {
timestamp: message.timestamp
}
]);

// 메시지 전송 후, loadMessages 함수 실행
if (oneFriend && oneFriend.chatRoomId) {
loadMessages(oneFriend.chatRoomId);
}

}
};

Expand Down
10 changes: 5 additions & 5 deletions src/components/game/InviteModal.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";
import React, {useEffect, useState} from 'react';
import {Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Grid} from "@mui/material";
import React, { useEffect, useState } from 'react';
import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Grid } from "@mui/material";
import Button from "@mui/material/Button";
import apiAxiosInstance from "@/hooks/apiAxiosInstance";

Expand Down Expand Up @@ -109,10 +109,10 @@ const InviteModal = ({open, onClose, userId, client, roomId}) => {
<Grid container spacing={2}> {/* Grid 컨테이너 추가 */}
{friendList.map((friend, index) => (
<Grid item xs={12} key={index} container alignItems="center" justifyContent="center">
<Grid item xs={6} style={{textAlign: 'center'}}> {/* 이름 영역 */}
<Grid item xs={6} style={{ textAlign: 'center' }}> {/* 이름 영역 */}
<span>{friend.nickname} {friend.userId}</span>
</Grid>
<Grid item xs={6} style={{textAlign: 'center'}}> {/* 버튼 영역 */}
<Grid item xs={6} style={{ textAlign: 'center' }}> {/* 버튼 영역 */}
<Button
variant="contained"
style={{
Expand All @@ -132,7 +132,7 @@ const InviteModal = ({open, onClose, userId, client, roomId}) => {
)}
</DialogContentText>
</DialogContent>
<DialogActions sx={{justifyContent: 'center'}}>
<DialogActions sx={{ justifyContent: 'center' }}>
<Button
color="primary"
onClick={onClose}
Expand Down
38 changes: 31 additions & 7 deletions src/components/game/Lobby.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,8 @@ const Lobby = () => {
const [isFriendToModalOpen, setIsFriendToModalOpen] = useState(false); // 친구 요청 받은 모달 상태
const [receiver, setReciver] = useState(''); // 친구 요청을 보낸 유저 닉네임
const [sender, setSender] = useState(''); // 친구 요청을 보낸 유저 닉네임

const {roomId} = useParams();


async function getUserData(jwt) {
try {
const response = await apiAxiosInstance.get(`/user/${jwt}`);
Expand Down Expand Up @@ -106,6 +104,23 @@ const Lobby = () => {
}, [roomId]);


//방 제목
useEffect(() => {
const fetchRoomName = async () => {
try {
const response = await apiAxiosInstance.get(`/roomName/${roomId}`);
setRoomName(response.data); // 서버에서 반환된 roomName 설정
} catch (err) {
setError(err.message);
}
};

if (roomId) {
fetchRoomName();
}
}, [roomId]);


useEffect(() => {
const socket = new SockJS('/ws/');
const stompClient = Stomp.over(socket);
Expand Down Expand Up @@ -201,10 +216,10 @@ const Lobby = () => {
}
};

const handleButtonClick = (name) => {
const handleButtonClick = (user_id) => {
setVisibleOptions((prevState) => ({
...prevState,
[name]: !prevState[name]
[user_id]: !prevState[user_id] // user_id를 기준으로 상태 업데이트
}));
};

Expand Down Expand Up @@ -419,14 +434,22 @@ const Lobby = () => {

const newPlayers = playersInfo.map((info) => {
const [user_id, characterSrc, nickname] = info.split("|");

// 올바르게 user_id, characterSrc, nickname을 매핑하는지 확인
console.log("user_id:", user_id);
console.log("characterSrc:", characterSrc);
console.log("nickname:", nickname);

return {
user_id: user_id,
user_id: user_id, // 첫 번째 값은 user_id
ready: false,
characterSrc: characterSrc || userData.profilePicture,
nickname: nickname
characterSrc: characterSrc || userData.profilePicture, // 두 번째 값은 캐릭터 이미지
nickname: nickname // 세 번째 값은 nickname
};
});

setPlayers(newPlayers);

const selectedChars = newPlayers.map(player => player.characterSrc).filter(src => src !== null && src !== undefined);
setSelectedCharacters(selectedChars);
} else if (message.type === 'READY') {
Expand Down Expand Up @@ -621,6 +644,7 @@ const Lobby = () => {
)}
</div>
)}

</div>
</div>

Expand Down
38 changes: 28 additions & 10 deletions src/components/game/RankAnimation.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,47 @@ const RankAnimation = ({players, userData, client}) => {
const [sortedPlayers, setSortedPlayers] = useState([]);

useEffect(() => {
// players를 speed에 따라 내림차순으로 정렬
const sorted = [...players].sort((a, b) => b.speed - a.speed);
setSortedPlayers(sorted);
// players 배열이 존재하고 길이가 0보다 큰 경우에만 실행
if (players && players.length > 0) {
console.log("Initial players: ", players);

// speed에 따라 players 배열을 내림차순으로 정렬
const sorted = players.sort((a, b) => b.speed - a.speed);
setSortedPlayers(sorted);

console.log("Sorted players: ", sorted);
}
}, [players]);

useEffect(() => {
if (currentRank < sortedPlayers.length) {
const timeoutId = setTimeout(() => {
setDisplayedPlayers(prev => [...prev, sortedPlayers[currentRank]]);
setCurrentRank(currentRank + 1);
}, 2000); // 각 순위 공개 간격 (밀리초)
}, 2000);

return () => clearTimeout(timeoutId);
} else if (currentRank === sortedPlayers.length) {
// 모든 순위가 공개된 후 서버로 데이터를 전송
const rankings = sortedPlayers.map((player, index) => ({
name: player.name,
userId: player.userId, // 여기서 userId 사용
rank: index + 1
}));

console.log("Rankings being sent: ", rankings);

// 서버로 순위 데이터 전송
if (stompClient && stompClient.connected) {
stompClient.send(`/app/chat.updateRank/${roomId}`, {}, JSON.stringify(rankings));
}
}
}, [currentRank, sortedPlayers]);
}, [currentRank, sortedPlayers, stompClient, roomId]);

// userData와 players가 모두 존재하고 players 배열이 비어있지 않은 경우만 isHost를 계산
const isHost = players[0]?.user_id == userData?.user_id;


// userData와 players가 존재할 때만 컴포넌트 렌더링
if (!userData || players.length === 0) {
if (!players || players.length === 0) {
return null;
}

Expand All @@ -58,8 +77,7 @@ const RankAnimation = ({players, userData, client}) => {
</div>
))}
</div>
<br/><br/>
{/* 호스트만 버튼보임 */}
<br /><br />
{isHost && (
<Button
style={{backgroundColor: '#007bff', color: 'black', boxShadow: '3px 3px 3px gray', width: '100px'}}
Expand Down

0 comments on commit 2dcb9a0

Please sign in to comment.