Advertisement
cookertron

Snake Python Pygame

Nov 16th, 2022
874
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | Source Code | 0 0
  1. import pygame
  2. import random
  3. import sys
  4.  
  5. def make_food(body_collision):
  6.     while True:
  7.         food = (random.randint(0, 63), random.randint(0 , 63))
  8.         if body_collision.get(food): continue
  9.         break
  10.     return food
  11.  
  12. grid_size = 10
  13. block_size = (grid_size, grid_size)
  14. PDR = pygame.Rect(0, 0, 640, 640)
  15. PDS = pygame.display.set_mode(PDR.size)
  16.  
  17. head_pos = [32, 32]
  18. body = []
  19. body_collision = {}
  20. for i in range(8):
  21.     new_pos = (head_pos[0], head_pos[1] + i)
  22.     body_collision[new_pos] = 1
  23.     body.append(new_pos)
  24.     pygame.draw.rect(PDS, (255, 255, 255), ((new_pos[0] * grid_size, new_pos[1] * grid_size), block_size))
  25. direction_x = 0
  26. direction_y = -1
  27.  
  28. pause_tail = 0
  29.  
  30. food = make_food(body_collision)
  31. pygame.draw.rect(PDS, (255, 0, 0), ((food[0] * grid_size, food[1] * grid_size), block_size))
  32.  
  33. while True:
  34.     for e in pygame.event.get():
  35.         if e.type == pygame.KEYUP:
  36.             if e.key == pygame.K_ESCAPE:
  37.                 pygame.quit()
  38.                 sys.exit()
  39.    
  40.     k = pygame.key.get_pressed()
  41.     if k[pygame.K_RIGHT] and direction_x != -1:
  42.         direction_y = 0
  43.         direction_x = 1
  44.     if k[pygame.K_LEFT] and direction_x != 1:
  45.         direction_y = 0
  46.         direction_x = -1
  47.     if k[pygame.K_UP] and direction_y != 1:
  48.         direction_x = 0
  49.         direction_y = -1
  50.     if k[pygame.K_DOWN] and direction_y != -1:
  51.         direction_x = 0
  52.         direction_y = 1
  53.  
  54.     pygame.display.update()
  55.     pygame.time.Clock().tick(5)
  56.  
  57.     if not pause_tail:
  58.         tail_pos = body.pop()
  59.         del body_collision[tail_pos]
  60.         pygame.draw.rect(PDS, (0, 0, 0), ((tail_pos[0] * grid_size, tail_pos[1] * grid_size), block_size))
  61.     else:
  62.         pause_tail -= 1
  63.    
  64.     new_head = (head_pos[0] + direction_x, head_pos[1] + direction_y)
  65.     if new_head == food:
  66.         food = make_food(body_collision)
  67.         pygame.draw.rect(PDS, (255, 0, 0), ((food[0] * grid_size, food[1] * grid_size), block_size))
  68.         pause_tail = 5
  69.     if body_collision.get(new_head):
  70.         pygame.quit()
  71.         sys.exit()
  72.  
  73.     pygame.draw.rect(PDS, (255, 255, 255), ((new_head[0] * grid_size, new_head[1] * grid_size), block_size))
  74.     body.insert(0, new_head)
  75.     body_collision[new_head] = 1
  76.     head_pos = new_head
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement