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

[공통] Release -> main #325

Merged
merged 99 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
99 commits
Select commit Hold shift + click to select a range
5efbf2e
feat: lottie 파일 추가
ijun17 Nov 28, 2024
be0c83e
feat: 커스텀 커서 구현
ijun17 Nov 28, 2024
88c53d6
feat: 보드 클릭 시 효과 적용
ijun17 Nov 28, 2024
dc95024
chore: npm run build 환경 변수 production으로 고정
ijun17 Nov 28, 2024
d8ad889
design: 디자인 쪼끔 변경
ijun17 Nov 28, 2024
b47c757
feat: joinRoom 이벤트에 isHost 추가
ijun17 Nov 28, 2024
d61914c
fix: 커스텀 커서 안되는 부분 적용
ijun17 Nov 28, 2024
7f5cce8
design: 디자인 쪼끔 변경
ijun17 Nov 28, 2024
d27f777
fix: 서버 연결 실패 예외 처리
ijun17 Nov 28, 2024
a6ae367
feat: 강퇴당했을때 뜨는 모달 구현
ijun17 Nov 28, 2024
319ee25
fix: 스크롤 버그 수정
ijun17 Nov 28, 2024
5d8ed3d
feat: 퀴즈셋 카테고리 추가
ijun17 Nov 28, 2024
5b84365
fix: 로그인 하고 새로고침 하도록 변경
ijun17 Nov 28, 2024
8e51742
feat: 나가기 버튼 추가
ijun17 Nov 28, 2024
733b1f9
fix: 플레이어 왼쪽 위로 나가는 버그 수정
ijun17 Nov 28, 2024
6e4b6e7
design: 게임 화면 배경 디자인
ijun17 Nov 28, 2024
853705f
hotfix
ijun17 Nov 28, 2024
a455e75
Merge pull request #290 from ijun17/dev-fe
ijun17 Nov 28, 2024
5aa9fed
hotfix
ijun17 Nov 28, 2024
a60bf9c
fix: endQuizTime에 호스트 사라지는 버그 수정
ijun17 Dec 1, 2024
639fd8c
fix: index.html에 prettier-ignore 삭제
ijun17 Dec 1, 2024
d3ccf64
Merge pull request #294 from ijun17/dev-fe
ijun17 Dec 2, 2024
73462ff
Merge pull request #296 from boostcampwm-2024/dev-fe
ijun17 Dec 2, 2024
49eb13b
fix: 채점 오류 해결
songbuild00 Dec 2, 2024
402c907
fix: TTL 관리 Cron 삭제
songbuild00 Dec 2, 2024
356c0b4
fix: 플레이어 키에 TTL 설정해주던 부분 주석 처리
songbuild00 Dec 2, 2024
e324d41
fix: [BE] 방정리 smembers to scan
DongHoonYu96 Dec 2, 2024
3c1e403
fix: [BE] 방삭제시 player 정보도 함께 삭제
DongHoonYu96 Dec 2, 2024
7e4ebb4
chore: [BE] 불필요한 주석 제거
DongHoonYu96 Dec 2, 2024
7e75160
Merge pull request #297 from songbuild00/fix-be-scoring-and-ttl
songbuild00 Dec 2, 2024
538dcea
Merge branch 'dev-be' into fix-be-room-clean
DongHoonYu96 Dec 2, 2024
51c0ce2
Merge pull request #298 from DongHoonYu96/fix-be-room-clean
DongHoonYu96 Dec 2, 2024
01546ea
Merge pull request #299 from boostcampwm-2024/dev-be
NewCodes7 Dec 2, 2024
f6ba79d
fix: 꼴등이 호스트가 되던 오류 수정
songbuild00 Dec 3, 2024
fb89693
fix: 서바이벌 모드 디버깅
NewCodes7 Dec 3, 2024
06803ab
feat: [BE] updatePos 성능개선 v1
DongHoonYu96 Dec 3, 2024
2dfbf8f
feat: [BE] updatePosition 성능개선 v2
DongHoonYu96 Dec 3, 2024
db874ea
fix: 게임 접속 시 설정과 퀴즈셋 전송 및 함수 분리
songbuild00 Dec 3, 2024
1b0e19a
fix: 죽은 자끼리의 채팅이 안 되는 버그 해결
NewCodes7 Dec 3, 2024
da14d2d
feat: [BE] updatePos 선검증후 set
DongHoonYu96 Dec 3, 2024
32b821b
feat: [BE] updatePos 성능개선 v3
DongHoonYu96 Dec 3, 2024
4052edb
feat: 소켓 목 호스트, 리드미 추가
ijun17 Dec 3, 2024
c204a9e
feat: 눈 내리는 배경 구현
ijun17 Dec 3, 2024
8e14b90
feat: 랜덤 배경 구현
ijun17 Dec 3, 2024
8c1a457
feat: 대기방 새로고침 버튼 구현
ijun17 Dec 3, 2024
e7e0208
feat: 순위 계산 유틸 함수 구현
ijun17 Dec 3, 2024
6ffccd4
fix: 접속 시 게임이 시작되어 있는 경우, 게임 시작 메시지 전송
songbuild00 Dec 3, 2024
5ab148d
feat: 테일 윈드 설정 변경
ijun17 Dec 3, 2024
3f1ea25
design: 스크롤 디자인 변경
ijun17 Dec 3, 2024
6f112c9
fix: 소켓 목 변경
ijun17 Dec 3, 2024
e19503e
feat: 스노우맨 로티 적용
ijun17 Dec 3, 2024
723ffdf
fix: 클립보드 버튼 줄바꿈 금지
ijun17 Dec 3, 2024
a14c20c
design: 커스텀 버튼 마진 탑 제거
ijun17 Dec 3, 2024
3195f61
design: 게임 헤더 디자인 변경
ijun17 Dec 3, 2024
674d577
style: 퀴즈 옵션 보드 불필요한 주석 제거
ijun17 Dec 3, 2024
4a62b83
fix: 서바이벌 모드에서의 죽은 자끼리의 updatePosition 수정
NewCodes7 Dec 3, 2024
7419bea
feat: 게임 결과 모달에 동일 점수 동일 랭크로 적용
ijun17 Dec 3, 2024
a65c8e9
Merge pull request #303 from DongHoonYu96/fix-be-updatePosition
NewCodes7 Dec 3, 2024
ea6e3a5
feat: 게임 대기방 새로고침
ijun17 Dec 3, 2024
f34bece
feat: 게임 페이지 랜덤 배경화면 및 눈내리는 배경 적용
ijun17 Dec 3, 2024
503f7df
Merge branch 'dev-be' into fix-survival
NewCodes7 Dec 3, 2024
83c2280
Merge pull request #301 from NewCodes7/fix-survival
NewCodes7 Dec 3, 2024
25b4f7a
Merge branch 'dev-be' into fix-be-reconnect-and-others
songbuild00 Dec 3, 2024
cc85e08
Merge pull request #304 from songbuild00/fix-be-reconnect-and-others
songbuild00 Dec 3, 2024
d5512c0
Merge pull request #306 from boostcampwm-2024/dev-be
NewCodes7 Dec 3, 2024
03ac6bb
Merge pull request #305 from ijun17/dev-fe
NewCodes7 Dec 3, 2024
ddb4a86
Merge pull request #307 from boostcampwm-2024/dev-fe
NewCodes7 Dec 3, 2024
431a5ea
fix: 타입 문제 해결
NewCodes7 Dec 3, 2024
3add6b4
Merge pull request #308 from NewCodes7/hot-fix
NewCodes7 Dec 3, 2024
7eebd65
Merge pull request #309 from boostcampwm-2024/dev-be
NewCodes7 Dec 3, 2024
ff92cd1
fix: 게임 종료 후 새로운 호스트 아이디 오류 수정
songbuild00 Dec 3, 2024
1b00078
feat: CORS Origin 추가
songbuild00 Dec 3, 2024
4ffbc87
feat: icon 추가
ijun17 Dec 3, 2024
adcadf2
feat: 배경 바꾸는 버튼 추가
ijun17 Dec 3, 2024
ce40c27
fix: 퀴즈 시작 전에 선택지 잠깐 보이는 오류 수정
ijun17 Dec 3, 2024
e3a5107
design: 팝업 애니메이션 적용
ijun17 Dec 3, 2024
1fdd95e
fix: 새로운 도메인으로 수정
ijun17 Dec 3, 2024
ebfc1c6
fix: 눈 내리는 배경 뒤에 렌더링 되도록 수정
ijun17 Dec 3, 2024
a1b0842
feat: 게임 배경 변경 기능
ijun17 Dec 3, 2024
4c74113
fix: 재접속 시 이름 입력 안뜨게 수정
ijun17 Dec 3, 2024
26953ae
Merge pull request #310 from songbuild00/fix-be-scoring-2
songbuild00 Dec 3, 2024
63d125d
Merge pull request #311 from ijun17/dev-fe
ijun17 Dec 3, 2024
3c93033
fix: 싱글 플레이 시 퀴즈 바로 끝나는 문제 해결
NewCodes7 Dec 3, 2024
7d5a3b5
Merge pull request #313 from NewCodes7/hot-fix-2
NewCodes7 Dec 3, 2024
63a9866
Merge pull request #316 from boostcampwm-2024/dev-be
NewCodes7 Dec 4, 2024
f3fe9c2
Merge pull request #317 from boostcampwm-2024/dev-fe
NewCodes7 Dec 4, 2024
824950a
fix: 대기방 새로고침 기능 수정
always97 Dec 4, 2024
e1bd9df
fix: 새로고침 수정
always97 Dec 4, 2024
085cdd4
Merge pull request #319 from always97/fe-refesh
always97 Dec 4, 2024
69e97cb
feat: 리드미용 소켓 목 추가
ijun17 Dec 3, 2024
3f09e3a
fix: 게임 시작 버튼 여러번 눌러도 한번만 게임 시작 요청 가도록 수정
ijun17 Dec 4, 2024
fa5bb2f
feat: 소켓 로그 변경
ijun17 Dec 5, 2024
645b60d
fix : test용 api 호출 금지
DongHoonYu96 Dec 5, 2024
f72d99c
design: 퀴즈 보드 살짝 더 투명하게 변경
ijun17 Dec 5, 2024
bb05a75
Merge pull request #321 from ijun17/hotfix
ijun17 Dec 5, 2024
3e3a053
Merge pull request #322 from boostcampwm-2024/dev-fe
ijun17 Dec 5, 2024
c92cf6d
fix: quiz test 수행되도록 수정
DongHoonYu96 Dec 5, 2024
470d5d4
Merge pull request #323 from DongHoonYu96/hot-fix
DongHoonYu96 Dec 5, 2024
fd4a280
Merge pull request #324 from boostcampwm-2024/dev-be
DongHoonYu96 Dec 5, 2024
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
5 changes: 3 additions & 2 deletions BE/src/InitDB/InitDB.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Controller, Post } from '@nestjs/common';
import { InitDBService } from './InitDB.Service';
import { Controller, HttpException, Post } from '@nestjs/common';

