I'm trying to make a snake game in pygame, but I'm having trouble making the snake longer once the snake touches the dot. The game will sometimes freeze when I touch the dot and on rare occasions it gives me a memory error.
Also, the snake doesn't get any longer when I successfully eat the dot.
Any help would be appreciated. Thank you!
My code:
import pygame
import sys
import random
pygame.init()
width = 800
height = 800
snake_pos = [width/2, height/2]
snake_list = []
color_red = (255, 0, 0)
snake_size = 20
game_over = False
screen = pygame.display.set_mode((width, height))
cookie_pos = [random.randint(0, width), random.randint(0, height)]
cookie_size = 10
color_white = (255, 255, 255)
cookie = []
direction = ''
game_over = False
def draw_snake():
for snake in snake_list:
pygame.draw.rect(screen, color_red, (snake[0], snake[1], snake_size, snake_size))
if not snake_list:
snake_list.append([snake_pos[0], snake_pos[1]])
def create_snake(direction):
length = len(snake_list)
for snake in snake_list:
if direction == 'left':
snake_list.append([snake[0] + (length * snake_size), snake[1]])
elif direction == 'right':
snake_list.append([snake[0] - (length * snake_size), snake[1]])
elif direction == 'top':
snake_list.append([snake[0], snake[1] + (length * snake_size)])
elif direction == 'bottom':
snake_list.append([snake[0], snake[1] - (length * snake_size)])
def create_cookie():
cookie.append([random.randint(0, width), random.randint(0, height)])
draw_cookie()
def draw_cookie():
for cookie_pos in cookie:
pygame.draw.rect(screen, color_white, (cookie_pos[0], cookie_pos[1], cookie_size, cookie_size))
def check_cookie(direction):
for snake_pos in snake_list:
for cookie_pos in cookie:
p_x = snake_pos[0]
p_y = snake_pos[1]
e_x = cookie_pos[0]
e_y = cookie_pos[1]
if e_x >= p_x and e_x < (p_x + snake_size) or p_x >= e_x and p_x < (e_x + cookie_size):
if e_y >= p_y and e_y < (p_y + snake_size) or p_y >= e_y and p_y < (e_y + cookie_size):
cookie.pop(0)
create_cookie()
create_snake(direction)
if not cookie:
cookie.append([random.randint(0, width), random.randint(0, height)])
def update_snake():
pass
def move_snake(direction):
keys = pygame.key.get_pressed()
for snake_pos in snake_list:
if keys[pygame.K_LEFT]:
direction = 'left'
snake_pos[0] -= 0.2
if keys[pygame.K_RIGHT]:
direction = 'right'
snake_pos[0] += 0.2
if keys[pygame.K_UP]:
direction = 'up'
snake_pos[1] -= 0.2
if keys[pygame.K_DOWN]:
direction = 'down'
snake_pos[1] += 0.2
screen.fill((0,0,0))
return direction
def main_game(direction):
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
draw_snake()
check_cookie(direction)
draw_cookie()
pygame.display.update()
direction = move_snake(direction)
main_game(direction)