Skip to content

Commit

Permalink
feat: 마피아 스킬을 웹소켓으로 교체 (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
cheonjiyun authored Dec 15, 2024
1 parent 2a09899 commit 02d7947
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 36 deletions.
2 changes: 1 addition & 1 deletion src/axios/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const existGame = () => {
};

export const getChats = () => {
return http.get<ChatArray>(`/v2/chat`);
return http.get<ChatArray>(`/chat`);
};

export const postChats = (payload: ChatRequest) => {
Expand Down
51 changes: 33 additions & 18 deletions src/components/job/MafiaNight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { css } from '@emotion/react';
import { useEffect, useState } from 'react';

import { postSkill, useMafiaVoteResultQuery } from '../../axios/http';
// import { postSkill, useMafiaVoteResultQuery } from '../../axios/http';
import { middle } from '../../pages/Night';
import { VariablesCSS } from '../../styles/VariablesCSS';
import { Player } from '../../type';
Expand All @@ -13,32 +13,47 @@ import PlayerNight from '../player/PlayerNight';
interface PropsType {
isAlive: boolean;
players: Player[];
publishSkill: (name: string) => void;
mafiaSkillPlayer: string | null;
}
export const MafiaNight = (props: PropsType) => {
const { players, isAlive } = props;
export const MafiaNight = ({ isAlive, players, publishSkill, mafiaSkillPlayer }: PropsType) => {
const mafiaVoteResult = mafiaSkillPlayer;

const { mafiaVoteResult } = useMafiaVoteResultQuery();
let nowVoteResult = mafiaVoteResult.target === '' ? 0 : -1;
let nowVoteResult = mafiaSkillPlayer === '' ? 0 : -1;

// 이름 -> index로 변경
players.forEach((player, i) => {
if (player.name === mafiaVoteResult.target) {
if (player.name === mafiaVoteResult) {
nowVoteResult = i + 1;
}
});

const [check, setCheck] = useState(-1);
useEffect(() => {
(async () => {
if (check === -1) {

const findTargetName = (): string => {
let targetName = '';
players.forEach((player, i) => {
if (check === i + 1) {
targetName = player.name;
return;
}
let targetName = '';
players.forEach((player, i) => {
if (check === i + 1) {
targetName = player.name;
return;
}
});
await postSkill({ target: targetName });
})();
});
return targetName;
};

const skill = async () => {
if (check === -1) {
return;
}
const targetName = findTargetName();
publishSkill(targetName);
};

useEffect(() => {
// (async () => {

// })();
skill();
}, [check, players]);

return (
Expand Down
70 changes: 58 additions & 12 deletions src/pages/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useRecoilState, useSetRecoilState } from 'recoil';
import { getChats, getGamesInfo, getMyJob } from '../axios/http';
import { BASE_URL } from '../axios/instances';
import { gameRound, myJobState, roomInfoState } from '../recoil/roominfo/atom';
import { ChatArray, ChatResponse, GameStatus, WaitingRoomInfo } from '../type';
import { ChatArray, ChatResponse, GameStatus, SkillResponse, WaitingRoomInfo } from '../type';
import Day from './Day';
import Night from './Night';
import Result from './Result';
Expand All @@ -18,6 +18,8 @@ export default function Game() {
const socketClientState = useRef<StompJs.Client | null>(null);

const [chatSubscribeId, setChatSubscribeId] = useState<StompJs.StompSubscription | null>(null);
const [skillSubscribeId, setSkillSubscribeId] = useState<StompJs.StompSubscription | null>(null);
const [mafiaSkillPlayer, setMafiaSkillPlayer] = useState<string | null>(null);
const [roomsInfoState, setRoomsInfoState] = useRecoilState(roomInfoState); // 방 정보
const [waitingRoomInfoState, setWaitingRoomInfoState] = useState<WaitingRoomInfo>({
totalPlayers: 1,
Expand Down Expand Up @@ -82,7 +84,17 @@ export default function Game() {
socketClientState.current = socket;
};

// 채팅구독
const disConnect = () => {
socketClientState.current?.deactivate();
};

// 웹소켓 연결
useEffect(() => {
connect();
return () => disConnect();
}, []);

// 채팅구독함수
const subscribeChat = () => {
if (!socketClientState.current?.connected) return;
const chatSubscribeId = socketClientState.current.subscribe(`/sub/chat/${auth}`, response => {
Expand Down Expand Up @@ -111,12 +123,9 @@ export default function Game() {
});
};

const disConnect = () => {
socketClientState.current?.deactivate();
};

// 채팅구독
// 채팅구독하기
useEffect(() => {
unsubscribeChat();
if (gamesStatus.statusType !== 'DAY') return;

// 본래 채팅불러오기
Expand All @@ -129,11 +138,42 @@ export default function Game() {
return () => unsubscribeChat();
}, [gamesStatus.statusType, finishSocketConneted]);

// 웹소켓 연결
// ======
// 밤 직업구독 함수
const subscribeSkill = async () => {
if (!socketClientState.current?.connected) return;

const mafiaSubscribeId = socketClientState.current.subscribe(`/sub/mafia/${auth}`, response => {
const msg: SkillResponse = JSON.parse(response.body);
setMafiaSkillPlayer(msg.content);
});

setSkillSubscribeId(mafiaSubscribeId);
};

// 밤 직업 구독끊기
const unsubscribeSkill = () => {
if (!socketClientState.current?.connected) return;
skillSubscribeId?.unsubscribe();
};

// 밤 스킬
const publishSkill = (name: string) => {
if (!socketClientState.current?.connected) return;

socketClientState.current.publish({
destination: `/pub/skill/${auth}`,
body: JSON.stringify({ target: name }),
});
};

useEffect(() => {
connect();
return () => disConnect();
}, []);
unsubscribeSkill();
if (gamesStatus.statusType !== 'NIGHT') return;

subscribeSkill();
return () => unsubscribeSkill();
}, [gamesStatus.statusType, finishSocketConneted]);

// 방 정보 저장 (방 상태가 바뀔때만 작동?)
useEffect(() => {
Expand All @@ -156,6 +196,8 @@ export default function Game() {
// 내 직업
if (gamesStatus.statusType !== 'WAIT' && !myJobRecoilState) {
const myJobResponse = await getMyJob();
console.log(myJobResponse);

setMyJobRecoilState(myJobResponse.job);
}
})();
Expand Down Expand Up @@ -186,7 +228,11 @@ export default function Game() {
/>
)}
{(gamesStatus.statusType === 'NIGHT_INTRO' || gamesStatus.statusType === 'NIGHT') && (
<Night statusType={gamesStatus.statusType} />
<Night
statusType={gamesStatus.statusType}
publishSkill={publishSkill}
mafiaSkillPlayer={mafiaSkillPlayer}
/>
)}
{gamesStatus.statusType === 'END' && <Result />}
</>
Expand Down
12 changes: 10 additions & 2 deletions src/pages/Night.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ import { Status } from '../type';

type PropsType = {
statusType: Status;
publishSkill: (name: string) => void;
mafiaSkillPlayer: string | null;
};

export default function Night({ statusType }: PropsType) {
export default function Night({ statusType, publishSkill, mafiaSkillPlayer }: PropsType) {
const [roomInfo] = useRecoilState(roomInfoState);
const [myJob] = useRecoilState(myJobState);

Expand All @@ -37,9 +39,15 @@ export default function Night({ statusType }: PropsType) {
) : (
<div>
<TopNight />
{myJob}
<>
{'MAFIA' === myJob && (
<MafiaNight players={roomInfo.players} isAlive={roomInfo.isAlive} />
<MafiaNight
players={roomInfo.players}
isAlive={roomInfo.isAlive}
publishSkill={publishSkill}
mafiaSkillPlayer={mafiaSkillPlayer}
/>
)}
{'CITIZEN' === myJob && (
<CitizenNight players={roomInfo.players} isAlive={roomInfo.isAlive} />
Expand Down
6 changes: 3 additions & 3 deletions src/pages/Result.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ export default function Result() {
<path
d="M9.14355 24.1042C9.14355 24.1042 11.1436 27.6042 21.1436 27.6042C31.1436 27.6042 32.1436 24.1043 32.1436 24.1043"
stroke="#210909"
stroke-opacity="0.8"
stroke-width="3.5"
stroke-linecap="round"
strokeOpacity="0.8"
strokeWidth="3.5"
strokeLinecap="round"
/>
</svg>
)}
Expand Down
7 changes: 7 additions & 0 deletions src/type/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export interface ChatRequest {
content: string;
}

export interface SkillResponse {
name: string;
content: string;
messageType: string;
timeStamp: Date;
}

export interface RoomResponse {
code: string;
}
Expand Down

0 comments on commit 02d7947

Please sign in to comment.