def draw_objects():
screen.fill(white)
for pos in snake:
pygame.draw.rect(screen, black, (pos[0], pos[1], cell_size, cell_size))
pygame.draw.rect(screen, food_color, (food[0], food[1], cell_size, cell_size))
def move_snake():
global direction
x, y = snake_head
if direction == 'UP':
y -= cell_size
elif direction == 'DOWN':
y += cell_size
elif direction == 'LEFT':
x -= cell_size
elif direction == 'RIGHT':
x += cell_size
new_head = (x, y)
snake.insert(0, new_head)
if snake_head != food:
snake.pop()
else:
create_food()
def check_collision():
if snake_head[0] < 0 or snake_head[0] >= screen_width or snake_head[1] < 0 or snake_head[1] >= screen_height:
return True
if snake_head in snake[1:]:
return True
return False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'DOWN':
direction = 'UP'
elif event.key == pygame.K_DOWN and direction != 'UP':
direction = 'DOWN'
elif event.key == pygame.K_LEFT and direction != 'RIGHT':
direction = 'LEFT'
elif event.key == pygame.K_RIGHT and direction != 'LEFT':
direction = 'RIGHT'
move_snake()
if check_collision():
pygame.quit()
sys.exit()
def draw_objects():
screen.fill(white)
for pos in snake:
pygame.draw.rect(screen, black, (pos[0], pos[1], cell_size, cell_size))
pygame.draw.rect(screen, food_color, (food[0], food[1], cell_size, cell_size))
def move_snake():
global direction
x, y = snake_head
if direction == 'UP':
y -= cell_size
elif direction == 'DOWN':
y += cell_size
elif direction == 'LEFT':
x -= cell_size
elif direction == 'RIGHT':
x += cell_size
new_head = (x, y)
snake.insert(0, new_head)
if snake_head != food:
snake.pop()
else:
create_food()
def check_collision():
if snake_head[0] < 0 or snake_head[0] >= screen_width or snake_head[1] < 0 or snake_head[1] >= screen_height:
return True
if snake_head in snake[1:]:
return True
return False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'DOWN':
direction = 'UP'
elif event.key == pygame.K_DOWN and direction != 'UP':
direction = 'DOWN'
elif event.key == pygame.K_LEFT and direction != 'RIGHT':
direction = 'LEFT'
elif event.key == pygame.K_RIGHT and direction != 'LEFT':
direction = 'RIGHT'
move_snake()
if check_collision():
pygame.quit()
sys.exit()