Page 2 of 2

Re: Trouble with a seemingly simple snake game

Posted: Sat Nov 19, 2022 11:40 pm
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

Re: Trouble with a seemingly simple snake game

Posted: Sun Nov 20, 2022 12:10 am
by LuaCre
I see! Thank you so much, what a silly oversight on my end.

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

Posted: Sun Nov 20, 2022 1:07 am
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.

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

Posted: Sun Nov 20, 2022 1:22 am
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