试图为我的外星人创建一个for循环,让他们在点击eventlistener按钮后在网格上曲折前进,但没有成功



语法和/或逻辑有问题吗?外星人只是没有在我建造的网格上移动。当游戏加载时,启动按钮的eventlistener会触发外星人。目的是让外星人向左移动一个盒子,然后向下移动一排,然后向右移动一个箱子,再向下移动一行。这就是我想要用这些动作创造的循环。

function aliensMove() {
for (i = 0; i < 1; i++)
if cell.addEventListener('click', ('.start') => {     
(alien > ((gridSize) - width - 1)) {
return
}
cells[alien].classList.remove('alien')
alien = alien + width
cells[alien].classList.add('alien')
if (alien > ((gridSize) - width - 1)) {
return
}
cells[alien].classList.remove('alien')
alien = alien + width
cells[alien].classList.add('alien')
if (alien === 0) {
return
}
cells[alien].classList.remove('alien')
alien = alien - 1
cells[alien].classList.add('alien')
break
if (alien > ((gridSize) - width - 1)) {
return
}
cells[alien].classList.remove('alien')
player = player + width
cells[alien].classList.add('alien')
}

你的问题看起来很有趣,所以我试了一下。我并没有真正理解你的代码,所以这可能不会真正回答你的问题,但它可能会给你一些想法。点击代码下的蓝色按钮试试:

var $grid = document.getElementById('grid'),
width = 40,
height = 10,
$rows = makeGrid($grid, width, height);
function makeGrid($container, width, height) {
var $rows = [];
for (var y = 0; y < height; y++) {
var $row = document.createElement('div');
$row.className = 'row';
$rows.push([]);
for (var x = 0; x < width; x++) {
var $cell = document.createElement('div');
$cell.className = 'cell';
$row.appendChild($cell);
$rows[y].push($cell);
}
$container.appendChild($row);
}
return $rows;
}
function Alien($rows, x, y) {
this.$rows = $rows;
this.x = x;
this.y = y;
// Create an array of moves you will loop through
this.moves = ['left', 'down', 'right', 'down'];
this.toggleAlienClass(true);
}
Alien.prototype.move = function() {
this.toggleAlienClass(false);
switch (this.moves[0]) {
case 'left':
this.x -= 1;
break;
case 'right':
this.x += 1;
break;
case 'up':
this.y -= 1;
break;
case 'down':
this.y += 1;
break;
}
this.toggleAlienClass(true);
// Remove the first move and push it to the end
this.moves.push(this.moves.shift());
}
Alien.prototype.toggleAlienClass = function(show) {
if (this.$rows.length > this.y && this.$rows[this.y].length > this.x) {
this.$rows[this.y][this.x].classList[show ? 'add' : 'remove']('alien');
}
}
var aliens = [
new Alien($rows, 10, 2),
new Alien($rows, 20, 2),
new Alien($rows, 30, 2)
];
setInterval(function() {
aliens.forEach(function(alien) {
alien.move();
});
}, 500);
#grid {
background: #222;
width: 40em;
margin-left: auto;
margin-right: auto;
}
.row:after {
content: "";
display: block;
clear: both;
}
.cell {
width: 1em;
height: 1em;
float: left;
}
.cell.alien {
background: center / contain no-repeat url('https://files.gamebanana.com/img/ico/sprays/render_9.gif');
}
<div id="grid"></div>

最新更新