import pygame import sys import random pygame.init() screen = pygame.display.set_mode((400, 400)) pygame.display.set_caption('snake') direct = [0, 1] body = [] for i in range(3, 8): body.append([4, i]) head = [4, 7] clock = 0 blank = [] for i in range(20): for j in range(20): if not [i, j] in body: blank.append([i, j]) food = random.choice(blank) while True: pygame.time.delay(20) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == ord('a'): new = [0, -1] elif event.key == ord('d'): new = [0, 1] elif event.key == ord('w'): new = [-1, 0] elif event.key == ord('s'): new = [1, 0] else: continue if direct[0] == new[0] or direct[1] == new[1]: continue direct = new[:] clock += 1 if clock >= 15: clock = 0 old = [body[len(body)-1][0], body[len(body)-1][1]] head = [old[0] + direct[0], old[1] + direct[1]] if food == head: blank = [] for i in range(20): for j in range(20): if not [i, j] in body: blank.append([i, j]) food = random.choice(blank) else: del body[0] if head in body: pygame.quit() sys.exit() if not (0 <= head[0] < 20) or not (0 <= head[1] < 20): pygame.quit() sys.exit() body.append(head) screen.fill((0, 0, 0)) for i in body: pygame.draw.rect(screen, (200, 200, 200), (20*i[1], 20*i[0], 20, 20)) pygame.draw.rect(screen, (100, 170, 255), (20*food[1], 20*food[0], 20, 20)) pygame.draw.rect(screen, (255, 255, 255), (20 * head[1], 20 * head[0], 20, 20)) pygame.display.update()