인터넷없이 크롬으로만 실행해야하는 html파일로 2048이라는 게임을 만들고 있습니다 방향키함수가 잘못된것 같은데 어떻게 고쳐도 안됩니다
인터넷없이 크롬으로만 실행해야하는 html파일로 2048이라는 게임을 챗got의 도움을 받아 만들고 있습니다 방향키함수가 잘못된것 같은데 어떻게 고쳐도 안됩니다.
코드 첨부할테니 무엇이 잘못 된건지 알려주시면 감사하겠습니다!
시중에 있는 2048과 같이 키보드로 한쪽으로 이동하면서 숫자가 합쳐져야하는데 좌우 방향키는 정상적으로 이동하고 합쳐지지만 위 아래 방향키가 정상적으로 작동하질 않습니다 좌우 방향키와 같은 로직으로 이동하게 할려해도 저의 지식으로는 어림도 없는듯 합니다.
정상적으로 작동하게 수정하여 주시면 감사하겠습니다 .
(코드전문)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2048</title>
<style>
td {
border: 2px solid #372c25;
border-radius: 9px;
text-align: center;
vertical-align: middle;
font-size: 18pt;
font-weight: bold;
height: 70px;
width: 70px;
color: #684A23;
background-color: #FBEDDC;
}
p {
color: white;
vertical-align: top;
}
body {
background-color: #372C25;
}
#title {
color: white;
font-size: 48px;
padding: 0px;
margin: 0px;
}
#titleBar {
padding-left: 70px;
margin-top: 35px;
}
#titlePad, #scorePad {
width: 148px;
height: 35px;
background-color: #372C25;
}
#scorePad {
background-color: #46382E;
}
#scoreType {
font-size: 14pt;
color: #715541;
}
#score {
font-size: 28pt;
color: white;
}
#board {
margin: 5px 70px;
}
#info {
margin-left: 82px;
font-size: 10pt;
color: white;
}
</style>
</head>
<body>
<table id="titleBar" border="0">
<tr>
<td id="titlePad">
<p id="title">2048</p>
</td>
<td id="scorePad">
<p id="scoreType">Score</p>
<p id="score">0</p>
</td>
</tr>
</table>
<table id="board" border="0">
<tr>
<td id="00"></td>
<td id="01"></td>
<td id="02"></td>
<td id="03"></td>
</tr>
<tr>
<td id="10"></td>
<td id="11"></td>
<td id="12"></td>
<td id="13"></td>
</tr>
<tr>
<td id="20"></td>
<td id="21"></td>
<td id="22"></td>
<td id="23"></td>
</tr>
<tr>
<td id="30"></td>
<td id="31"></td>
<td id="32"></td>
<td id="33"></td>
</tr>
</table>
<p id="info">2048 Copyright (c) YJYOON All rights reserved.</p>
<script>
var board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
var score = 0;
document.onkeydown = function(e) {
switch(e.keyCode) {
case 38: if (move('up')) addNewNum(); break;
case 40: if (move('down')) addNewNum(); break;
case 37: if (move('left')) addNewNum(); break;
case 39: if (move('right')) addNewNum(); break;
}
update();
}
function move(direction) {
let rotated = false, moved = false, merged = false;
if (direction === 'up' || direction === 'down') {
// Rotate board to left or right to use the left movement logic
rotateBoard();
rotated = true;
if (direction === 'down') {
board.reverse();
}
}
if (direction === 'right') {
// Reverse each row for right movement
board.forEach(row => row.reverse());
}
// Move and merge
for (let i = 0; i < 4; i++) {
// remove zeros
let cleanRow = board[i].filter(val => val !== 0);
// merge
for (let j = 0; j < cleanRow.length - 1; j++) {
if (cleanRow[j] === cleanRow[j + 1]) {
cleanRow[j] *= 2;
cleanRow[j + 1] = 0;
score += cleanRow[j];
merged = true;
}
}
// remove zeros again
cleanRow = cleanRow.filter(val => val !== 0);
// ensure row is the correct length by adding zeros
while (cleanRow.length < 4) {
cleanRow.push(0);
}
if (board[i].join(',') !== cleanRow.join(',')) moved = true;
board[i] = cleanRow;
}
if (direction === 'right') {
// Reverse back rows after right move
board.forEach(row => row.reverse());
}
if (rotated) {
if (direction === 'down') {
board.reverse();
}
rotateBoard(); // Rotate back the original orientation
}
return moved || merged;
}
function rotateBoard() {
// Transpose + reverse rows mimicking rotation
var newBoard = [];
for (let j = 0; j < 4; j++) {
let newRow = [];
for (let i = 0; i < 4; i++) {
newRow.push(board[i][j]);
}
newBoard.push(newRow.reverse());
}
board = newBoard;
}
function addNewNum() {
let placed = false;
while (!placed) {
let row = Math.floor(Math.random() * 4);
let col = Math.floor(Math.random() * 4);
if (board[row][col] === 0) {
board[row][col] = Math.random() < 0.9 ? 2 : 4;
placed = true;
}
}
}
function update() {
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let cell = document.getElementById(i.toString() + j.toString());
cell.innerHTML = board[i][j] === 0 ? "" : board[i][j];
coloring(cell, board[i][j]);
}
}
document.getElementById('score').innerHTML = score;
}
function coloring(cell, value) {
cell.style.backgroundColor = value === 0 ? '#FBEDDC' : `hsl(${Math.log2(value) * 45}, 70%, 85%)`;
cell.style.color = value > 4 ? 'white' : '#684A23';
}
function init() {
addNewNum();
addNewNum();
update();
}
init(); // Initialize the game
</script>
</body>
</html>
안녕하세요 소중한후루티9입니다.
코드를 살펴보니 방향키 함수에는 로직상의 오류가 보이지 않습니다. 하지만 브라우저마다 keyCode가 호환되지 않을 수 있습니다. 대신 key를 사용하여 이벤트를 처리하는 것이 더 좋습니다. 아래는 수정된 방향키 함수입니다:
javascript
코드 복사
document.addEventListener('keydown', function(event) { switch(event.key) { case 'ArrowUp': if (move('up')) addNewNum(); break; case 'ArrowDown': if (move('down')) addNewNum(); break; case 'ArrowLeft': if (move('left')) addNewNum(); break; case 'ArrowRight': if (move('right')) addNewNum(); break; } update(); });
이렇게 수정하면 방향키 입력이 더 잘 작동할 것입니다.