@Controller('/api/initDB')
export class InitDBController {
constructor(private readonly initDBService: InitDBService) {}

@Post()
create() {
return this.initDBService.create();
throw new HttpException('test용 api 입니다.', 501);
// return this.initDBService.create();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@ export enum GameMode {
RANKING = 'RANKING',
SURVIVAL = 'SURVIVAL',
}

export enum SurvivalStatus {
ALIVE = '1',
DEAD = '0',
}
2 changes: 1 addition & 1 deletion BE/src/game/dto/create-game.dto.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IsIn, IsInt, IsString, Max, MaxLength, Min, MinLength } from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { WsException } from '@nestjs/websockets';
import { GameMode } from '../../common/constants/game-mode';
import { GameMode } from '../../common/constants/game';

export class CreateGameDto {
@IsString()
Expand Down
2 changes: 1 addition & 1 deletion BE/src/game/dto/update-room-option.dto.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IsIn, IsInt, IsString, Length, Max, MaxLength, Min, MinLength } from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { WsException } from '@nestjs/websockets';
import { GameMode } from '../../common/constants/game-mode';
import { GameMode } from '../../common/constants/game';

export class UpdateRoomOptionDto {
@IsString()
Expand Down
3 changes: 2 additions & 1 deletion BE/src/game/game.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ import { ExceptionMessage } from '../common/constants/exception-message';
origin: [
'https://news.taskify.shop',
'https://quizground.duckdns.org',
'https://admin.socket.io'
'https://admin.socket.io',
'https://quizground.site'
],
credentials: true
},
Expand Down
55 changes: 53 additions & 2 deletions BE/src/game/redis/game-redis-memory.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';
import { Cron, CronExpression } from '@nestjs/schedule';
import { REDIS_KEY } from '../../common/constants/redis-key.constant';
import { Cron, CronExpression } from '@nestjs/schedule';

