Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import random
- import sys
- def make_food(body_collision):
- while True:
- food = (random.randint(0, 63), random.randint(0 , 63))
- if body_collision.get(food): continue
- break
- return food
- grid_size = 10
- block_size = (grid_size, grid_size)
- PDR = pygame.Rect(0, 0, 640, 640)
- PDS = pygame.display.set_mode(PDR.size)
- head_pos = [32, 32]
- body = []
- body_collision = {}
- for i in range(8):
- new_pos = (head_pos[0], head_pos[1] + i)
- body_collision[new_pos] = 1
- body.append(new_pos)
- pygame.draw.rect(PDS, (255, 255, 255), ((new_pos[0] * grid_size, new_pos[1] * grid_size), block_size))
- direction_x = 0
- direction_y = -1
- pause_tail = 0
- food = make_food(body_collision)
- pygame.draw.rect(PDS, (255, 0, 0), ((food[0] * grid_size, food[1] * grid_size), block_size))
- while True:
- for e in pygame.event.get():
- if e.type == pygame.KEYUP:
- if e.key == pygame.K_ESCAPE:
- pygame.quit()
- sys.exit()
- k = pygame.key.get_pressed()
- if k[pygame.K_RIGHT] and direction_x != -1:
- direction_y = 0
- direction_x = 1
- if k[pygame.K_LEFT] and direction_x != 1:
- direction_y = 0
- direction_x = -1
- if k[pygame.K_UP] and direction_y != 1:
- direction_x = 0
- direction_y = -1
- if k[pygame.K_DOWN] and direction_y != -1:
- direction_x = 0
- direction_y = 1
- pygame.display.update()
- pygame.time.Clock().tick(5)
- if not pause_tail:
- tail_pos = body.pop()
- del body_collision[tail_pos]
- pygame.draw.rect(PDS, (0, 0, 0), ((tail_pos[0] * grid_size, tail_pos[1] * grid_size), block_size))
- else:
- pause_tail -= 1
- new_head = (head_pos[0] + direction_x, head_pos[1] + direction_y)
- if new_head == food:
- food = make_food(body_collision)
- pygame.draw.rect(PDS, (255, 0, 0), ((food[0] * grid_size, food[1] * grid_size), block_size))
- pause_tail = 5
- if body_collision.get(new_head):
- pygame.quit()
- sys.exit()
- pygame.draw.rect(PDS, (255, 255, 255), ((new_head[0] * grid_size, new_head[1] * grid_size), block_size))
- body.insert(0, new_head)
- body_collision[new_head] = 1
- head_pos = new_head
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement