Advertisement
Korotkodul

snake_v3

Dec 7th, 2023 (edited)
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. import pygame, sys, random
  2. from pygame.math import Vector2
  3.  
  4. class SNAKE:
  5.     def __init__(self):
  6.         self.body = [Vector2(5,10), Vector2(6,10), Vector2(7,10)]
  7.         self.direction = Vector2(1, 0)
  8.  
  9.     def draw_snake(self):
  10.         for block in self.body:
  11.             #create a rect
  12.             x_pos = int(block.x * cell_size)
  13.             y_pos = int(block.y * cell_size)
  14.             block_rect = pygame.Rect(x_pos, y_pos,cell_size,cell_size)
  15.             #draw the rectangle
  16.             pygame.draw.rect(screen, (255, 0, 0), block_rect)
  17.  
  18.     def move_snake(self):
  19.         body_copy = self.body[:-1]
  20.         body_copy.insert(0, body_copy[0] + self.direction)
  21.         self.body = body_copy
  22.  
  23. class FRUIT:
  24.     def __init__(self):
  25.         #create x and y position
  26.         self.x = random.randint(0, cell_number - 1)
  27.         self.y = random.randint(0, cell_number - 1)
  28.         self.pos = Vector2(self.x, self.y)
  29.     def draw_fruit(self):
  30.         #create rectangle
  31.         fruit_rect = pygame.Rect(int(self.pos.x * cell_size), int(self.pos.y * cell_size), cell_size, cell_size)
  32.         #draw the rectangle
  33.         pygame.draw.rect(screen, (126, 166, 114), fruit_rect)
  34.  
  35. pygame.init()
  36. cell_size = 40
  37. cell_number = 20
  38. screen = pygame.display.set_mode((cell_number * cell_size, cell_number * cell_size))
  39. clock = pygame.time.Clock()
  40.  
  41. fruit = FRUIT()
  42. snake = SNAKE()
  43.  
  44. SCREEN_UPDATE = pygame.USEREVENT
  45. pygame.time.set_timer(SCREEN_UPDATE, 150)
  46.  
  47. while True:
  48.     for event in pygame.event.get():
  49.         if event.type == pygame.QUIT:
  50.             pygame.quit()
  51.             sys.exit()
  52.         if event.type == SCREEN_UPDATE:
  53.             snake.move_snake()
  54.         if event.type == pygame.KEYDOWN:
  55.             if event.key == pygame.K_UP:
  56.                 snake.direction = Vector2(0, -1)
  57.             elif event.key == pygame.K_DOWN:
  58.                 snake.direction = Vector2(0, 1)
  59.             elif event.key == pygame.K_RIGHT:
  60.                 snake.direction = Vector2(1, 0)
  61.             elif event.key == pygame.K_LEFT:
  62.                 snake.direction = Vector2(-1, 0)
  63.  
  64.     screen.fill((175, 250, 70))
  65.     fruit.draw_fruit()
  66.     snake.draw_snake()
  67.     pygame.display.update()
  68.  
  69.     clock.tick(60)
  70.  
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement