Indie_Coder

Snake Tutorial Code

Aug 28th, 2022
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.87 KB | Source Code | 0 0
  1. import random
  2. import pygame as pg
  3. from pygame.math import Vector2
  4.  
  5. WIDTH = 500
  6. FPS = 60
  7. GRID = 20
  8. CELLSIZE = WIDTH / GRID
  9.  
  10. RIGHT = Vector2(1, 0)
  11. LEFT = Vector2(-1, 0)
  12. UP = Vector2(0, -1)
  13. DOWN = Vector2(0, 1)
  14.  
  15. class Game:
  16.     def __init__(self):
  17.         pg.init()
  18.         self.screen = pg.display.set_mode((WIDTH, WIDTH))
  19.         self.clock = pg.time.Clock()
  20.         pg.display.set_caption('Little Python')
  21.  
  22.         self.apple = Apple(self.screen)
  23.         self.snake = Snake(self.screen)
  24.         self.snake_timer = 300
  25.         self.snake_clk = 0
  26.         self.score = 0
  27.         self.hi_score = 0
  28.         self.gameover = False
  29.  
  30.     def restart(self):
  31.         self.snake = Snake(self.screen)
  32.         self.score = 0
  33.         self.gameover = False
  34.  
  35.     def draw(self):
  36.         if self.gameover:
  37.             self.display_gameover()
  38.             return
  39.         self.screen.fill([100, 50, 150])
  40.         # [pg.draw.rect(self.screen, 'black', (x * CELLSIZE, y * CELLSIZE, CELLSIZE, CELLSIZE), 1) for y in range(GRID) for x in range(GRID)]
  41.         self.apple.draw()
  42.         self.snake.draw()
  43.         self.write(f'Score: {self.score}', 30, 20, 5, 'white')
  44.         self.write(f'Best: {self.hi_score}', 30, 350, 5, 'white')
  45.  
  46.     def write(self, text, size, x, y, color):
  47.         font = pg.font.SysFont('comicsansms', size)
  48.         message = font.render(text, True, color)
  49.         text_box = message.get_rect()
  50.         text_box.topleft = x, y
  51.         self.screen.blit(message, text_box)
  52.  
  53.     def display_gameover(self):
  54.         self.screen.fill([200, 50, 40])
  55.         self.write('GAME OVER!', 50, 100, 30, 'white')
  56.         self.write(f'Score: {self.score}', 35, 180, 200, 'white')
  57.         self.write(f'Best: {self.hi_score}', 35, 180, 250, 'white')
  58.         self.write('press SPACE to play again', 20, 120, 350, 'white')
  59.  
  60.  
  61.     def control(self):
  62.         keys = pg.key.get_pressed()
  63.         if keys[pg.K_UP]:
  64.             self.snake.change_direction(UP)
  65.         elif keys[pg.K_DOWN]:
  66.             self.snake.change_direction(DOWN)
  67.         elif keys[pg.K_LEFT]:
  68.             self.snake.change_direction(LEFT)
  69.         elif keys[pg.K_RIGHT]:
  70.             self.snake.change_direction(RIGHT)
  71.         if keys[pg.K_SPACE] and self.gameover:
  72.             self.restart()
  73.  
  74.  
  75.     def check_borders(self):
  76.         snake_head = self.snake.body[0]
  77.         if snake_head.x >= GRID or snake_head.x < 0:
  78.             return True
  79.         if snake_head.y >= GRID or snake_head.y < 0:
  80.             return True
  81.         return False
  82.  
  83.     def check_collisions(self):
  84.         snake_head = self.snake.body[0]
  85.         if snake_head.x == self.apple.x and snake_head.y == self.apple.y:
  86.             self.snake.eat()
  87.             self.apple.move_random()
  88.             self.score += 1
  89.             if self.score > self.hi_score:
  90.                 self.hi_score = self.score
  91.         if self.check_borders() or snake_head in self.snake.body[1:]:
  92.             self.gameover = True
  93.  
  94.  
  95.     def update(self):
  96.         pg.display.update()
  97.         self.clock.tick(FPS)
  98.         if self.gameover:
  99.             return
  100.         now = pg.time.get_ticks()
  101.         if now - self.snake_clk > self.snake_timer:
  102.             self.snake_clk = now
  103.             self.snake.move()
  104.         self.check_collisions()
  105.  
  106.  
  107. class Snake:
  108.     def __init__(self, screen):
  109.         self.screen = screen
  110.         self.body = [Vector2(10, 10), Vector2(9,10)]
  111.         self.color = [10, 230, 150]
  112.         self.direction = RIGHT
  113.  
  114.     def _get_segment(self, index):
  115.         rect = pg.Rect(self.body[index].x*CELLSIZE, self.body[index].y*CELLSIZE, CELLSIZE, CELLSIZE)
  116.         return rect
  117.  
  118.     def draw(self):
  119.         for i in range(len(self.body)):
  120.             rect = self._get_segment(i)
  121.             pg.draw.rect(self.screen, self.color, rect)
  122.  
  123.     def eat(self):
  124.         self.body.append(self.body[-1].copy())
  125.  
  126.     def move(self):
  127.         for i in range(len(self.body)-1, 0, -1):
  128.             self.body[i] = self.body[i-1].copy()
  129.         self.body[0] += self.direction
  130.  
  131.     def change_direction(self, new_dir):
  132.         if new_dir.x == self.direction.x or new_dir.y == self.direction.y:
  133.             return
  134.         self.direction = new_dir
  135.  
  136.  
  137. class Apple:
  138.     def __init__(self, screen):
  139.         self.screen = screen
  140.         self.x = 0
  141.         self.y = 0
  142.         self.move_random()
  143.  
  144.     def draw(self):
  145.         rect = pg.Rect(self.x * CELLSIZE, self.y * CELLSIZE, CELLSIZE, CELLSIZE)
  146.         pg.draw.rect(self.screen, 'red', rect)
  147.  
  148.     def move_random(self):
  149.         self.x = random.randrange(GRID)
  150.         self.y = random.randrange(GRID)
  151.  
  152.  
  153.  
  154. def main():
  155.     game = Game()
  156.     running = True
  157.     while running:
  158.         for event in pg.event.get():
  159.             if event.type == pg.QUIT:
  160.                 running = False
  161.         game.control()
  162.         game.draw()
  163.         game.update()
  164.     pg.quit()
  165.  
  166.  
  167. if __name__ == '__main__':
  168.     main()
  169.  
Advertisement
Add Comment
Please, Sign In to add comment