The issue of apples failing to spawn correctly in the Snake game

My Snake game seems to have a bug that causes some strange behavior whenever an apple is collected. Upon collision, the apple disappears and a new one spawns in a new location, but then the original apple reappears in its initial spot. Subsequently, when the newly spawned second apple is collected, the first two apples vanish and a third one appears in a new location. This cycle continues with the previous apples reappearing in their original locations.

It appears that only the newest spawned apple is capable of detecting collisions with the snake and triggering the spawning of new apples.

In my code, I have an Apple class that keeps track of its x and y coordinates, and a SnakeGame class which consists of an apple and a snake. When an apple is collected, I set the SnakeGame.apple property to null and create a new Apple object with new x,y coordinates to set it as the new SnakeGame.apple object.

If you have any ideas on how to solve this issue, I would greatly appreciate your input!

If you wish to experiment with my code, here is a fiddle link: https://jsfiddle.net/gabewest1/knuxsa5t/1/

Apple Class:

class Apple {
  constructor(x, y) {
    this.xPos = x;
    this.yPos = y;
    this.radius = 10;
  }

  draw(ctx) {
    ctx.fillStyle = "black";
    ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI);
    ctx.fill();
  }

  position(x, y) {
    if (x > -100 && y > -100) {
      this.xPos = x;
      this.yPos = y;
    } else {
      return {
        x: this.xPos,
        y: this.yPos
      };
    }
  }
}

SnakeGame Class:

class SnakeGame {
    constructor(snake) {
        this.ctx = $("#myCanvas")[0].getContext("2d");
        this.canvas = $("#myCanvas")[0];
        this.init();

        this.frameLength = 500;
        this.apple = this.createApple();
        this.snake = snake;

        this.score = 0;
        this.gameloop();
    }

    createApple() {
        var xPos = Math.floor(Math.random() * this.canvas.width);
        var yPos = Math.floor(Math.random() * this.canvas.height);
        var apple = new Apple(xPos, yPos);
        return apple;
    }

    gameloop() {
        var ctx = this.ctx;

        this.snake.move();

        if (this.collision()) {
            console.log("There was a collision!");
            this.score++;
            this.increaseSnake();
            this.apple = null;
        }

        ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        this.snake.draw(ctx);

        if (this.apple) {
        this.apple.draw(ctx);
        } else {
            this.apple = this.createApple();
        }

        setTimeout($.proxy(this.gameloop, this), this.frameLength);
     }
}

Answer №1

To start, insert ctx.beginPath(); prior to forming the arc.

ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI);
ctx.fill();

Using the ctx, each arc created is recorded and fill is applied to all of these shapes.

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

What is the best way to create a backup copy of my project using git?

To ensure the safety of my project, I took the necessary steps to back it up. First, I initialized a repository using git init Following that, I committed all files by executing git add . git commit -am "first commit" Now, the next step involves pushin ...

What is the best way to change any timezone to the local timezone using JavaScript?

Check out the code snippet below that is designed to convert a date to the local timezone: function convertDateToServerDate(incomingDate) { var serverOffset = new Date(); serverOffset = serverOffset.getTimezoneOffset(); var outgoingServerDate = new Date ...

Decide whether an angular rotation is within the camera's field of vision inside a spherical object

Seeking assistance with a three.js project. I have set up a camera inside a SphereGeometry at position (0,0,0) and am projecting an image on the sphere's wall. My goal is to create interactive JS elements outside of the threejs framework that respond ...

Encountering issues with bidirectional data binding functionality

I have integrated a pagination component from ng-bootstrap into a generic component that includes a select dropdown to choose the number of items per page. I triggered an event from this generic component and caught it in the parent component (member-list. ...

Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on Everyth ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

What approach provides the most effective way to navigate through an NPM Package?

I have an idea to enhance a particular open source NPM package. Although I understand the necessary steps, it would be incredibly beneficial to have the ability to debug the package while it is in operation. Is this achievable? ...

The presence of '<!DOCTYPE html>' causes my website's content to compress

After including !DOCTYPE html, I noticed that the first section of my website is shrinking even though its height is set at 120%. I attempted various solutions from stack overflow like setting the height of HTML and body to 100%, but none of them resolved ...

A helpful guide on using workbox to effectively cache all URLs that follow the /page/id pattern, where id is a

Looking at this code snippet from my nodejs server: router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , va ...

Convert HTML to PDF using AJAX for seamless downloading

I am currently using html2pdf to generate PDFs from WordPress posts within a multi-site installation. The setup is working well and here is how it is structured: On my homepage, I have a link: <a target="_blank" id="downloadPDF" href="<?php echo ge ...

How to effectively utilize JSON responses with jQuery Mobile?

I've been facing an issue with working on my JSON result in JavaScript. Can anyone provide some insight? Even though the JSON call returns a success status code (200) and I can view the data in Firebug, no alert is being displayed. $(document).on(& ...

Encountering an issue where props are receiving a value of undefined within a component that is

After receiving a JSON response from getStaticProps, I double-checked the data by logging it in getStaticProps. The fetch functionality is working smoothly as I am successfully retrieving the expected response from the API. import Layout from '../comp ...

Calculating the depth of a webpage with Python

I need help determining the depth of a website through Python. The depth of a subwebsite is defined as the number of clicks needed to reach it from the main website (e.g. www.ualberta.ca). For example, if a subwebsite like www.ualberta.ca/beartracks requir ...

Error: The jQuery Class is returning an undefined value

I have been working on creating a basic AJAX request class in jQuery. However, I've encountered an issue with the 'process' function where I can get the response from the variable 'response'. When I return 'response', it ...

Error message: "wp is not defined" appears when using TinyMCE, Bootstrap Modal, and URL Parameter together

Currently utilizing Bootstrap 5 alongside WordPress 6.2 In the process of developing a WordPress plugin, where I have successfully created a Dashboard and an All Content page. On the Dashboard page, users can find a list of the most recently created cont ...

Text affected by mix-blend-mode glitch

Currently, I am experimenting with knockout text using the mix-blend-mode property. An interesting issue arises when I examine the responsiveness of my design by utilizing Developer tools in the browser console - there are faint lines that momentarily appe ...

Unable to invoke Parse.Promise._continueWhile

I have attempted to use the conditional promise loop outlined below, but it never progresses to the second function. I have searched extensively for a solution, but have not yet found one. Any ideas you can provide would be greatly appreciated. Thank you. ...

What's the difference between using find_all on a bs4.element.ResultSet object and a list in Beautiful Soup

When I use the find_all method on a beautifulsoup object, it returns either an bs4.element.ResultSet object or a list. However, I am unable to directly apply the find_all method on the bs4.element.ResultSet object. One way to work around this is by loopin ...

Tips for customizing CSS for the ValidatorCallout Extender in an ajax tool

I am currently attempting to implement the ValidatorCallout Extender feature from the asp.net Ajax website. However, I am struggling with customizing the CSS for the popup validator. ...

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...