I am using the Sense Hat emulator (https://trinket.io/sense-hat), and trying to make a simple snake game. The snake grows when I eat the first food, but it grows indefinitely. Then it crashes on the second food. I'm not sure how to fix this issue and would love any input! This is my first time coding in Python.
from sense_hat import SenseHat
from time import sleep
from random import randint
sense = SenseHat()
black = (0, 0, 0)
red = (255, 0, 0)
posy = [4]
posx = [4]
color = (0, 0, 255)
speed = 1
direction = 0
eatcount = 0
exist = 0
tempposx = 0
tempposy = 0
oldposx = 0
oldposy = 0
try:
while True:
randposx = randint(0,7)
randposy = randint(0,7)
if len(posx) == 1:
sense.set_pixel(posx[len(posx) - 1], posy[len(posy) - 1], (0, 0, 0))
for event in sense.stick.get_events():
if event.action == "pressed":
if event.direction == "up":
if direction != 2:
direction = 1
elif event.direction == "down":
if direction != 1:
direction = 2
elif event.direction == "left":
if direction != 4:
direction = 3
elif event.direction == "right":
if direction != 3:
direction = 4
elif event.direction == "middle":
direction = 5
oldposx = posx[0]
oldposy = posy[0]
if direction == 1:
posx[0] -=1
elif direction == 2:
posx[0] +=1
elif direction == 3:
posy[0] +=1
elif direction == 4:
posy[0] -=1
elif direction == 5:
posx[0] +=1
if exist == 1:
if tempposx == posx[0] and tempposy == posy[0]:
exist = 0
eatcount += 1
posx.append(tempposx)
posy.append(tempposy)
if speed > 0.2:
speed -= 0.05
if exist == 0:
sense.set_pixel(randposx, randposy, red)
tempposx = randposx
tempposy = randposy
exist = 1
if len(posx) > 1:
for i in range(1, len(posx) - 1, 1):
sense.set_pixel(posx[oldposx], posy[oldposy], color)
sense.set_pixel(posx[i], posy[i], (0, 0, 0))
oldposx = posx[i]
oldposy = posy[i]
sense.set_pixel(posx[0], posy[0], color)
sleep(speed)
except:
sense.show_message("Game Over - Score: " + str(eatcount), text_colour=red, back_colour=black, scroll_speed=0.03)