Pacman-inspired Javascript game - scoring limitations on horizontal paths

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.

Answer №1

It seems the issue lies in moving the ninja onto a sushi and then checking the block ahead in the wrong direction. Your movements should be adjusted accordingly in order to fix this.

Try implementing the following solution: https://plnkr.co/edit/VCsa2cTWYaUn2jiTgmS4?p=preview

if (world[ninjaman.y][ninjaman.x-1] == 2) { //Checking if 

Update the code to:

if (world[ninjaman.y][ninjaman.x] == 2) { //Checking if 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered error: "Node.js and socket.io: Address already in use"

Experimenting with chat using Node.js and socket.io Currently, I am running Ubuntu 12.04 as a user and have a folder "pp" on my desktop. In this folder, I have placed a server file named server.js. Below is the client code: $(document).ready(function() ...

Choosing2 - incorporate a style to a distinct choice

Let's talk about a select element I have: <select id="mySelect"> <option>Volvo</option> <option value="Cat" class="red">Cat</option> <option value="Dog" class="r ...

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

What is the best way to correlate two arrays of strings with one another?

I am working with two sets of data: First Set: let training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ]; Second Set: let skill = [ "P1, Shooting", "P2, Passing", ]; I need to combine both arrays bas ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

Experiencing a DNS error while running a JavaScript script using Node.js

const { Client, EmbedBuilder, GatewayIntentBits, Collection, Events, Partials } = require("discord.js"); require("dotenv").config(); const { Guilds, GuildMembers, GuildMessages } = GatewayIntentBits; const { User, Message, GuildMember, ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...

What is the best way to group Angular $http.get() requests for efficiency?

My challenge involves a controller that must retrieve two distinct REST resources to populate two dropdowns. I want to ensure that neither dropdown is populated until both $http.get() calls have completed, so that the options are displayed simultaneously r ...

Ways to verify if the user has inputted a typeahed value

My code snippet looks like this: var students = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('fullName'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { ...

Create a boolean flag in Java using JavaScript

Hey there, I'm working on a project where I need to detect the user's browser in JavaScript. For Safari browsers, I have to download an audio file, while for every other browser I need to play the audio. Currently, my code can correctly identify ...

Utilizing PHP with WordPress: Execute the specified .js file if the link includes the ID "124"

I am currently using WordPress on my local server and I want to set up a redirect after a user submits the contact form through the Contact Form 7 Plugin. I am looking to redirect them to a specific page, but so far, the plugins I have tried have caused th ...

PUPPETER - Unpredictable pause in loop not functioning as expected

Having an issue with this specific part of the code: (async () => { const browser = await puppeteer.launch({ headless: false, // slowMo: 250 // slow down by 250ms }); const page = await browser.newPage(); //some code // CODE ABOVE WORKS, ...

The response detail error code 2 indicates that the post method API body check has failed within the Agora REST API, resulting in

const Authorization = `Basic ${Buffer.from(`${config.CUSTOMERID}:${config.CUSTOMER_SECRET}`).toString("base64")}`; const acquire = await axios.post(`https://api.agora.io/v1/apps/${config.agoraAppId}/cloud_recording/acquire`,{ ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

When trying to import the "firebase/app" module, an error occurred stating that the default condition should be the last one to be considered

Greetings! I am diving into the world of webpack and firebase. Every time I use: import { initializeApp } from "firebase/app"; I encounter this error message: https://i.sstatic.net/tvuxZ.png Here is my file structure: https://i.sstatic.net/406o ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...

Combining a complete hierarchy of Object3D/Mesh into one merged entity

I'm currently working on a project that involves dynamically generating trees using simple cubes for branches and leaves in the early prototype stages. Each tree consists of a hierarchy of cubes nested with rotations and scaling to create the final st ...

What could be causing Node Pdfkit to sometimes generate a corrupted file within my code?

I've encountered an issue with my function that generates a PDF file and sends it via email using `pdfkit` and `nodemailer`. Occasionally, I receive a file that cannot be opened. I'm unsure why this happens sporadically while it works fine most o ...

Is there a problem with textbox support for multi-line strings?

I'm having trouble getting a textbox to display multiple lines of text. For instance, when I copy three lines of text from Microsoft Word and paste it into the textbox, only the first line appears. The other two lines are not showing up, and I'm ...