我正在和JavaScript一起做这个练习,我们应该用Javascript创建一个忍者吃豆人风格的游戏,然后保持分数。忍者吃寿司,而我每吃一份寿司。
目前的行为是,当忍者上升或下降时,我可以存储分数。问题是,当忍者水平移动时,得分只会计算第一个寿司。第二和第三苏轼不算在内。对于垂直和水平移动,我确实使用了相同的逻辑。
这是我的密码。添加了上下文的全部代码,但有问题的部分在"document.onkeydown = function(e) {“之后。
<script type="text/javascript">
var world = [
[1,1,1,1,1],
[1,0,2,2,1],
[1,2,1,2,1],
[3,2,2,2,3],
[1,2,1,2,1],
[1,2,2,2,1],
[3,2,1,2,3],
[1,2,2,2,1],
[1,1,1,3,1],
]
var worldDict = {
0 : 'blank',
1 : 'wall',
2 : 'sushi',
3 : 'onigiri'
}
var ninjaScore = 0;
function drawWorld() {
var output = "";
for (var row = 0; row < world.length; row++) {
output += "<div class='row'></div>"
for (var x = 0; x <world[row].length; x++) {
output += "<div class='" + worldDict[world[row][x]]+"'></div>"
}
output += "</div>"
}
document.getElementById('world').innerHTML = output;
}
drawWorld();
var ninjaman = {
x: 1,
y: 1
}
function drawNinjaMan() {
document.getElementById('ninjaman').style.top = ninjaman.y * 40 + "px"
document.getElementById('ninjaman').style.left = ninjaman.x * 40 + "px"
}
drawNinjaMan();
document.onkeydown = function(e) {
if (e.keyCode == 40) { //DOWN
if (world[ninjaman.y + 1][ninjaman.x] != 1) {
ninjaman.y++;
if (world[ninjaman.y + 1][ninjaman.x] == 2) { //Checking if next block is sushi; adding to score
ninjaScore = ninjaScore + 1;
}
}
}
if (e.keyCode == 38) { //UP
if (world[ninjaman.y - 1][ninjaman.x] != 1) {
ninjaman.y--;
if (world[ninjaman.y - 1][ninjaman.x] == 2) { //Checking if next block is sushi; adding to score
ninjaScore = ninjaScore + 1;
}
}
}
if (e.keyCode == 37) { //LEFT
if (world[ninjaman.y][ninjaman.x - 1] != 1) {
ninjaman.x--;
if (world[ninjaman.y][ninjaman.x - 1] == 2) { //Checking if next block is sushi; adding to score
//Somehow this is returning false on the second key press; need to check why
ninjaScore = ninjaScore + 1;
}
}
}
if (e.keyCode == 39) { //RIGHT
if (world[ninjaman.y][ninjaman.x + 1] != 1) {
ninjaman.x++;
if (world[ninjaman.y][ninjaman.x + 1] == 2) { //Checking if next block is sushi; adding to score
//Somehow this is returning false on the second key press; need to check why
ninjaScore = ninjaScore + 1;
}
}
}
world[ninjaman.y][ninjaman.x] = 0;
drawWorld()
drawNinjaMan()
}
有人能指出我出了什么错吗?
此外,值得称赞的是:这是在Dojo编码(https://www.codingdojo.com/)入门课程前的一个练习。他们提出了大部分的代码和练习本身。
发布于 2018-05-26 02:59:44
我想是因为你把忍者放在寿司上面,然后在你移动的方向检查前面的那个块。你所有的动作都是错误的,向上,向下,左和右。
这应该能解决问题。https://plnkr.co/edit/VCsa2cTWYaUn2jiTgmS4?p=preview
if (world[ninjaman.y][ninjaman.x-1] == 2) { //Checking if 应该是
if (world[ninjaman.y][ninjaman.x] == 2) { //Checking if https://stackoverflow.com/questions/50538763
复制相似问题