Advertisement
harisha

snake1

Feb 20th, 2022 (edited)
1,081
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. import pygame, random, time
  2.  
  3. pygame.init()
  4.  
  5. width = 400
  6. height = 400
  7. game_screen = pygame.display.set_mode((width, height))
  8.  
  9. x, y = 200, 200
  10. delta_x, delta_y = 0, 0
  11.  
  12. food_x, food_y = random.randrange(0, width)//10*10, random.randrange(0, height)//10*10
  13.  
  14. body_list = [(x, y)]
  15.  
  16. clock = pygame.time.Clock()
  17.  
  18. game_over = False
  19.  
  20. def snake():
  21.   global x, y, food_x, food_y, game_over
  22.   #x = x + delta_x
  23.   #y = y + delta_y
  24.   x = (x + delta_x)%width
  25.   y = (y + delta_y)%height
  26.  
  27.  
  28.   if((x, y) in body_list):
  29.     game_over = True
  30.     return
  31.  
  32.   body_list.append((x, y))
  33.  
  34.   if(food_x == x and food_y == y):
  35.     while((food_x, food_y) in body_list):
  36.       food_x, food_y = random.randrange(0, width)//10*10, random.randrange(0, height)//10*10
  37.   else:
  38.     del body_list[0]
  39.     if(game_over):
  40.         pygame.quit()
  41.         quit()
  42.  
  43.   game_screen.fill((0,0,0))
  44.   pygame.draw.rect(game_screen, (255, 0, 0), [food_x, food_y, 10, 10])
  45.   for (i, j) in body_list:
  46.     pygame.draw.rect(game_screen, (255, 255, 255), [i, j, 10, 10])
  47.   pygame.display.update()
  48.  
  49. while True:
  50.   events = pygame.event.get()
  51.   for event in events:
  52.     if event.type == pygame.KEYDOWN:
  53.       if event.key == pygame.K_ESCAPE:
  54.         pygame.quit()
  55.         quit()
  56.        
  57.       if event.key == pygame.K_LEFT:
  58.         if delta_x != 10:
  59.             delta_x = -10
  60.         delta_y = 0
  61.       elif event.key == pygame.K_RIGHT:
  62.         if delta_x != -10:
  63.           delta_x = 10
  64.         delta_y = 0
  65.       elif event.key == pygame.K_UP:
  66.         delta_x = 0
  67.         if delta_y != 10:
  68.           delta_y = -10
  69.       elif event.key == pygame.K_DOWN:
  70.         delta_x = 0
  71.         if delta_y != -10:
  72.           delta_y = 10
  73.       else:
  74.         continue
  75.       snake()
  76.      
  77.   if(not events):
  78.     snake()
  79.   clock.tick(8)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement