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

✨ : 새로운 위치 정보를 소켓에 반영 #132

Merged
merged 2 commits into from
Nov 9, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 5 additions & 1 deletion back-end/socket-server/services/socket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Server } from 'socket.io';
import { initTetrisSocket } from './tetrisSocket';

export const initSocket = (httpServer) => {
const io = new Server(httpServer, {
Expand All @@ -8,7 +9,8 @@ export const initSocket = (httpServer) => {
},
});
const nsp = io.of('/ad');

const tetris = io.of('/tetris');

nsp.on('connection', (socket) => {
console.log(socket.id);
console.log('asdf');
Expand All @@ -20,4 +22,6 @@ export const initSocket = (httpServer) => {

socket.on('disconnect', () => {});
});

initTetrisSocket(tetris);
};
64 changes: 64 additions & 0 deletions back-end/socket-server/services/tetrisSocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export const initTetrisSocket = (io) => {
const online = {};
const room = 0;
const rooms = {
0 : {
players: []
},
};

io.on('connection', (socket) => {
console.log(`socket ${socket.id} connect`);

socket.join(room);
online[socket.id] = {room: room};
rooms[room].players.push(socket.id);

console.log(online);
console.log(rooms);
// socket.on('join room', (roomId) => { // 방 ID 를 고유하게 만들어서 join할 예정
// online[socket.id] = {room: roomId};

// //socket.broadcast.to(roomId).emit('join new player', socket.id);
// //socket.emit('get other players info', rooms[roomId].players); // 누군가 방에 들어오면 자신을 제외한 모든 사람들 전송

// rooms[roomId].players.push(socket.id);

// //if(!rooms[roomId].players) return;
// console.log(online);
// console.log(rooms);
// });

socket.broadcast.to(room).emit('enter new player', socket.id);

socket.on('get other players info', res => {
const otherPlayer = rooms[room].players.filter(player => player != socket.id);
res(otherPlayer);
});

socket.on('drop block', block => { // 내 떨어지는 블록을 다른 사람에게 전송한다.
socket.broadcast.to(room).emit(`other player's drop block`, socket.id, block);
})

socket.on('disconnect', () => {
console.log(`disconnect ${socket.id}`);

if(rooms[online[socket.id].room].players != undefined)
rooms[online[socket.id].room].players = rooms[online[socket.id].room].players.filter(player => player != socket.id);


// if(rooms[online[socket.id].room].players.length == 0) { // 모두가 방을 비우면 해당 방 삭제
// delete rooms[online[socket.id].room];
// }

delete online[socket.id]; // 일단 온라인에서 유저도 삭제

console.log(online);
console.log(rooms);
});

socket.on('canvas', (data) => {
console.log(data);
});
});
}
12 changes: 0 additions & 12 deletions back-end/socket-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,4 @@ const server = http.createServer(app);

initSocket(server);

// const io = require('socket.io')(server, {
// cors: { origin: '*' },
// });

// io.sockets.on('connection', (socket) => {
// console.log(`socket ${socket.id} connect`);

// socket.on('disconnect', () => {
// console.log(`disconnect ${socket.id}`);
// });
// });

server.listen(5001);
Binary file added front-end/public/assets/other_block.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added front-end/public/assets/other_player_board.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
77 changes: 41 additions & 36 deletions front-end/src/components/Tetris/Board/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { useEffect, useRef } from 'react';
import { Socket } from 'socket.io-client';
import * as TETRIS from '../../../constants/tetris';
import {
Block,
TetrisBlock,
TetrisBlocks,
TetrisState,
TetrisTimer,
Expand All @@ -14,15 +15,15 @@ import { drawCell } from '../utils/block';
const BOARD: number[][] = TETRIS.BOARD;

const BLOCK: TetrisBlocks = {
NOW: null as unknown as Block,
BEFORE: null as unknown as Block,
NEXT: null as unknown as Block,
GHOST: null as unknown as Block,
HOLD: null as unknown as Block,
NOW: null as unknown as TetrisBlock,
BEFORE: null as unknown as TetrisBlock,
NEXT: null as unknown as TetrisBlock,
GHOST: null as unknown as TetrisBlock,
HOLD: null as unknown as TetrisBlock,
};

const STATE: TetrisState = {
QUEUE: null as unknown as Block[],
QUEUE: null as unknown as TetrisBlock[],
CAN_HOLD: null as unknown as boolean,
SOLID_GARBAGES: null as unknown as number,
KEYDOWN_TURN_RIGHT: null as unknown as boolean,
Expand Down Expand Up @@ -57,7 +58,7 @@ const PROPS_FUNC: TetrisPropsFunc = {
// 추가 블록 7개를 반환하는 함수
const getPreviewBlocks = () => {
const randomBlocks = TETRIS.randomTetromino();
const queue: Block[] = [];
const queue: TetrisBlock[] = [];

randomBlocks.forEach((block) => {
queue.push({
Expand All @@ -72,7 +73,7 @@ const getPreviewBlocks = () => {
};

// 블록의 현재 위치를 기준으로 BOARD에 고정시키는 함수
const setFreeze = (BOARD: number[][], BLOCK: Block) => {
const setFreeze = (BOARD: number[][], BLOCK: TetrisBlock) => {
BLOCK.shape.forEach((row: Array<number>, y: number) => {
row.forEach((value: number, x: number) => {
const [nX, nY] = [BLOCK.posX + x, BLOCK.posY + y];
Expand Down Expand Up @@ -102,7 +103,7 @@ const setSolidBlock = (board: number[][], solidBlocks: number) => {
};

// 블록이 한칸 다음으로 더 나아갈 수 있는지 아닌지 확인하는 함수 (블록이 바닥으로 내려오거나, 다른 블록 위에 떠 있는 경우 확인)
const isBottom = (board: number[][], block: Block) => {
const isBottom = (board: number[][], block: TetrisBlock) => {
return block.shape.some((row, y) =>
row.some((value: number, x: number) => {
if (value > 0) {
Expand Down Expand Up @@ -148,7 +149,7 @@ const draw = (BOARD: number[][], BLOCK: TetrisBlocks, BACKGROUND: TetrisBackgrou
};

// 충돌이 있는지 없는지 검사하는 함수
const isNotConflict = (block: Block, board: number[][]) => {
const isNotConflict = (block: TetrisBlock, board: number[][]) => {
return block.shape.every((row: Array<number>, y: number) => {
return row.every((value: number, x: number) => {
const [nX, nY] = [block.posX + x, block.posY + y];
Expand All @@ -158,7 +159,7 @@ const isNotConflict = (block: Block, board: number[][]) => {
};

// 블록을 45도 isRight에 따라 (시계 or 반시계)회전 시키는 함수
const rotate = (block: Block, isRight: boolean) => {
const rotate = (block: TetrisBlock, isRight: boolean) => {
if (block.name === 'O') return block;
for (let y = 0; y < block.shape.length; ++y) {
for (let x = 0; x < y; ++x) {
Expand Down Expand Up @@ -208,7 +209,7 @@ const SRSAlgorithm = (BOARD: number[][], BLOCK: TetrisBlocks, key: string) => {
// 게임 오버 상황인지 체크하는 함수
// 1. BOARD에서 범위가 y 0~3인 부분에 블록이 있다면 게임 오버
// 2. 새로운 블록이 생성 됐을때 그 자리에 이미 어떤 블록이 놓여져 있다면 게임 오버 (새로운 블록은 항상 y가 4인 곳 - 최상단에 위치하기 때문)
const isGameOver = (board: number[][], block: Block) => {
const isGameOver = (board: number[][], block: TetrisBlock) => {
const gameOverArr = board.slice(0, 4);

const outRange = gameOverArr.every((row: Array<number>, y: number) => {
Expand Down Expand Up @@ -238,7 +239,7 @@ const gameoverBlocks = (board: number[][]) => {
};

// 블록이 현재 상태에서 바닥으로 떨어졌을 때 블록을 반환하는 함수
const hardDropBlock = (board: number[][], block: Block) => {
const hardDropBlock = (board: number[][], block: TetrisBlock) => {
const nextBlock = JSON.parse(JSON.stringify(block));

while (true) {
Expand All @@ -252,7 +253,7 @@ const hardDropBlock = (board: number[][], block: Block) => {
};

const popBlockQueue = (STATE: TetrisState, PROPS_FUNC: TetrisPropsFunc) => {
const next = STATE.QUEUE.shift() as Block;
const next = STATE.QUEUE.shift() as TetrisBlock;
if (STATE.QUEUE.length === 5) {
STATE.QUEUE.push(...getPreviewBlocks());
}
Expand All @@ -262,22 +263,22 @@ const popBlockQueue = (STATE: TetrisState, PROPS_FUNC: TetrisPropsFunc) => {

// 각 event.key에 따라 블록을 바꿔서 반환
const moves = {
[TETRIS.KEY.LEFT]: (prev: Block) => ({
[TETRIS.KEY.LEFT]: (prev: TetrisBlock) => ({
...prev,
posX: prev.posX - 1,
}),
[TETRIS.KEY.RIGHT]: (prev: Block) => ({
[TETRIS.KEY.RIGHT]: (prev: TetrisBlock) => ({
...prev,
posX: prev.posX + 1,
}),
[TETRIS.KEY.DOWN]: (prev: Block) => ({
[TETRIS.KEY.DOWN]: (prev: TetrisBlock) => ({
...prev,
posY: prev.posY + 1,
}),
[TETRIS.KEY.TURN_RIGHT]: (prev: Block) => rotate(JSON.parse(JSON.stringify(prev)), true),
[TETRIS.KEY.TURN_LEFT]: (prev: Block) => rotate(JSON.parse(JSON.stringify(prev)), false),
[TETRIS.KEY.HOLD]: (prev: Block) => prev,
[TETRIS.KEY.HARD_DROP]: (prev: Block) => prev,
[TETRIS.KEY.TURN_RIGHT]: (prev: TetrisBlock) => rotate(JSON.parse(JSON.stringify(prev)), true),
[TETRIS.KEY.TURN_LEFT]: (prev: TetrisBlock) => rotate(JSON.parse(JSON.stringify(prev)), false),
[TETRIS.KEY.HOLD]: (prev: TetrisBlock) => prev,
[TETRIS.KEY.HARD_DROP]: (prev: TetrisBlock) => prev,
};

// 시작 전 테트리스를 초기화 하는 함수
Expand All @@ -288,8 +289,8 @@ const initTetris = (
TIMER: TetrisTimer,
BACKGROUND: TetrisBackground,
endGame: () => void,
getHoldBlockState: (newBlock: Block) => void,
getPreviewBlocksList: (newBlocks: null | Array<Block>) => void
getHoldBlockState: (newBlock: TetrisBlock) => void,
getPreviewBlocksList: (newBlocks: null | Array<TetrisBlock>) => void
) => {
PROPS_FUNC.GAMEOVER_FUNC = endGame;
PROPS_FUNC.HOLD_FUNC = getHoldBlockState;
Expand All @@ -308,7 +309,7 @@ const initTetris = (

BLOCK.NOW = popBlockQueue(STATE, PROPS_FUNC);
BLOCK.GHOST = hardDropBlock(BOARD, BLOCK.NOW);
BLOCK.HOLD = null as unknown as Block;
BLOCK.HOLD = null as unknown as TetrisBlock;

TIMER.PLAY_TIME = 0;

Expand Down Expand Up @@ -367,7 +368,8 @@ const initNewBlockCycle = (
BLOCK: TetrisBlocks,
STATE: TetrisState,
TIMER: TetrisTimer,
BACKGROUND: TetrisBackground
BACKGROUND: TetrisBackground,
socket: Socket
) => {
BLOCK.NOW = BLOCK.NEXT;

Expand All @@ -387,6 +389,7 @@ const initNewBlockCycle = (
TIMER.DROP = setInterval(() => {
BLOCK.NEXT = moves[TETRIS.KEY.DOWN](BLOCK.NOW);
moveBlock(BOARD, BLOCK, BACKGROUND);
socket.emit('drop block', BLOCK.NOW);
}, 900);

draw(BOARD, BLOCK, BACKGROUND);
Expand All @@ -400,15 +403,16 @@ const dropBlockCycle = (
TIMER: TetrisTimer,
option: string,
PROPS_FUNC: TetrisPropsFunc,
BACKGROUND: TetrisBackground
BACKGROUND: TetrisBackground,
socket: Socket
) => {
freezeBlock(BOARD, BLOCK, STATE, TIMER, option, PROPS_FUNC);
// 게임 오버 검사
if (isGameOver(BOARD, BLOCK.NEXT)) {
finishGame(BOARD, TIMER, BACKGROUND, PROPS_FUNC);
return;
}
initNewBlockCycle(BOARD, BLOCK, STATE, TIMER, BACKGROUND);
initNewBlockCycle(BOARD, BLOCK, STATE, TIMER, BACKGROUND, socket);
};

//블록을 홀드함
Expand Down Expand Up @@ -438,18 +442,18 @@ const holdBlock = (
};

const Board = ({
socket,
gameStart,
endGame,
getHoldBlockState,
getPreviewBlocksList,
}: {
socket: Socket;
gameStart: boolean;
endGame: () => void;
getHoldBlockState: (newBlock: Block) => void;
getPreviewBlocksList: (newBlocks: null | Array<Block>) => void;
getHoldBlockState: (newBlock: TetrisBlock) => void;
getPreviewBlocksList: (newBlocks: null | Array<TetrisBlock>) => void;
}): JSX.Element => {
const canvasContainer = useRef<HTMLCanvasElement>(null);

useEffect(() => {
if (!gameStart) return;

Expand All @@ -470,6 +474,7 @@ const Board = ({
TIMER.DROP = setInterval(() => {
BLOCK.NEXT = moves[TETRIS.KEY.DOWN](BLOCK.NOW);
moveBlock(BOARD, BLOCK, BACKGROUND);
socket.emit('drop block', BLOCK.NOW);
}, 900); // 블록을 0.9초마다 한칸씩 떨어뜨리는 타이머 등록

TIMER.CONFLICT = setInterval(() => {
Expand All @@ -483,7 +488,8 @@ const Board = ({
TIMER,
TIMER.PLAY_TIME >= 20 ? OPTIONS.TIME_OUT : '',
PROPS_FUNC,
BACKGROUND
BACKGROUND,
socket
);
}
}
Expand Down Expand Up @@ -528,7 +534,7 @@ const Board = ({
case TETRIS.KEY.HARD_DROP:
if (STATE.KEYDOWN_HARD_DROP) return;
STATE.KEYDOWN_HARD_DROP = true;
dropBlockCycle(BOARD, BLOCK, STATE, TIMER, OPTIONS.HARD_DROP, PROPS_FUNC, BACKGROUND);
dropBlockCycle(BOARD, BLOCK, STATE, TIMER, OPTIONS.HARD_DROP, PROPS_FUNC, BACKGROUND, socket);
break;
default:
break;
Expand Down Expand Up @@ -563,12 +569,11 @@ const Board = ({
<canvas
style={{
position: 'relative',
background: `url(assets/board.png)`,
background: `url(assets/player_board.png)`,
}}
className="board"
width={TETRIS.BOARD_WIDTH}
height={TETRIS.BOARD_HEIGHT}
ref={canvasContainer}
></canvas>
);
};
Expand Down
4 changes: 2 additions & 2 deletions front-end/src/components/Tetris/HoldBlock/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React, { useEffect, useRef } from 'react';
import * as TETRIS from '../../../constants/tetris';
import { drawCell } from '../utils/block';
import { Block } from '../types';
import { TetrisBlock } from '../types';

const HOLD_BOARD_SIZE = 4 * TETRIS.BLOCK_ONE_SIZE;

function HoldBlock({ holdBlock }: { holdBlock: Block | null }) {
function HoldBlock({ holdBlock }: { holdBlock: TetrisBlock | null }) {
const canvasContainer = useRef<HTMLCanvasElement>(null);

useEffect(() => {
Expand Down
Loading