Skip to content

Commit

Permalink
Merge pull request #486 from GunGonGamLee/484-fix-online-game-비동기-처리
Browse files Browse the repository at this point in the history
feat: online-game 모든 로직 비동기로 변경
  • Loading branch information
donghyun1998 authored Mar 12, 2024
2 parents 15d2168 + 7b3cd7a commit f28fce5
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 80 deletions.
17 changes: 9 additions & 8 deletions frontend/src/header/mainHeader/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ export default function MainHeader($container) {
this.ws = new WebSocket(`${WEBSOCKET}/friend_status/`);
this.ws.onmessage = (msg) => {
let response = JSON.parse(msg.data);
// TODO: 중복로그인 임시로 풀어둠
// if (response.type === 'alreadyLogin') {
// console.log(response.message);
// this.ws.close();
// navigate("error", { errorCode: 4001 });
// return;
// }
if (response.type === "alreadyLogin") {
console.log(response.message);
this.ws.close();
navigate("error", { errorCode: 4001 });
return;
}

// 업데이트된 내용을 set 함수에 전달합니다.
setFriendsList(response.data);
Expand Down Expand Up @@ -271,7 +270,9 @@ export default function MainHeader($container) {
// 상태 관리 시스템으로부터 현재 친구 목록 상태를 가져옴.
const newFriendList = getFriendsList();
// friends가 배열인지 확인하고, 아니라면 빈 배열을 사용.
const friends = Array.isArray(newFriendList.friends) ? newFriendList.friends : [];
const friends = Array.isArray(newFriendList.friends)
? newFriendList.friends
: [];

// 새로운 친구 목록을 기반으로 친구 카드를 생성.
const newFriendCards = friends
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/pages/local-game/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,7 @@ export default function LocalGame($container, info = null) {
}
drawFunction(bar1, bar2, ball);
let moveBallEventId = window.requestAnimationFrame(moveBall);
if (getScore().player1 + getScore().player2 >= 1) {
// TODO: 게임 종료 스코어 나중에 고치기
if (getScore().player1 + getScore().player2 >= 5) {
cancelAnimationFrame(moveBallEventId);
// 게임 종료
if (info.finalPlayer1 === null) {
Expand Down
1 change: 0 additions & 1 deletion frontend/src/pages/match-up/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export default function Matchup($container, info = null) {
navigate("/game-mode");
return;
}
console.log(info);
// 이전 페이지로 부터 받아온 정보 처리
const ws = info.socket;
ws.onmessage = null;
Expand Down
121 changes: 58 additions & 63 deletions frontend/src/pages/online-game/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ export default function OnlineGame($container, info) {
navigate("/game-mode");
return;
}
console.log(info);
const ws = info.socket;
let scoreInput = { player1: 0, player2: 0 };
let [getScore, setScore] = useState(scoreInput, this, "renderScoreBoard");
let [getTime, setTime] = useState(0, this, "renderTime");
let keyState = { up: false, down: false };

let myNickname = null;
let myMatch = 1;
let bar1, bar2, ball, $toast, toastObj, canvas, ctx;
let matchEndCnt = 0;
let initMyInfo = async () => {
myNickname = await getUserMe().then((user) => user.data.nickname);
if (
Expand All @@ -38,9 +38,8 @@ export default function OnlineGame($container, info) {
)
myMatch = 3;
};

const init = () => {
initMyInfo();
const init = async () => {
await initMyInfo();
hideHeader();
this.render();
this.renderScoreBoard();
Expand All @@ -51,10 +50,60 @@ export default function OnlineGame($container, info) {
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);

const $toast = document.querySelector(".toast");
const toast = new bootstrap.Toast($toast);
toast.show(); // Toast를 보여줍니다.
$toast = document.querySelector(".toast");
toastObj = new bootstrap.Toast($toast);
toastObj.show(); // Toast를 보여줍니다.
window.addEventListener("beforeunload", disconnectWebSocket);
canvas = $container.querySelector("#gameCanvas");
ctx = canvas.getContext("2d");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight * 0.88; // header의 height가 12vh이므로 88%만큼의 height를 가짐

bar1 = { x: 10, y: canvas.height / 2 - 50, width: 20, height: 100 };
bar2 = {
x: canvas.width - 30,
y: canvas.height / 2 - 50,
width: 20,
height: 100,
};
ball = { x: canvas.width / 2, y: canvas.height / 2, radius: 10 };
ws.send(
JSON.stringify({
type: myMatch === 3 ? "match3_start" : "start",
data: {
map_width: canvas.width,
map_height: canvas.height,
},
}),
);

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// console.log(data);
if (data.type === "in_game") {
bar1.x = data.data.left_side_player.x;
bar1.y = data.data.left_side_player.y;
bar1.width = data.data.width;
bar1.height = data.data.height;
bar2.x = data.data.right_side_player.x;
bar2.y = data.data.right_side_player.y;
bar2.width = data.data.width;
bar2.height = data.data.height;
ball.x = data.data.ball.x;
ball.y = data.data.ball.y;
draw(bar1, bar2, ball);
let score = getScore();
let newScore = {
player1: data.data.left_side_player.score,
player2: data.data.right_side_player.score,
};
if (
score.player1 !== newScore.player1 ||
score.player2 !== newScore.player2
)
setScore(newScore);
} else if (data.type === "game_end") endGame(data, ws);
};
};

const disconnectWebSocket = () => {
Expand All @@ -69,7 +118,6 @@ export default function OnlineGame($container, info) {
document.removeEventListener("keyup", keyUpHandler);
window.removeEventListener("beforeunload", disconnectWebSocket);
};
// TODO: avatar 하드코딩된거 나중에 수정하기 중복 코드 gameutils.js로 따로 빼기
this.render = () => {
$container.innerHTML = `
${scoreBar(info.data.data, myMatch)}
Expand Down Expand Up @@ -137,12 +185,10 @@ export default function OnlineGame($container, info) {
if (e.key === "ArrowUp") {
if (keyState.up === false) return;
keyState.up = false;
console.log("up");
ws.send(JSON.stringify({ type: "keyboard", data: "up" }));
} else if (e.key === "ArrowDown") {
if (keyState.down === false) return;
keyState.down = false;
console.log("down");
ws.send(JSON.stringify({ type: "keyboard", data: "down" }));
}
};
Expand Down Expand Up @@ -173,58 +219,7 @@ export default function OnlineGame($container, info) {
}

init();
const canvas = $container.querySelector("#gameCanvas");
const ctx = canvas.getContext("2d");
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight * 0.88; // header의 height가 12vh이므로 88%만큼의 height를 가짐
console.log(canvas.width, canvas.height);

let bar1 = { x: 10, y: canvas.height / 2 - 50, width: 20, height: 100 };
let bar2 = {
x: canvas.width - 30,
y: canvas.height / 2 - 50,
width: 20,
height: 100,
};
let ball = { x: canvas.width / 2, y: canvas.height / 2, radius: 10 };
ws.send(
JSON.stringify({
type: myMatch === 3 ? "match3_start" : "start",
data: {
map_width: canvas.width,
map_height: canvas.height,
},
}),
);

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// console.log(data);
if (data.type === "in_game") {
bar1.x = data.data.left_side_player.x;
bar1.y = data.data.left_side_player.y;
bar1.width = 20;
bar1.height = 100;
bar2.x = data.data.right_side_player.x;
bar2.y = data.data.right_side_player.y;
bar2.width = 20;
bar2.height = 100;
ball.x = data.data.ball.x;
ball.y = data.data.ball.y;
draw(bar1, bar2, ball);
let score = getScore();
let newScore = {
player1: data.data.left_side_player.score,
player2: data.data.right_side_player.score,
};
if (
score.player1 !== newScore.player1 ||
score.player2 !== newScore.player2
)
setScore(newScore);
} else if (data.type === "game_end") endGame(data, ws);
};
let matchEndCnt = 0;
function match3Logic(ws) {
ws.onmessage = null;
ws.send(JSON.stringify({ type: "match3_info" }));
Expand All @@ -234,7 +229,6 @@ export default function OnlineGame($container, info) {
};
}
function endGame(data, ws) {
console.log(myMatch, data);
if (myMatch !== data.data.match) {
matchEndCnt++;
return;
Expand All @@ -256,6 +250,7 @@ export default function OnlineGame($container, info) {
};
}
} else {
ws.close();
navigate(
`/histories/details?mode=${endData.game_mode}&gameId=${endData.game_id}`,
{ gameId: endData.game_id },
Expand Down
1 change: 0 additions & 1 deletion frontend/src/pages/register/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ export default function Register($container) {
})
.then((data) => {
// response.json()이 null이 아닐 때만 아래 로직 실행
console.log(data);
if (data) {
// token 값을 로컬 스토리지에 저장
if (data.token) {
Expand Down
4 changes: 0 additions & 4 deletions frontend/src/pages/waiting-room/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export default function WaitingRoom($container, info = null) {
}
let userNickname = null;
let players = info.data.players;
console.log(players);
getUserMe().then((user) => {
userNickname = user.data.nickname;
});
Expand All @@ -42,12 +41,10 @@ export default function WaitingRoom($container, info = null) {
);
ws.onmessage = (msg) => {
let data = JSON.parse(msg.data);
console.log(data);
if (data.type === "game_info") {
const player = info.data.players.find(
(player) => player.nickname === userNickname,
);
console.log(player, userNickname);
if (
((data.data.mode === 1 && data.data.players.length === 4) ||
(data.data.mode === 0 && data.data.players.length === 2)) &&
Expand All @@ -60,7 +57,6 @@ export default function WaitingRoom($container, info = null) {
players = data.data.players;
setUserState(players);
} else {
console.log(data);
ws.close();
const newWs = new WebSocket(`${WEBSOCKET}${data.data}`);
newWs.onmessage = (msg) => {
Expand Down
1 change: 0 additions & 1 deletion frontend/src/utils/clickEvent.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// TODO => click 시의 동작은 여기서 정의
export const click = (element, func) => {
element.addEventListener("click", func);
};
Expand Down

0 comments on commit f28fce5

Please sign in to comment.