@Injectable()
export class GameRedisMemoryService {
private readonly logger = new Logger(GameRedisMemoryService.name);
private readonly BATCH_SIZE = 100; // 한 번에 처리할 배치 크기
private readonly INACTIVE_THRESHOLD = 30 * 60 * 1000; // 30분 30 * 60 * 1000;

private readonly TTL = {
ROOM: 3 * 60 * 60,
Expand All @@ -18,11 +19,61 @@ export class GameRedisMemoryService {

constructor(@InjectRedis() private readonly redis: Redis) {}

/**
* 비활성 방 체크 (주기적으로 실행)
*/
/**
* 비활성 방을 체크하고 정리하는 크론 작업
* SCAN을 사용하여 대규모 방 목록도 안전하게 처리
*/
@Cron(CronExpression.EVERY_10_MINUTES)
async checkInactiveRooms(): Promise<void> {
this.logger.verbose('비활성 방 체크 시작');
try {
const now = Date.now();
let cursor = '0';
let processedCount = 0;

do {
// SCAN을 사용하여 배치 단위로 처리
const [nextCursor, rooms] = await this.redis.sscan(
REDIS_KEY.ACTIVE_ROOMS,
cursor,
'COUNT',
this.BATCH_SIZE
);
cursor = nextCursor;

// 병렬로 방 상태 체크 및 처리
await Promise.all(
rooms.map(async (roomId) => {
try {
const lastActivity = await this.redis.hget(REDIS_KEY.ROOM(roomId), 'lastActivityAt');

if (lastActivity && now - parseInt(lastActivity) > this.INACTIVE_THRESHOLD) {
await this.redis.publish('room:cleanup', roomId);
this.logger.verbose(`비활성으로 인해 방 ${roomId} 정리 시작`);
processedCount++;
}
} catch (error) {
this.logger.error(`방 ${roomId} 처리 중 오류 발생: ${error.message}`);
}
})
);
} while (cursor !== '0');

this.logger.verbose(`비활성 방 체크 완료: ${processedCount}개 방 정리됨`);
} catch (error) {
this.logger.error(`비활성 방 체크 중 오류 발생: ${error.message}`);
}
}

/**
* TTL 관리를 위한 스케줄러
* 배치 처리로 블로킹 최소화
*/
@Cron(CronExpression.EVERY_MINUTE)

// @Cron(CronExpression.EVERY_MINUTE)
async manageTTL(): Promise<void> {
try {
// SCAN으로 활성 방 목록을 배치로 처리
Expand Down
38 changes: 23 additions & 15 deletions BE/src/game/redis/subscribers/player.subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Redis from 'ioredis';
import { Namespace } from 'socket.io';
import SocketEvents from '../../../common/constants/socket-events';
import { REDIS_KEY } from '../../../common/constants/redis-key.constant';
import { SurvivalStatus } from '../../../common/constants/game';

@Injectable()
export class PlayerSubscriber extends RedisSubscriber {
Expand Down Expand Up @@ -84,27 +85,34 @@ export class PlayerSubscriber extends RedisSubscriber {

const isAlivePlayer = await this.redis.hget(REDIS_KEY.PLAYER(playerId), 'isAlive');

if (isAlivePlayer === '1') {
if (isAlivePlayer === SurvivalStatus.ALIVE) {
server.to(gameId).emit(SocketEvents.UPDATE_POSITION, updateData);
} else if (isAlivePlayer === '0') {
} else if (isAlivePlayer === SurvivalStatus.DEAD) {
const players = await this.redis.smembers(REDIS_KEY.ROOM_PLAYERS(gameId));
const deadPlayers = await Promise.all(
players.map(async (id) => {
const isAlive = await this.redis.hget(REDIS_KEY.PLAYER(id), 'isAlive');
return { id, isAlive };
})
);

deadPlayers
const pipeline = this.redis.pipeline();

players.forEach((id) => {
pipeline.hmget(REDIS_KEY.PLAYER(id), 'isAlive', 'socketId');
});

type Result = [Error | null, [string, string] | null];
const results = await pipeline.exec();

(results as Result[])
.map(([err, data], index) => ({
id: players[index],
isAlive: err ? null : data?.[0],
socketId: err ? null : data?.[1]
}))
.filter((player) => player.isAlive === '0')
.forEach((player) => {
server.to(player.id).emit(SocketEvents.UPDATE_POSITION, updateData);
const socket = server.sockets.get(player.socketId);
if (!socket) {
return;
}
socket.emit(SocketEvents.UPDATE_POSITION, updateData);
});
}

this.logger.verbose(
`[updatePosition] RoomId: ${gameId} | playerId: ${playerId} | isAlive: ${isAlivePlayer === '1' ? '생존자' : '관전자'} | position: [${positionX}, ${positionY}]`
);
}

private async handlePlayerDisconnect(playerId: string, playerData: any, server: Namespace) {
Expand Down
9 changes: 9 additions & 0 deletions BE/src/game/redis/subscribers/room.cleanup.subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ export class RoomCleanupSubscriber extends RedisSubscriber {
try {
const pipeline = this.redis.pipeline();

// 1. 방에 속한 플레이어 목록 가져오기, 200명미만 -> smembers 사용!
const players = await this.redis.smembers(REDIS_KEY.ROOM_PLAYERS(roomId));

// 2. 플레이어 데이터 삭제
for (const playerId of players) {
pipeline.del(REDIS_KEY.PLAYER(playerId)); // 플레이어 기본 데이터
pipeline.del(`${REDIS_KEY.PLAYER(playerId)}:Changes`); // 플레이어 Changes 데이터
}

// 1. 방 관련 기본 데이터 삭제
pipeline.del(REDIS_KEY.ROOM(roomId));
pipeline.del(REDIS_KEY.ROOM_PLAYERS(roomId));
Expand Down
48 changes: 27 additions & 21 deletions BE/src/game/redis/subscribers/timer.subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Redis from 'ioredis';
import { Namespace } from 'socket.io';
import { REDIS_KEY } from '../../../common/constants/redis-key.constant';
import SocketEvents from '../../../common/constants/socket-events';
import { GameMode } from '../../../common/constants/game-mode';
import { GameMode, SurvivalStatus } from '../../../common/constants/game';

@Injectable()
export class TimerSubscriber extends RedisSubscriber {
Expand All @@ -28,6 +28,7 @@ export class TimerSubscriber extends RedisSubscriber {
const currentQuiz = await this.redis.get(REDIS_KEY.ROOM_CURRENT_QUIZ(gameId));
const [quizNum, state] = currentQuiz.split(':');

// REFACTOR: start, end 상수화
if (state === 'start') {
await this.handleQuizScoring(gameId, parseInt(quizNum), server);
} else {
Expand Down Expand Up @@ -65,7 +66,7 @@ export class TimerSubscriber extends RedisSubscriber {
const selectAnswer = this.calculateAnswer(
player.positionX,
player.positionY,
quizList.length
parseInt(quiz.choiceCount)
);
// this.logger.verbose(selectAnswer);

Expand Down Expand Up @@ -113,12 +114,18 @@ export class TimerSubscriber extends RedisSubscriber {

// 생존 모드에서 모두 탈락하진 않았는지 체크
const players = await this.redis.smembers(REDIS_KEY.ROOM_PLAYERS(gameId));
const alivePlayers = players.filter(async (id) => {
const isAlive = await this.redis.hget(REDIS_KEY.PLAYER(id), 'isAlive');
return isAlive === '1';
});
const aliveCount = (
await Promise.all(players.map((id) => this.redis.hget(REDIS_KEY.PLAYER(id), 'isAlive')))
).filter((isAlive) => isAlive === SurvivalStatus.ALIVE).length;

// 게임 끝을 알림
if (this.hasNoMoreQuiz(quizList, newQuizNum) || this.checkSurvivalEnd(players.length, aliveCount)) {
// 모든 플레이어를 생존자로 변경
const players = await this.redis.smembers(REDIS_KEY.ROOM_PLAYERS(gameId));
players.forEach((id) => {
this.redis.hset(REDIS_KEY.PLAYER(id), { isAlive: SurvivalStatus.ALIVE });
});

if (quizList.length <= newQuizNum || alivePlayers.length === 0) {
const leaderboard = await this.redis.zrange(
REDIS_KEY.ROOM_LEADERBOARD(gameId),
0,
Expand All @@ -128,13 +135,13 @@ export class TimerSubscriber extends RedisSubscriber {

this.redis.set(`${REDIS_KEY.ROOM(gameId)}:Changes`, 'End');
this.redis.hset(REDIS_KEY.ROOM(gameId), {
host: leaderboard[0],
host: leaderboard.at(-2),
status: 'waiting',
isWaiting: '1'
});

server.to(gameId).emit(SocketEvents.END_GAME, {
hostId: leaderboard[0]
hostId: leaderboard.at(-2)
});
this.logger.verbose(`[endGame]: ${gameId}`);
return;
Expand Down Expand Up @@ -167,8 +174,8 @@ export class TimerSubscriber extends RedisSubscriber {
}

private calculateAnswer(positionX: string, positionY: string, quizLen: number): number {
const x = parseFloat(positionX);
const y = parseFloat(positionY);
const x = parseFloat(positionY);
const y = parseFloat(positionX);

// 행의 개수 계산 (2열 고정이므로 총 개수의 절반을 올림)
const rows = Math.ceil(quizLen / 2);
Expand All @@ -177,21 +184,20 @@ export class TimerSubscriber extends RedisSubscriber {
const rowIndex = Math.floor(y * rows);

// X 좌표로 왼쪽/오른쪽 결정
const colIndex = x < 0.5 ? 0 : 1;
const colIndex = Math.round(x);

// 최종 선택지 번호 계산
const answer = rowIndex * 2 + colIndex + 1;

// 실제 선택지 범위를 벗어나지 않도록 보정
return Math.min(answer, quizLen);
// return (
// Math.round(
// parseFloat(positionX) + Math.floor(parseFloat(positionY) * Math.ceil(quizLen / 2))
// ) * 2
// );
// if (parseFloat(positionY) < 0.5) {
// return parseFloat(positionX) < 0.5 ? 1 : 2;
// }
// return parseFloat(positionX) < 0.5 ? 3 : 4;
}

private hasNoMoreQuiz(quizList, newQuizNum: number) {
return quizList.length <= newQuizNum;
}

private checkSurvivalEnd(playerCount: number, aliveCount: number) {
return playerCount > 1 && aliveCount <= 1;
}
}
17 changes: 12 additions & 5 deletions BE/src/game/service/game.chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { REDIS_KEY } from '../../common/constants/redis-key.constant';
import SocketEvents from '../../common/constants/socket-events';
import { Namespace } from 'socket.io';
import { TraceClass } from '../../common/interceptor/SocketEventLoggerInterceptor';
import { SurvivalStatus } from '../../common/constants/game';

@TraceClass()
@Injectable()
Expand Down Expand Up @@ -56,7 +57,8 @@ export class GameChatService {
const playerKey = REDIS_KEY.PLAYER(chatMessage.playerId);
const isAlivePlayer = await this.redis.hget(playerKey, 'isAlive');

if (isAlivePlayer === '1') {
// 생존한 사람이라면 전체 브로드캐스팅
if (isAlivePlayer === SurvivalStatus.ALIVE) {
server.to(gameId).emit(SocketEvents.CHAT_MESSAGE, chatMessage);
return;
}
Expand All @@ -65,11 +67,16 @@ export class GameChatService {
const players = await this.redis.smembers(REDIS_KEY.ROOM_PLAYERS(gameId));
await Promise.all(
players.map(async (playerId) => {
const playerKey = REDIS_KEY.PLAYER(playerId);
const isAlive = await this.redis.hget(playerKey, 'isAlive');
const socketId = await this.redis.hget(REDIS_KEY.PLAYER(playerId), 'socketId');
const socket = server.sockets.get(socketId);

if (isAlive === '0') {
server.to(playerId).emit(SocketEvents.CHAT_MESSAGE, chatMessage);
if (!socket) {
return;
}

const isAlive = await this.redis.hget(REDIS_KEY.PLAYER(playerId), 'isAlive');
if (isAlive === SurvivalStatus.DEAD) {
socket.emit(SocketEvents.CHAT_MESSAGE, chatMessage);
}
})
);
Expand Down
Loading
Loading