Here is a way to nest an interval within a switch case statement of a keycode without permitting the user to tab more than once

As I work on creating a Pacman game, I encountered an issue with the movement logic. I implemented a switch statement and interval to ensure that when the user presses the right arrow key once, Pacman will move continuously to the right. However, I noticed that if I press the tab key twice, it moves twice as fast. Additionally, if I alternate between pressing the right and left arrow keys, Pacman moves in a zigzag pattern.

Below is the initial code without using intervals:

JS code without interval:

const grid = document.querySelector('.grid');
const scoreEl = document.getElementById('score');
const width = 28;
let squares = [];
let score = 0;

// Layout array containing information about the game board layout
const layout = [
    // board layout data here...
];

// Various elements represented by numbers in the layout array
// Functions for creating the game board
function createBoard() {
    // Create board logic here...
}

createBoard();

// Initial position of Pacman
let pacManPosition = 490;
squares[pacManPosition].classList.add('pac-man');

// Function to handle Pacman movement based on keyboard input
function move(e) {
    // Movement logic here...
}
document.addEventListener('keyup', move);

JS Code with intervals:


//
let myInt = '';
//
function move(e) {
    // Updated movement logic using setInterval here...
    
}

I am seeking advice on how to address this issue?

Answer №1

A helpful commenter suggested clearing the interval after each key pressed, which was a revelation to me.

The solution provided was:

case 'ArrowUp':
            clearInterval(myInt);
            myInt = setInterval( function () {
                //console.log('up')
                if (!squares[pacManPosition - width].classList.contains('wall')) {
                    powerPelletsEaten();
                    squares[pacManPosition].classList.remove('pac-man');
                    pacManPosition -= width;
                    squares[pacManPosition].classList.add('pac-man');
                    pacdotsEaten();
                }
            }, 400)
        break;

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

The checkbox fails to display as checked when the value is set to true

I have integrated iCheck into my angular application. It's working well, except for one issue: when I set the checkbox value to true in my controller, it doesn't show up as checked when the page is loaded. Controller $scope.basicIntake = {}; $s ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

function for app.get callback in express.js

Hey there, I'm a bit puzzled by the syntax of the get route function because there seem to be two versions. Here's an example of some code: First one: app.get('/users', function(req,res){ ... }); Second one: app.get('u ...

How to eliminate Internet Explorer error messages

Encountering the following error message in IE8 "Do you want to view the webpage content that was delivered securely" To prevent this error, we must adjust this setting "Internet options -> Security -> Internet -> Custom -> Miscellaneous ...

Combining two arrays by finding common elements

Currently, I am working on a project where I retrieve data from the server, and each piece of data has to adhere to a specific format: const DATA = [ { title: {title: 'Main dishes'}, data: [ {_id: 1, type: 'Pizza'}, ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

What is the reason behind the lack of preservation of object state when using Promises?

Here is a code snippet to consider: class ClientWrapper { private client: Client; constructor() { this.client = new Client(); } async connect() : Promise<void> { return this.client.connect(); } async isConne ...

"HTML and JavaScript: The search functionality fails when trying to search for a string that is sourced from an array

Could someone assist me with a comparison issue I'm encountering? I am trying to use the includes() method to compare a list in a table with a list of names stored in a string. Strangely, when I hardcode the string directly into the includes() method, ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

I'm having trouble with my Rock Paper Scissors script. The console is showing an error message: "Uncaught SyntaxError: Identifier 'playerSelection' has already been declared."

Currently delving into the world of JavaScript, I've embarked on a project to create a console-based Rock Paper Scissors game. Here's the code snippet that I've come up with: <!DOCTYPE html> <html> <body> <script> ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

My goal is to create a backend platform similar to Kinvey, utilizing Node.js, Sails.js, and MongoDB

Hey there! I'm looking to develop a backend service similar to Kinvey (but for HTML and HTML5) using node.js, sails.js, and mongodb. With this service, I want the capability to create, post, update, and delete data just like you can with Kinvey. Here& ...

The functionality of GET_POST is not functioning properly

I've encountered an issue with my PHP webpage and JavaScript function: function send_answer(){ $.ajax({ type: 'POST', url: '../path2file/file_mine.php', data: {dbf1:1, us:1, re:1}, success: relo ...

Guide to selecting a checkbox using its unique identifier with a specific key press

Does anyone know how to create a script that will automatically click a checkbox when the 'c' key is pressed? I would appreciate any guidance or assistance in creating this script. This is the desired functionality: $("#cHideChat").click(); ...

Error: bundling unsuccessful: Issue occurred while attempting to locate module `react-native-vector-icons/Feather`

Implementing a Flatlist from the React Native library in my React Native project. Managed to install all necessary libraries. package.json "dependencies": { "feather-icons-react": "^0.3.0", "react": "16.6.3", "react-native": "0.57.8", " ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Saving JSON Data into my HTML document

Currently, I am in the process of learning about API's at school which means my knowledge of jQuery is quite limited. However, I have a specific task that involves making an API call and using the retrieved information. Recently, I conducted an ajax ...

The THREE.js FBXLoader mistakenly identifies .png files as .psd files, causing issues with loading materials

While using the THREE.js FBXLoader to import a .fbx file, I noticed that the model is only partially loaded, and the alpha textured parts are not loading at all. An error message I encountered is: FBXLoader: PSD textures are not supported, creating emp ...

jQuery - Creating an organized hierarchy list

My website's DOM structure is shown below: <ul> <li id="Browse"> Browse <ul id="browse-one"> </ul> </li> </ul> At the bottom of the page, my jQuery script looks like this: $("#Brow ...