Skip to content

Commit

Permalink
Merge pull request #101 from tscenping/game
Browse files Browse the repository at this point in the history
feat: game 브랜치 머지 합니다
  • Loading branch information
cjho0316 authored Dec 28, 2023
2 parents 43b384e + 463ded9 commit 62cedac
Show file tree
Hide file tree
Showing 17 changed files with 700 additions and 256 deletions.
17 changes: 13 additions & 4 deletions src/channels/channels.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import Redis from 'ioredis';
import { Server, Socket } from 'socket.io';
import { AuthService } from 'src/auth/auth.service';
import { UserStatus } from 'src/common/enum';
import { EVENT_USER_STATUS } from 'src/common/events';
import { EVENT_ERROR, EVENT_USER_STATUS } from 'src/common/events';
import { WSBadRequestException } from 'src/common/exception/custom-exception';
import { WsExceptionFilter } from 'src/common/exception/custom-ws-exception.filter';
import { GatewayCreateChannelInvitationParamDto } from 'src/game/dto/gateway-create-channelInvitation-param-dto';
Expand Down Expand Up @@ -58,14 +58,16 @@ export class ChannelsGateway
this.usersRepository.initAllSocketIdAndUserStatus();
}

async handleConnection(@ConnectedSocket() client: Socket, ...args: any[]) {
async handleConnection(@ConnectedSocket() client: Socket) {
// Socket으로부터 user 정보를 가져온다.

const user = await this.authService.getUserFromSocket(client);
if (!user || !client.id || user.channelSocketId) {
if (!user || !client.id) return client.disconnect();
if (user.channelSocketId) {
this.sendError(client, 400, `중복 연결입니다`);
return client.disconnect();
}
this.logger.log(`Client connected: userId: ${user.id}`);
this.logger.log(`Client connected: ${client.id}, userId: ${user.id}`);

// 유저의 channelSocketId와 status를 업데이트한다.
await this.usersRepository.update(user.id, {
Expand Down Expand Up @@ -265,4 +267,11 @@ export class ChannelsGateway
.to(channelId.toString())
.emit('notice', channelNoticeResponseDto);
}

sendError(client: Socket, statusCode: number, message: string) {
this.server.to(client.id).emit(EVENT_ERROR, {
statusCode: statusCode,
message: message,
});
}
}
5 changes: 5 additions & 0 deletions src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ export const CHANNEL_PASSWORD_REGEXP =
/^[a-zA-Z0-9`~;'"!@#$%^&*()_+|<>?:{}]*$/;

export const CHANNEL_NAME_REGEXP = /^[---a-zA-Z0-9]*$/;

// ladder score
/* If K is of a lower value, then the rating is changed by a small fraction
but if K is of a higher value, then the changes in the rating are significant.*/
export const K = 30;
1 change: 1 addition & 0 deletions src/common/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export enum GameType {
NORMAL_INVITE = 'NORMAL_INVITE',
SPECIAL_MATCHING = 'SPECIAL_MATCHING',
SPECIAL_INVITE = 'SPECIAL_INVITE',
NONE = 'NONE',
}

export enum GameStatus {
Expand Down
4 changes: 4 additions & 0 deletions src/common/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ export const EVENT_GAME_START = 'gameStart';
export const EVENT_MATCH_SCORE = 'matchScore';

export const EVENT_MATCH_STATUS = 'matchStatus';

export const EVENT_MATCH_END = 'matchEnd';

export const EVENT_ERROR = 'error';
7 changes: 7 additions & 0 deletions src/common/exception/custom-exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
DB_UPDATE_FAILURE,
ErrorCode,
WS_BAD_REQUEST_ERROR,
WS_DB_UPDATE_FAILURE,
WS_UNAUTHORIZED_ERROR,
} from './error-code';
export class customException extends Error {
Expand Down Expand Up @@ -36,3 +37,9 @@ export const WSUnauthorizedException = (message?: string): customException => {
export const WSBadRequestException = (message?: string): customException => {
return new customException(WS_BAD_REQUEST_ERROR, message);
};

export const WSDBUpdateFailureException = (
message?: string,
): customException => {
return new customException(WS_DB_UPDATE_FAILURE, message);
};
1 change: 1 addition & 0 deletions src/common/exception/custom-ws-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export class WsExceptionFilter extends BaseWsExceptionFilter {
const client = host.switchToWs().getClient();
client.packet({
type: PacketType.ACK,
namespace: ['channels', 'game'],
data: [{ sucess: false, error: exception?.message }],
id: client.nsp._ids++,
});
Expand Down
9 changes: 7 additions & 2 deletions src/common/exception/error-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ class ErrorCodeValueObject {
export type ErrorCode = ErrorCodeValueObject;

export const DB_UPDATE_FAILURE = new ErrorCodeValueObject(
HttpStatus.I_AM_A_TEAPOT,
HttpStatus.INTERNAL_SERVER_ERROR,
'DataBase task could not be done',
);

export const DB_QUERY_ERROR = new ErrorCodeValueObject(
HttpStatus.I_AM_A_TEAPOT,
HttpStatus.INTERNAL_SERVER_ERROR,
'Query task could not be done',
);

Expand All @@ -31,3 +31,8 @@ export const WS_BAD_REQUEST_ERROR = new ErrorCodeValueObject(
HttpStatus.BAD_REQUEST,
'WebSocket: bad request',
);

export const WS_DB_UPDATE_FAILURE = new ErrorCodeValueObject(
HttpStatus.INTERNAL_SERVER_ERROR,
'WebSocket: DataBase task could not be done',
);
2 changes: 1 addition & 1 deletion src/config/typeorm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default registerAs('typeorm', () => {
: process.env.POSTGRES_DB,
);
const ENTITIES = [__dirname + '/../**/entities/*.entity.{js,ts}'];
const SYNCHRONIZE = false;
const SYNCHRONIZE = true;

return {
type: TYPE,
Expand Down
10 changes: 10 additions & 0 deletions src/game/dto/emit-event-match-end-param.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { GameType } from '../../common/enum';

export class EmitEventMatchEndParamDto {
gameType: GameType;
rivalScore: number | null;
myScore: number | null;
isWin: boolean | null;
myLadderScore: number | null;
rivalLadderScore: number | null;
}
17 changes: 17 additions & 0 deletions src/game/dto/emit-event-server-game-ready-param.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,21 @@ export class EmitEventServerGameReadyParamDto {
rivalNickname: string;
rivalAvatar: string;
myPosition: string;
ball: {
x: number;
y: number;
radius: number;
};
myRacket: {
x: number;
y: number;
height: number;
width: number;
};
rivalRacket: {
x: number;
y: number;
height: number;
width: number;
};
}
53 changes: 49 additions & 4 deletions src/game/dto/game.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ export class GameDto {
private gameId: number;
playerLeftId: number;
playerRightId: number;
winnerId: number | null;
loserId: number | null;
scoreLeft: number;
scoreRight: number;
winnerId: number | null;
loserId: number | null;
winnerScore: number;
loserScore: number;
gameType: GameType;
gameStatus: GameStatus;
viewMap: ViewMapDto;
Expand All @@ -20,10 +22,12 @@ export class GameDto {
this.setGameId(game.id);
this.playerLeftId = game.winnerId;
this.playerRightId = game.loserId;
this.winnerId = null;
this.loserId = null;
this.scoreLeft = game.winnerScore;
this.scoreRight = game.loserScore;
this.winnerId = null;
this.loserId = null;
this.winnerScore = 0;
this.loserScore = 0;
this.gameType = game.gameType;
this.gameStatus = game.gameStatus;
this.viewMap = new ViewMapDto(game.ballSpeed, game.racketSize);
Expand All @@ -49,7 +53,48 @@ export class GameDto {
}
return false;
}

async restart() {
await this.viewMap.initObjects();
}

async setResult() {
if (this.gameType === GameType.NONE) {
this.winnerId = this.playerLeftId;
this.winnerScore = 0;
this.loserId = this.playerRightId;
this.loserScore = 0;
return;
}
if (this.loserId) {
this.loserScore = 0;
this.winnerScore = this.maxScore;
this.winnerId =
this.loserId === this.playerLeftId
? this.playerRightId
: this.playerLeftId;
} else {
if (this.scoreLeft === this.maxScore) {
this.winnerScore = this.scoreLeft;
this.winnerId = this.playerLeftId;
this.loserScore = this.scoreRight;
this.loserId = this.playerRightId;
} else if (this.scoreRight === this.maxScore) {
this.winnerScore = this.scoreRight;
this.winnerId = this.playerRightId;
this.loserScore = this.scoreLeft;
this.loserId = this.playerLeftId;
}
}
}

private setGameId(gameId: number) {
this.gameId = gameId;
}

// 테스트에만 쓰임
async testSetScore(scoreLeft: number, scoreRight: number) {
this.scoreLeft = scoreLeft;
this.scoreRight = scoreRight;
}
}
10 changes: 10 additions & 0 deletions src/game/dto/update-game-result-param.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { GameStatus, GameType } from '../../common/enum';

export class UpdateGameResultParamDto {
winnerId: number;
loserId: number;
winnerScore: number;
loserScore: number;
gameType: GameType;
gameStatus: GameStatus;
}
Loading

0 comments on commit 62cedac

Please sign in to comment.