Snake game bug - food spawning coordination

Good days, I currently have some problem with my snake game food spawning location.

so the picture shows that the green square (snake food), spawned at the end of the right side of the canvas. That’s a section that I coded as a restricted area, where the player loses if they went in it (or should I say the whole first and last row and column are restricted areas). While stopping the snake and resetting the game wasn’t a problem, the snake food (green square) keeps spawning inside the restricted area although I’ve specified the range of its spawn coordinate.

my code :

this.x = (Math.floor(Math.random()*((rows - 1) + 1)) + 1) * box;
this.y = (Math.floor(Math.random()*((columns - 1) + 1)) + 1) * box;

where rows = 30, columns = 30, and box=20

could anyone guide me where did I get wrong…thank you.

this evaluates to rows

this.x = (Math.floor(Math.random()*rows) + 1) * box;
this.x = (Math.floor(Math.random()*((rows - 1) + 1)) + 1) * box;

I’ll give you a hint, this.x will never be 0, it should be able to be 0.

this same thing can be applied to this.y

good day,
that’s the idea it can’t be 0.
The idea is that the first row, last row, first column and last column will be a restricted area.
So, the x and y can’t be 0…

oh okay, my mistake didn’t read that bit. My new hint is:

this.x can evaluate to 600, it should never be able to do that.

You may already know that, but I think the brackets might have had you a bit confused, if you fix that line and work from there I think you’ll be able to get it. You’re very close.

oh ok than I’ll continue to work on it. Thank you

If you find that you’re still stuck I can help more. Just don’t want to help more than I need to.

1 Like

oh ok I solved it thank alot
:joy:

it should be

this.x = Math.floor(Math.random() * (rows - 2) + 1) * box;
this.y = Math.floor(Math.random()* (columns - 2) + 1) *  box;
1 Like