Прежде всего, я бы предложил капитальный ремонт. Игра, которую вы получили, называя все эти идентификаторы, не является масштабируемой или практичной. Это нарушает принцип СУХОГО (посмотрите).
Вместо того, чтобы иметь див с игроком id
, просто позвольте .grid-square
дивам принять класс .contains-player
. Таким образом, вы не будете перетасовывать раскладку каждый раз, когда ваш игрок перемещается.
Вы хотите иметь массив всех элементов div, а затем использовать некоторую логику, например, чтобы определить, что должно произойти вслучай перемещения в направлении. Это то, что я бы сделал, пожалуйста, адаптируйтесь к вашему вкусу и потребностям.
window.onload = function() {
const gameHeight = 10;
const gameWidth = 10;
const container = document.getElementById("grid-container");
for(let i = 0; i < gameWidth * gameHeight; i++) {
container.innerHTML += `<div class="grid-square"></div>`;
}
const gridSquares = document.querySelectorAll(".grid-square");
gridSquares[0].classList.add("contains-player");
let playerX = 0,
playerY = 0;
function move(direction) {
const playerDiv = document.querySelector(".grid-square.contains-player");
playerDiv.classList.remove("contains-player");
let newPlayerDiv;
switch(direction) {
case "left": playerX--; break;
case "up": playerY--; break;
case "right": playerX++; break;
case "down": playerY++; break;
// ...
}
newPlayerDiv = gridSquares[(playerY * gameWidth) + playerX]
newPlayerDiv = gridSquares[(playerY * gameWidth) + playerX];
// Add some logic in here to make sure player isn't offscreen;
newPlayerDiv.classList.add("contains-player");
}
function toBeExecutedOnKeyDown(event) {
let direction;
switch(event.which) {
case 37: direction = "left"; break;
case 38: direction = "up"; break;
case 39: direction = "right"; break;
case 40: direction = "down"; break;
}
if(direction) {
event.preventDefault(); // Prevent screen from moving around
// More readable
move(direction);
}
}
window.onkeydown = toBeExecutedOnKeyDown;
}
:root {
--game-size: 10;
--game-scale: 10px;
--game-actual-size: calc(var(--game-size) * var(--game-scale));
}
#grid-container {
width: var(--game-actual-size);
height: var(--game-actual-size);
clear: both;
}
#grid-container .grid-square {
width: var(--game-scale);
height: var(--game-scale);
float: left;
background-color: grey;
}
.grid-square.contains-player {
background-color: red !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<script src="./script.js"></script>
<link rel="stylesheet" href="./style.css"/>
</head>
<body>
<div id="grid-container">
<!--
This will be filled with divs like the following when the JS loads
<div class="grid-square"></div>
The div containing the player will look like this
<div class="grid-square contains-player"></div>
-->
</div>
</body>
</html>