Unable to implement the checkCollision function within the Snake game using JavaScript

My latest project involves creating a Snake game using canvas in JavaScript. I've managed to set up most of the game, but I'm having trouble with the collision check. Whenever the snake hits itself or the wall, the game crashes because I can't figure out how to implement the checkCollision method I've defined.

<script>
//Code for creating the game canvas, drawing borders, and setting up the score
...

//Code for creating the Snake, Apple, and handling player input
...

//Code for detecting collisions and moving the snake
...

//Run the game loop
let snake = new Snake(); 
let apple = new Apple(); 
var aniTime = 100; 
function core () { 
    ctx.clearRect(0, 0, width, height); 
    drawScore(); 
    snake.move(); 
    snake.draw(); 
    apple.draw(); 
    drawBorder();
    timeOutId = setTimeout(core, aniTime);
    if (snake.checkCollision() === true) { //**the PROBLEM
        clearTimeout(timeOutId);
        gameOver();
    };
};
core();

//Handle game over condition
var gameOver = function () {
    clearTimeout(timeOutId);
    ctx.font = '60px Arial';
    ctx.fillStyle = 'Black';
    ctx.textAlign = 'center';
    ctx.textBaseLine = 'middle';
    ctx.fillText('Game Over', width / 2, height / 2);
};
</script>

Whenever there is a collision, I encounter the following error messages:

Uncaught TypeError: Cannot read properties of undefined (reading 'col')
at Snake.checkCollision (snake.html:148:43)
at core (snake.html:191:27)
at snake.html:196:13
Uncaught TypeError: Cannot read properties of undefined (reading 'col')
at Snake.checkCollision (snake.html:148:43)
at core (snake.html:191:27)
snake.html:129 
Uncaught TypeError: gameOver is not a function
at Snake.move (snake.html:129:21)
at core (snake.html:186:23)

Answer №1

It appears that there are a few minor errors that can easily be corrected:

  • gameOver is declared as a var after calling core(). To ensure its definition is hoisted to the top, declare it as a function (or call core() below var gameOver = ...)
  • timeOutId is utilized by both the core and gameOver functions. Declare it outside of those functions to ensure both have access.
  • Snake.prototype.checkCollision requires head as an argument, but core invokes it without one.
  • The self-collision loop begins at i = 0, leading to a situation where it always checks if the head collides with itself.

Here's an example that addresses all of these issues:

// Updated code snippet goes here... 

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 format a time in a 12-hour clock using JavaScript?

Is it possible to create a timer that performs an action after 12 hours? I want the timer to start at 6am and end at 6pm, lasting for exactly 12 hours. Additionally, I'm interested in converting my current 12-hour clock into a 24-hour format. I am se ...

Launch Google Maps within Facebox

When I try to open an edit formula within a jQuery Facebox, I encounter an issue. Under the form, there is a Google Map that should indicate the position of a given address with a marker using the geocoder. However, the map is not showing up within the fac ...

Change your favicon dynamically based on the user's online or offline status using Vue

I am currently working on setting up different icons to display when my browser is online (normal logo) and offline (greyed out logo). With Vue JS, I am able to detect the online and offline states, as well as set different favicons accordingly. However, t ...

Navigating through dynamic elements using Selenium

I'm having trouble extracting boxer information from the flashcore.com website using Selenium. The code I've written doesn't seem to be working properly. Can anyone point out where the error might be? The expectation is that Selenium should ...

Encountered difficulties logging in with MongoDB and Node.js

I encountered an issue while attempting to authenticate a user using MongoDB and Node.js. Although no errors are thrown, the system fails to provide the expected data after the user logs in. Below is a breakdown of my code. server.js var port=8888; va ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

PHP and Ajax Form Submission Directing to Backend PHP Script

While working on a portfolio, I encountered an issue with the contact form. When I click the submit button to send a message, instead of displaying the bootstrap alert message below the form, the page redirects to the PHP file. Although I receive the emai ...

Reduce the amount of time it takes for a Google AdWords Script to generate a

According to Google Script best practices, it is recommended to store operations in an array and then call the methods once all the operations have been constructed. This helps minimize response time each time a service is called. For example, let's ...

Ways to display a default view in React

I am working on a React website that has three different routes. My goal is to have the first route, named Home, automatically displayed when a user lands on the site. Below is the code snippet from my App.js: <Router> <Navigation /> <Sw ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

The issue of CSS not being applied to HTML content after being inserted via AJAX has been encountered

I've successfully implemented AJAX to retrieve specific page content from a database, but now I'm facing an issue: When it comes to the 'Contact' page, the form retrieved from the database (as HTML) is not applying the CSS styles I hav ...

What is the best way to extract a specific value from a line of data using JavaScript (JSON)?

My current task involves extracting the "correctAnswers" from a specific number. Let's take a look at this JSON example: { "questions": [ { "number": 3, "question": "☀️ ➕ ...

Obtaining the responseJSON property from a jQuery $.ajax object involves accessing the data returned

Recently, I encountered an issue with my JavaScript code that involves an AJAX request: $ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {} ...

Twilio - encountering difficulties processing phone number upon submission

I clicked on this link to follow the tutorial (you can find it via twilio.) and after completing all the necessary steps, I encountered an issue. Upon running localhost and entering a phone number, I did not receive any text message and the verification wi ...

Error message: "Unable to locate jQuery file within the node.js + Express application running on Heroku platform."

My current setup involves a node.js application with Express and express-handlebars deployed on Heroku. However, whenever I run the app, the console displays a 404 error for the jquery file, leading to subsequent failures for dependent libraries like Boots ...

Finding the index of a class using jQuery is posing some difficulties

I am facing a challenge with controlling multiple hidden modals on a webpage using a single block of JavaScript code. In my attempt to test whether I can access the correct close button with the class close, I am encountering an issue where my console.log ...

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

Having trouble retrieving user login information in Postman

I have encountered an issue while creating a REST API using Node js and expressJs. When attempting to create a user, I successfully implemented the following code: /** * save user data from the user model */ router.post("/users", async (req, res) => ...

Guide on adding HTML to a specific div element in jQuery by utilizing the keyword "(this)"

I have been working on a script for my PHP page in Wordpress to add titles to images in my photo gallery that open in a lightbox. Here's what I developed: $(".responsive1").bind("click", function() { $(this).("<div class='imgTitle ...