Is there a shorter method to continuously run a function based on keypress in a specific scenario?

What is the goal of my task?

My objective is to keep the movement of the TrumpHead going until another key is pressed to change its direction, similar to the game snake. I am considering creating multiple cases with functions containing cases within each one. Any suggestions or assistance would be greatly appreciated as I am new to Javascript.

Here is my current code

var width = 1000, height = 1000; // Defining Canvas Width and Height
var cvs = document.getElementById('Snake'); // Representing the Canvas
var ctx = cvs.getContext('2d'); // 2D Context

cvs.width = window.innerWidth; // Setting canvas width to match window
cvs.height = window.innerHeight; // Setting canvas height to match window

var img = new Image();
img.src = 'snakeHead.png';
var TrumpHead = createCanvasImage(100, 100, img);
window.addEventListener('keydown', this.checkOn, false);

function createCanvasImage(x, y, img) {
    this.image = img;
    this.x = x;
    this.y = y;
    this.width = img.width;
    this.height = img.height;
    return this;
}

function checkOn(e) {
    switch (e.keyCode) {
        case 37: // Left Key
            if (TrumpHead.x == cvs.width) {
                alert("You Lose"); 
            } else if (TrumpHead.x < 0) {
                alert("You Lose");
            } else {
                left();
                console.log("Pressed Left");
            }
            break;

        case 38: // Up Key
            if (TrumpHead.y < 0) {
                alert("You Lose");
            } else if (TrumpHead.y > cvs.height) {
                alert("You Lose");
            } else {
                up();
                console.log("Pressed Up");
            }
            break;

        case 39: // Right Key
            if (TrumpHead.x > cvs.width) {
                alert("You Lose");
            } else if (TrumpHead.x < 0) {
                alert("You Lose");
            } else {
                right();
                console.log("Pressed Right");
            }
            break;

        case 40: // Down Key
            if (TrumpHead.y < 0) {
                alert("You Lose");
            } else if (TrumpHead.y > cvs.height) {
                alert("You Lose");
            } else {
                down();
                console.log("Pressed Down");
            }
            break;
    }
}

function gameLoop() {
    checkOn();
    setTimeout("gameLoop()", 10);
}

function left() {
    TrumpHead.x = TrumpHead.x - 50;
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}

function right() {
    TrumpHead.x = TrumpHead.x + 50;
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}

function up() {
    TrumpHead.y = TrumpHead.y - 50;
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}

function down() {
    TrumpHead.y = TrumpHead.y + 50;
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    ctx.drawImage(TrumpHead.image, TrumpHead.x, TrumpHead.y, 50, 50);
}

Answer №1

To achieve the desired functionality, you will need to implement two separate loops in your code. One loop will be responsible for handling user input, while the other loop will handle the actual drawing on the display. By utilizing browser events, you can detect key input and update the state of your program accordingly based on the keys pressed. This state can then be used in your update loop to manipulate the display. Below is an example code snippet:

var movingLeft = false, movingUp = false;

document.body.onkeydown(function(e) { 
   switch(e.keyCode) { 
      case 38: 
          movingUp = true;
          movingLeft = false;
          break;
      case 37: 
          movingLeft = true;
          movingUp = false;
          break;
   }
});

// Update loop:

function loop() {
  if (movingLeft) {
    updateDisplayByLeftIncrement(); // Update display as needed
  else if(movingUp) {
     updateDisplayByUpIncrement(); // Update display as needed
  } // Repeat for other movement directions
}

// Utilize setInterval() to create a looping mechanism with a specified delay
setInterval(loop, timeOut);

Answer №2

In order to optimize program execution, it is essential to separate it into two distinct loops or pumps. This includes: 1) A dedicated input loop, 2) An update loop for processing data

Failing to do so will result in your scene updates being dependent on user input timing.

Best of luck with your programming endeavors!

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

Is it possible to read an XML response as a stream using Ext JS?

Requesting an XML response can sometimes result in a slow completion time due to certain constraints. Despite this, the data begins returning quickly. I am wondering if it is feasible to read the response stream in Ext JS before it is fully complete. My u ...

