Snake size not increasing after eating food

In summary, this conversation discusses a specific code and how to increase the size of the snake in the game when it eats food. The expert advises the use of a single object to store all the variables, and gives a hint to think about where the coordinates of the new element should be set. They also encourage the asker to take the time to debug their own code with occasional hints, rather than expecting someone to give them the full working code. They mention that ChatGPT and some users on Stack Overflow may not be reliable sources for code debugging.
  • #1
shivajikobardan
674
54
TL;DR Summary
snake game javascript
Relevant code:

JavaScript:
if (food.x === snake[0].x && food.y === snake[0].y) {
    // increase the size of the snake
    snake.push({
      x: snake[snake.length - 1].x,
      y: snake[snake.length - 1].y    });

where snake is an array of objects. Each object is x and y coordinates of snake position and food is an object with x and y coordinates randomly placed.

Here's the full code:
 
Technology news on Phys.org
  • #2
First I strongly encourage you to stop scattering variables representing state around in your code (e.g. let d half way down). Gather all of these into a single object declared before anything else:
JavaScript:
const state = {
  // Current direction of the snake (could have a better name like `currentDirection`).
  d: 'right',
  // Array of coordinates of the elements of the snake.
  snake: [{ x: 15, y: 15 }],
  // ...
};
This will save you a LOT of time, but more importantly it will also save time for anyone else trying to help you.

Now as to your question think about where you want the coordinates of the new element to be after eating food to be. Then look at x: snake[snake.length - 1].x and think where you are actually setting the coordinates to be.
 
Last edited:
  • Like
  • Informative
Likes Wrichik Basu and Vanadium 50
  • #3
@pbuk just humble request, is it illegal to share the code in this forum or something? I've tried a lot and failed. So, would not it be good to share the code with me now? Or is stackoverflow the only place?
Those who are willing to learn will still learn even if you share code, those unwilling to learn won't even if you don't. Not sharing code in a programming problem where someone has gave that much try is just funny.
 
  • Skeptical
Likes Wrichik Basu
  • #4
shivajikobardan said:
@pbuk just humble request, is it illegal to share the code in this forum or something? I've tried a lot and failed. So, would not it be good to share the code with me now? Or is stackoverflow the only place?
You are asking us to correct the logic of your program. Well and good. We can help with that, and @pbuk did help with that:
pbuk said:
Now as to your question think about where you want the coordinates of the new element to be after eating food to be. Then look at x: snake[snake.length - 1].x and think where you are actually setting the coordinates to be.

Now, you are basically expecting to be spoon-fed the correct version of the code instead of being given hints where to find the issues. This is something we prefer not to do. In my personal opinion, in the case of programming, you will learn a lot more by debugging your code yourself with occasional hints from others rather than someone just giving away the full code with necessary changes made, unless the error is not logical but syntactical. That's how I learnt programming myself.
 
Last edited:
  • Like
Likes Vanadium 50, DrClaude, Mark44 and 1 other person
  • #5
looks like I should be paying to a tutor instead :D thanks for your responses.
 
  • Skeptical
Likes Vanadium 50
  • #6
btw stackoverflow and chatgpt both thinks the code should be working. I also don't see anything wrong with the code even though I've read your comments.
 
  • #7
Thread title: Snake size not getting increased after eating food

shivajikobardan said:
btw stackoverflow and chatgpt both thinks the code should be working. I also don't see anything wrong with the code even though I've read your comments.
Whether you see it or not, the thread title you chose indicates that you know something is wrong with the code. The fact that ChatGPT and some random users on stackoverflow think that the code should be working does not reflect well on them.

pbuk said:
Now as to your question think about where you want the coordinates of the new element to be after eating food to be. Then look at x: snake[snake.length - 1].x and think where you are actually setting the coordinates to be.
This is a very strong hint.

Wrichik Basu said:
In my personal opinion, in the case of programming, you will learn a lot more by debugging your code yourself with occasional hints from others rather than someone just giving away the full code with necessary changes made, unless the error is not logical but syntactical.
I couldn't agree with this more. Seeing someone do something and doing the same thing yourself are two entirely different things. And to elaborate, one aspect of effective debugging is to predict beforehand what some section of code will produce, and then using the debugger to verify that prediction or tell you that for some reason, your prediction was incorrect.
 
  • Like
Likes Wrichik Basu
  • #8
shivajikobardan said:
btw stackoverflow and chatgpt both thinks the code should be working.
ChatGPT is not even supposed to check your code.

I found your question on Stack Overflow: https://stackoverflow.com/q/75368306/8387076

One user commented that it works for them. They posted a link, where I see just a white screen. No HTML, no CSS and only some JS. A white screen. No snake. No boxes. Doesn't even make sense.

The MWE you posted on SO isn't even enough to reproduce what you are trying to do.

Also, there is a difference between "should be working" and "is working".
shivajikobardan said:
I also don't see anything wrong with the code even though I've read your comments.
From the output of the code sample you posted in the OP, I can confirm it's not working, even though I am illiterate in JS. In addition to the fact that the snake size doesn't increase, if the snake goes out of the boundary, it never returns.

If everything is fine, why post a thread here and a question on SO?
 
  • #9
shivajikobardan said:
chatgpt
I use fortune cookies. Tasatier and no less reliable.
 
  • Haha
  • Like
Likes fresh_42, Wrichik Basu and Tom.G
  • #10
The code has a few problems.

First, you only ever move the first segment of the snake. And second, when you grow the snake, you need to add the new segment to the position where the last segment was before it moved. And then what happens if the snake goes out of bounds or self intersects?

You might try to get some paper and pencil and draw the snake, and then try to think through what things should happen step by step when it updates. Then maybe try putting those steps in comments first, and then carefully add the code to implement the steps.

Here is an example with pseudocode of how your draw function could work, if you get stuck:

One way to think about it: move each non head segment to the position of the segment in front of it, move the head segment in the current direction, and if it eats food, add a new segment where the last one used to be.
Code:
// save last segment position before moving it
lastSegPrevious = segments.last

// move each non-head segment to the position of the segment in front of it
for( i = N-1; i >= 1; --i)
    segments[ i ] = segments[ i - 1 ]

// move the head in the current direction
segments[ 0 ] = += d

// What if it goes out of bounds?
<?>

// check if snake eats food
if segment[ 0 ] == foodPos
    // add new segment where the last segment used to be
    segments.push( lastSegPrevious )

// Self intersection?
<?>

draw everything
 
Last edited:
  • Care
Likes Wrichik Basu
  • #11
@Wrichik Basu impressed by your stuffs(apps and github). Would love to hear how you achieved this? How do you achieve problem solving logic?
 
  • #12
Jarvis323 said:
The code has a few problems.

First, you only ever move the first segment of the snake. And second, when you grow the snake, you need to add the new segment to the position where the last segment was before it moved.

You might try to get some paper and pencil and draw the snake, and then try to think through what things should happen step by step when it updates. Then maybe try putting those steps in comments first, and then carefully add the code to implement the steps.

Here is an example with pseudocode of how your draw function could work, if you get stuck:

One way to think about it: move each non head segment to the position of the segment in front of it, move the head segment in the current direction, and if it eats food, add a new segment where the last one used to be.
Code:
// save last segment position before moving it
lastSegPrevious = segments.last

// move each non-head segment to the position of the segment in front of it
for( i = N-1; i >= 1; --i)
    segments[ i ] = segments[ i - 1 ]

// move the head in the current direction
segments[ 0 ] += d

// check if snake eats food
if segment[ 0 ] == foodPos
    // add new segment where the last segment used to be
    segments.push( lastSegPrevious )

draw everything
thanks for the good stuff.
 
  • #13
shivajikobardan said:
@Wrichik Basu impressed by your stuffs(apps and github). Would love to hear how you achieved this? How do you achieve problem solving logic?
My school gave a hell LOT of programming problems. And I solved them all by myself. That created the base for programming logic.
 
  • Like
Likes Dale and Jarvis323
  • #14
Wrichik Basu said:
My school gave a hell LOT of programming problems. And I solved them all by myself. That created the base for programming logic.
Can you share those problems? I'm having hard time findin problems that are not too easy and not too hard. Codewars 7kyu problems are even harder for me. Indian programming books don't have proper exercises.
 
  • #15
shivajikobardan said:
Can you share those problems? I'm having hard time findin problems that are not too easy and not too hard. Codewars 7kyu problems are even harder for me. Indian programming books don't have proper exercises.
Those are Java programs, but anyway, I will get in touch with you via PM after I polish the document a bit.
 

1. Why doesn't a snake's size increase after eating?

Snakes do not have the ability to increase their size like some other animals do. Their growth is limited by their skeletal structure, which does not allow for much expansion. Additionally, snakes have very slow metabolisms, so the energy they obtain from their food is primarily used for maintaining bodily functions rather than increasing their size.

2. Can a snake's size ever increase after eating?

In rare cases, a snake's size may increase slightly after eating due to the expansion of its stomach. However, this increase is temporary and the snake will return to its original size once it has digested its food.

3. Do some snake species have the ability to increase their size after eating?

No, all snake species are limited by their skeletal structure and slow metabolisms. While some may have a larger appetite and be able to consume larger prey, their size will not increase as a result.

4. What factors determine the size of a snake?

The size of a snake is primarily determined by its species, genetics, and age. Some species are naturally larger or smaller than others, and individuals within the same species may also vary in size based on their genetic makeup. Age also plays a role, as younger snakes will be smaller and continue to grow as they age.

5. Can overfeeding a snake increase its size?

No, overfeeding a snake can actually be harmful to its health. Snakes are adapted to survive on infrequent meals, so constantly feeding them large amounts of food can lead to obesity and other health issues. It will not cause the snake to increase in size beyond its natural limits.

Similar threads

  • Programming and Computer Science
Replies
1
Views
998
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
5
Views
3K
  • Programming and Computer Science
Replies
1
Views
754
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
11
Views
1K
  • Programming and Computer Science
Replies
33
Views
6K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
15
Views
1K
Back
Top