import pygame, sys
import random
pygame.init()
x = 200
y = 200
fx = 0
fy = 0
followers = 0
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Snake but from memory')
player = pygame.draw.rect(screen,(255,255,255),(1000,1000,50,50))
body = []
fruit = pygame.draw.rect(screen,(255,0,0),(1000,1000,25,25))
lastkey = [(50,0)]
pastkeys = []
def reset():
global x
global y
global followers
global lastkey
global pastkeys
x = 200
y = 200
followers = 0
lastkey = [(50,0)]
pastkeys = []
body = []
def generate_fruit():
global fx
global fy
fx = random.randint(0,9) * 50 #+ 13
fy = random.randint(0,9) * 50 #+ 13
if fx == x and fy == y:
print('Cant spawn there, snake head is occupying the space!')
generate_fruit()
else:
for rect in body:
if rect.x == fx and rect.y == fy:
print('Cant spawn there, snake body is occupying the space!')
generate_fruit()
break
fx = fx + 2
fy = fy + 2
#print(fx, ' ', fy)
reset()
generate_fruit()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_RIGHT:
lastkey.append((50,0))
elif event.key==pygame.K_LEFT:
lastkey.append((-50,0))
elif event.key==pygame.K_UP:
lastkey.append((0,-50))
elif event.key==pygame.K_DOWN:
lastkey.append((0,50))
elif event.key==pygame.K_r:
generate_fruit()
#print(lastkey)
x = x + lastkey[0][0]
y = y + lastkey[0][1]
#print(pastkeys)
if len(lastkey) > 1:
lastkey.remove(lastkey[0])
if x >= 500:
x = 0
elif x < 0:
x = 450
if y >= 500:
y = 0
elif y < 0:
y = 450
pastkeys.insert(0,(x, y))
#if len(pastkeys) >= 101:
#pastkeys.remove(pastkeys[100])
fruit = pygame.draw.rect(screen,(255,0,0),(fx,fy,25,25))
player = pygame.draw.rect(screen,(100,255,100),(x,y,30,30))
for _ in range(followers):
#print(_)
if _ == 0:
continue
body.append(pygame.draw.rect(screen,(150,255,150),(pastkeys[_][0],pastkeys[_][1],30,30)))
while len(body) > followers - 1:
body.remove(body[0])
#print(body)
if pygame.Rect.colliderect(player,fruit):
generate_fruit()
if followers == 0:
followers = followers + 2
else:
followers = followers + 1
if pygame.Rect.collidelist(player,body) > -1:
pygame.time.wait(4000)
reset()
pygame.display.update()
#print(x, ' ', y)
screen.fill((0,0,0))
pygame.time.delay(250)