How come my uvmapped texture is flipping vertically when using iewebgl + threejs?

Currently in the process of developing a 3D viewer for game pads with the aim of customizing the pad using various colors and materials. Initially, I created a simple ".bin .js" loader with sample materials using Threejs r62 to create a visualizer prototy ...

When it comes to the CSS `:visited` pseudo-class, I have

I'm having trouble changing the color of the anchor tag and blurring the image after visiting the link. Despite my CSS code, only the color is changing and the image remains unchanged. Here's my CSS code: <style> .image123{ paddin ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Having difficulty accessing node_modules directory in JavaScript

I am confused about how to access node_modules for JavaScript. Can someone provide an example of calling module.exports from a node_module folder after installing a package with NPM in Node.js? File tree structure: There is a folder named 'ethereum&a ...

Custom styling options for Google Chart

I have been attempting to dynamically adjust the width and height of a google-chart directive by utilizing input field values. However, I am encountering an issue where the width and height are not updating as expected. Check out the Plunker here $scope. ...

Getting the value of a sibling select element when a button is clicked

Trying to retrieve the selected option value on button click has become a challenge due to multiple groups of buttons and select elements. The key seems to be using siblings somehow, but the exact method remains elusive... <div class="form-group" ng-re ...

Learn how to toggle the menu list visibility by clicking on a component in Vue

I seem to be having an issue with closing a menu item in vue and vuetify2. Here is the code snippet that I have: <v-menu transition="slide-y-transition" bottom left offset-y nudge-bot ...

Is there a way to verify if a variable is a generator function, for example, a function with the asterisk symbol and

Is there a foolproof method to determine if a function is a generator, like in the example below: let fn = function* () { yield 100; } if (fn instanceof ??) { for (let value in fn()) { ... } } I have only been able to come up with fn.to ...

Improprove jQuery code to eliminate redundancy

Is there a better way to improve the appearance of this code? Here is a condensed snippet of the HTML: <div id="template" style="display:none;"> <div style="position:relative;"> <fieldset> <img class="sm_kont" ...

Why isn't the transparency feature in graphicsmagick working?

Currently, I am utilizing the graphicsmagick npm package which can be found at https://www.npmjs.com/package/gm. In my attempt to write a piece of code similar to the one below, I am struggling to make it function properly with stream. The image file myimg ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

Is there a way to delay the start of this until a legitimate answer is provided in a pop-up window?

Is it possible to delay the loading of this content until a prompt box is answered with a valid response, and have it only appear once a month? Do I need anything beyond JS and HTML for this functionality? <script language="javascript"> function ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

Update the array in state by adding a new element using setState

How can I add a new element to an array using setState? Consider the following data: this.state = { items : [ { "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }, { "id" : "24", "parent" : "dwdw", "text" : "Root node" }, { "id" ...

Unable to fetch the Observable value

I have a function that returns an Observable<Person[]>, where Person is my model: export interface Person { id: string; age: number; } Now in my component.ts, I am calling this function and aiming to retrieve the array to display it in the HTML ...

Eliminate the ending slash from your Nuxt application

Hello, I am currently working on a Nuxt Application and encountering an issue. After running the npm run build command and starting it with npm start, there seems to be an inconsistency with trailing slashes. During the build, the URL appears without a t ...

What is the best way to attach a tag or label onto multiple objects so that it remains facing the camera whenever the user interacts with the objects?

My goal is to create a tag or label that always faces the camera when a user clicks on an object, even if that object is rotated. How can I achieve this? I've been advised to use an Orthogonal camera, but I'm not sure how to do that. Additionall ...

Is it possible to display a title tooltip only when the CSS ellipsis feature is active in a React component?

Issue: I am trying to find a neat solution to display a title tooltip on items that have a CSS ellipsis applied, within a React component. Approaches Attempted: I created a ref, but it only exists after componentDidUpdate. Therefore, I force an update w ...

Innovative idea for a time management system based on timelines and scheduling

My latest project involves creating a scrollable scheduler, inspired by vis-timeline and built using Vue.js. One of the main challenges I'm facing is achieving smooth infinite scrolling in all directions (past and future). I must confess that I&apo ...