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.
 

FAQ: Snake size not increasing after eating food

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

When a snake eats food, its digestive system works to break down and absorb nutrients from the meal. The energy gained from the food is primarily used for maintaining bodily functions and growth, rather than increasing overall size. Additionally, snakes have limited ability to expand their body size due to their rigid skeletal structure.

2. Can a snake's size increase over time with regular feeding?

While a snake's size may increase slightly with regular feeding due to growth and accumulation of body mass, the overall size change is minimal compared to the size of the prey consumed. Snakes have evolved to efficiently utilize energy from their meals for survival and reproduction, rather than physical growth.

3. Do all snake species exhibit the same lack of size increase after eating?

Most snake species exhibit a similar lack of significant size increase after eating, as their physiology and metabolism are adapted to efficiently process and utilize food for energy. However, there may be variations in growth rates and size changes among different snake species based on their specific dietary habits and environmental factors.

4. Is there a maximum size limit for snakes regardless of their feeding habits?

Yes, there is a maximum size limit for snakes determined by genetic factors, species-specific characteristics, and environmental influences. While regular feeding can contribute to growth and body mass accumulation, snakes are ultimately limited by their genetic potential and physical constraints in terms of size.

5. Can a snake's size decrease after not eating for an extended period?

Yes, a snake's size may decrease after not eating for an extended period due to loss of body mass and muscle wastage. Snakes that experience prolonged fasting or limited access to food may undergo significant weight loss and reduction in size as their body utilizes stored energy reserves to sustain vital functions.

Similar threads

Replies
1
Views
1K
Replies
12
Views
1K
Replies
5
Views
3K
Replies
4
Views
1K
Replies
6
Views
1K
Replies
11
Views
1K
Replies
12
Views
3K
Back
Top