Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FE] feat 디자인 #272

Merged
merged 16 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 26 additions & 17 deletions FE/src/api/socket/mocks/SocketMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,27 @@ type SocketEvent = keyof SocketDataMap;
export class SocketMock {
private listenerSet: Record<string, ((...args: unknown[]) => void)[]> = {};
private onAnyListenerList: ((event: string, ...args: unknown[]) => void)[] = [];
initialrized: Promise<void>;
Copy link
Preview

Copilot AI Nov 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable name 'initialrized' is misspelled. It should be 'initialized'.

Suggested change
initialrized: Promise<void>;
initialized: Promise<void>;

Copilot is powered by AI, so mistakes are possible. Review output carefully before use.

Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
constructor() {
console.log(`Mock WebSocket 연결`);
console.log(`%c Mock WebSocket 연결`, 'color:yellow; font-weight:bold;');
this.initialrized = new Promise((resolve) => {
this.delay(0).then(() => {
resolve();
});
});
this.initialrized.then(() => {
const currentPlayer = {
playerId: this.id,
playerName: 'Me',
playerPosition: [0.5, 0.5] as [number, number]
};
this.emitServer('joinRoom', { players: [currentPlayer] });
this.addPlayers([currentPlayer]);
this.emitServer('selfId', { playerId: this.id });
this.emitServer('setPlayerName', { playerId: this.id, playerName: 'Me' });
});

// }
}

/**
Expand All @@ -28,12 +47,10 @@ export class SocketMock {
this.onAnyListenerList.push(listener);
}
emit<T extends SocketEvent>(event: T, data: SocketDataMap[T]['request']) {
//여기서 서버에 데이터 전송
console.log(`%c SERVER_SOCKET[${event}]`, 'background:blue; color:white', data);
switch (event) {
case SocketEvents.CHAT_MESSAGE:
return this.handleChat(data as SocketDataMap[typeof SocketEvents.CHAT_MESSAGE]['request']);
case SocketEvents.JOIN_ROOM:
return this.handleJoin(data as SocketDataMap[typeof SocketEvents.JOIN_ROOM]['request']);
case SocketEvents.UPDATE_POSITION:
return this.handlePosition(
data as SocketDataMap[typeof SocketEvents.UPDATE_POSITION]['request']
Expand Down Expand Up @@ -119,18 +136,6 @@ export class SocketMock {
await this.delay(0.1);
this.chatMessage(this.id, data.message);
}
private async handleJoin(data: SocketDataMap[typeof SocketEvents.JOIN_ROOM]['request']) {
if (this.getPlayer(this.id)) return;
await this.delay(0.1);
const currentPlayer: (typeof this.players)[string] = {
playerId: this.id,
playerName: data.playerName,
playerPosition: [0.5, 0.5]
};
this.emitServer(SocketEvents.JOIN_ROOM, { players: this.getPlayerList() });
this.emitServer(SocketEvents.JOIN_ROOM, { players: [currentPlayer] });
this.addPlayers([currentPlayer]);
}
private async handlePosition(
data: SocketDataMap[typeof SocketEvents.UPDATE_POSITION]['request']
) {
Expand Down Expand Up @@ -172,6 +177,7 @@ export class SocketMock {
}
addPlayers(players: Array<SocketMock['players'][keyof SocketMock['players']]>) {
players.forEach((p) => (this.players[p.playerId] = p));
this.emitServer('joinRoom', { players });
}
setQuiz(quiz: string, quizSecond: number, choiceList: string[]) {
const COUNT_DOWN_TIME = 3000;
Expand Down Expand Up @@ -225,7 +231,8 @@ export class SocketMock {
});
}

createDummyPlayer(count: number) {
async createDummyPlayer(count: number) {
await this.initialrized;
const playerCount = Object.keys(this.players).length;
this.addPlayers(
Array(count)
Expand All @@ -239,6 +246,7 @@ export class SocketMock {
}

async chatRandom(testSec: number, chatPerSecPerPlyaer: number = 1) {
await this.initialrized;
const playerCount = this.getPlayerList().length;
for (let j = 0; j < testSec; j++) {
for (const player of this.getPlayerList()) {
Expand All @@ -250,6 +258,7 @@ export class SocketMock {
}

async moveRandom(testSec: number, movePerSecPerPlyaer: number = 1) {
await this.initialrized;
const playerCount = this.getPlayerList().length;
for (let j = 0; j < testSec; j++) {
for (const player of this.getPlayerList()) {
Expand Down
63 changes: 28 additions & 35 deletions FE/src/api/socket/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,20 @@ class SocketService {
this.handlers = [];
}

async connect() {
async connect(header: { 'create-room'?: string; 'game-id'?: string }) {
if (this.isActive()) return;
this.socket = io(this.url) as SocketInterface;
await new Promise<void>((resolve, reject) => {
this.socket.on('connect', () => resolve());
this.socket.on('error', () => reject());
});
this.initHandler();
return;
}

async connectMock(gameId: keyof typeof mockMap) {
if (this.isActive()) return;
this.socket = new mockMap[gameId]() as SocketInterface;
const gameId = header['game-id'];
if (gameId && gameId in mockMap) {
// mock과 연결
this.socket = new mockMap[gameId as keyof typeof mockMap]() as SocketInterface;
} else {
// 소켓 연결
this.socket = io(this.url, { query: header }) as SocketInterface;
await new Promise<void>((resolve, reject) => {
this.socket.on('connect', () => resolve());
this.socket.on('error', () => reject());
});
}
this.initHandler();
}

Expand All @@ -70,27 +70,13 @@ class SocketService {
}

disconnect() {
this.socket.disconnect();
if (this.isActive()) this.socket.disconnect();
}

isActive() {
return this.socket && this.socket.connected;
}

getSocketId() {
return this.socket.id;
}

// deprecated
onPermanently<T extends SocketEvent>(
event: T,
callback: (data: SocketDataMap[T]['response']) => void
) {
const handler = () => this.socket.on(event, callback);
this.handlers.push(handler);
if (this.isActive()) handler();
}

on<T extends SocketEvent>(event: T, callback: (data: SocketDataMap[T]['response']) => void) {
if (this.isActive()) this.socket.on(event, callback);
if (!this.handlerMap[event]) this.handlerMap[event] = [];
Expand All @@ -107,15 +93,22 @@ class SocketService {
this.socket.emit(event, data);
}

async createRoom(payload: SocketDataMap['createRoom']['request']) {
await this.connect();
this.socket.emit(SocketEvents.CREATE_ROOM, payload);
async createRoom(option: {
title: string;
gameMode: 'RANKING' | 'SURVIVAL';
maxPlayerCount: number;
isPublic: boolean;
}) {
this.disconnect();
await this.connect({
'create-room': Object.entries(option)
.map(([key, value]) => key + '=' + value)
.join(';')
});
}

async joinRoom(gameId: string, playerName: string) {
if (gameId in mockMap) this.connectMock(gameId as keyof typeof mockMap);
else if (!this.isActive()) await this.connect();
this.socket.emit(SocketEvents.JOIN_ROOM, { gameId, playerName });
async joinRoom(gameId: string) {
await this.connect({ 'game-id': gameId });
}

kickRoom(gameId: string, kickPlayerId: string) {
Expand Down
62 changes: 24 additions & 38 deletions FE/src/api/socket/socketEventTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,6 @@ type UpdatePositionResponse = {
playerPosition: [number, number];
};

// 게임방 생성 타입
type CreateRoomRequest = {
title: string;
gameMode: 'RANKING' | 'SURVIVAL';
maxPlayerCount: number;
isPublic: boolean;
};

type CreateRoomResponse = {
gameId: string; // PIN
};
Expand Down Expand Up @@ -62,12 +54,6 @@ type UpdateRoomQuizsetResponse = {
quizCount: number;
};

// 게임방 입장 타입
type JoinRoomRequest = {
gameId: string;
playerName: string;
};

type JoinRoomResponse = {
players: Array<{
playerId: string; // socketId
Expand All @@ -76,22 +62,26 @@ type JoinRoomResponse = {
}>;
};

// 게임 시작 타입
type StartGameRequest = {
gameId: string;
type getSelfIdResponse = {
playerId: string;
};

type StartGameResponse = Record<string, never>; // 빈 객체
type setPlayerNameRequest = {
playerName: string;
};

// 게임 정지 타입
type StopGameRequest = {
gameId: string;
type setPlayerNameResponse = {
playerId: string;
playerName: string;
};

type StopGameResponse = {
status: string;
// 게임 시작 타입
type StartGameRequest = {
gameId: string;
};

type StartGameResponse = Record<string, never>; // 빈 객체

type EndGameRequest = {
gameId: string;
};
Expand All @@ -113,11 +103,6 @@ type StartQuizTimeEvent = {
startTime: number; //timestamp
};

// 게임 점수 업데이트 타입
type UpdateScoreEvent = {
scores: Map<string, number>; // Map<playerId, score>
};

// 게임방 퇴장 타입
type ExitRoomEvent = {
playerId: string;
Expand All @@ -127,6 +112,7 @@ type KickRoomRequest = {
gameId: string;
kickPlayerId: string;
};

type KickRoomResponse = {
playerId: string;
};
Expand All @@ -142,7 +128,7 @@ export type SocketDataMap = {
response: UpdatePositionResponse;
};
createRoom: {
request: CreateRoomRequest;
request: null;
response: CreateRoomResponse;
};
updateRoomOption: {
Expand All @@ -154,17 +140,21 @@ export type SocketDataMap = {
response: UpdateRoomQuizsetResponse;
};
joinRoom: {
request: JoinRoomRequest;
request: null;
response: JoinRoomResponse;
};
selfId: {
request: null;
response: getSelfIdResponse;
};
setPlayerName: {
request: setPlayerNameRequest;
response: setPlayerNameResponse;
};
startGame: {
request: StartGameRequest;
response: StartGameResponse;
};
stopGame: {
request: StopGameRequest;
response: StopGameResponse;
};
endQuizTime: {
request: null;
response: EndQuizTimeEvent;
Expand All @@ -173,10 +163,6 @@ export type SocketDataMap = {
request: null;
response: StartQuizTimeEvent;
};
updateScore: {
request: null;
response: UpdateScoreEvent;
};
exitRoom: {
request: null;
response: ExitRoomEvent;
Expand Down
42 changes: 17 additions & 25 deletions FE/src/features/game/components/AnswerModal.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
import Lottie from 'lottie-react';
import AnswerBg from '@/assets/lottie/answer_background.json';
// import { useEffect, useState } from 'react';
import { useEffect, useState } from 'react';

type AnswerModalProps = {
isOpen: boolean;
// onClose: () => void;
answer: number;
};

const AnswerModal: React.FC<AnswerModalProps> = ({ isOpen, answer }) => {
// const [countdown, setCountdown] = useState(3);
const [countdown, setCountdown] = useState(3);

// useEffect(() => {
// if (isOpen) {
// setCountdown(3); // 모달이 열릴 때 카운트다운을 초기화
// const interval = setInterval(() => {
// setCountdown((prev) => {
// if (prev === 1) {
// clearInterval(interval);
// onClose(); // 0에 도달하면 모달 닫기
// }
// return prev - 1;
// });
// }, 1000);
// return () => clearInterval(interval); // 모달이 닫히거나 언마운트될 때 타이머 정리
// }
// }, [isOpen, onClose]);
useEffect(() => {
if (isOpen) {
setCountdown(3);
const interval = setInterval(() => {
setCountdown((prev: number) => {
if (prev === 1) {
clearInterval(interval);
}
return prev - 1;
});
}, 1000);
return () => clearInterval(interval);
}
}, [isOpen]);

if (!isOpen) return null;
if (!isOpen || countdown <= 0) return null;
return (
<div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50 pointer-events-none">
<Lottie
Expand All @@ -46,12 +44,6 @@ const AnswerModal: React.FC<AnswerModalProps> = ({ isOpen, answer }) => {
<p className="text-2xl text-black" style={{ marginBottom: '4rem' }}>
{answer}
</p>
{/* <button
onClick={onClose}
className="bg-blue-500 text-white px-6 py-3 rounded-md hover:bg-blue-600 transition"
>
닫기 ({countdown})
</button> */}
</div>
</div>
);
Expand Down
Loading
Loading