I'm currently working on a fun project involving JavaScript that requires creating a ninja-like game similar to pacman. The objective is to control the ninja to eat sushis and earn points based on each sushi eaten.
At the moment, I am facing an issue with scoring points. While the scoring mechanism works fine when the ninja moves up or down, it fails to count the second and third sushis when moving horizontally. I have used the same logic for both vertical and horizontal movements.
Below is the code snippet in question. The complete code is provided for context, but the relevant section causing the issue is located after "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
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
ninjaScore = ninjaScore + 1;
}
}
}
world[ninjaman.y][ninjaman.x] = 0;
drawWorld()
drawNinjaMan()
}
I would appreciate if someone could help identify the issue with my code.
It's worth mentioning that this exercise is part of the Coding Dojo pre-bootcamp course (), where most of the code and the exercise content were provided.