Trouble with a seemingly simple snake game(Solved!)

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Xugro
Party member
Posts: 110
Joined: Wed Sep 29, 2010 8:14 pm

Re: Trouble with a seemingly simple snake game

Post by Xugro »

Setting

Code: Select all

occupied = false
at the beginning of the loop will fix the issue:

Code: Select all

--snake.lua, starting from line 137
local occupied = false
repeat
occupied = false
newfood_position = {math.random(1,25),math.random(1,25)}
for i,v in pairs(snake.all_positions) do 
  if v.x == newfood_position[1] and v.y == newfood_position[2] then 
    occupied = true 
  end
end
until occupied == false
LuaCre
Prole
Posts: 27
Joined: Mon Dec 03, 2018 11:21 am

Re: Trouble with a seemingly simple snake game

Post by LuaCre »

I see! Thank you so much, what a silly oversight on my end.
MrFariator
Party member
Posts: 509
Joined: Wed Oct 05, 2016 11:53 am

Re: Trouble with a seemingly simple snake game(Solved!)

Post by MrFariator »

You may also want to consider a case where there's very little space left on the game board. The bigger the snake gets, the more likely it is that the food item will spawn on top of it, which means it's more likely for the check spawn loop to repeat a fair number of times. As such, it may still randomly get stuck, depending on what math.random is spitting out.

To combat this, you could perhaps instead keep a list of spaces the player is not occupying at that tick, and pick a random one among those.
LuaCre
Prole
Posts: 27
Joined: Mon Dec 03, 2018 11:21 am

Re: Trouble with a seemingly simple snake game(Solved!)

Post by LuaCre »

MrFariator wrote: Sun Nov 20, 2022 1:07 am You may also want to consider a case where there's very little space left on the game board. The bigger the snake gets, the more likely it is that the food item will spawn on top of it, which means it's more likely for the check spawn loop to repeat a fair number of times. As such, it may still randomly get stuck, depending on what math.random is spitting out.

To combat this, you could perhaps instead keep a list of spaces the player is not occupying at that tick, and pick a random one among those.
Super good idea, another thing I had not considered, Ill try this immediately
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Mathisto and 42 guests