New Text Document
New Text Document
import time
from pygame.locals import * # importing global variables
import random
class Food:
def __init__(self, parent_screen):
self.image = pygame.image.load("Resources\\apple.jpg").convert() # loading
block image from resources
self.parent_screen = parent_screen
self.x = SIZE * 5
self.y = SIZE * 5
def draw(self):
self.parent_screen.blit(self.image, (self.x, self.y)) # blit is used to
draw on surface blit(object, dimension)
pygame.display.flip() # displaying the surface color
def move(self):
self.x = random.randint(10, 24) * SIZE
self.y = random.randint(10, 19) * SIZE
def move_up(self):
self.direction = 'up'
def move_down(self):
self.direction = 'down'
def move_left(self):
self.direction = 'left'
def move_right(self):
self.direction = 'right'
def slither(self):
# Update body
for i in range(self.length - 1, 0, -1):
self.x[i] = self.x[i - 1]
self.y[i] = self.y[i - 1]
# Update head
if self.direction == 'up':
self.y[0] -= SIZE
if self.direction == 'down':
self.y[0] += SIZE
if self.direction == 'right':
self.x[0] += SIZE
if self.direction == 'left':
self.x[0] -= SIZE
self.draw()
class Game:
def __init__(self):
pygame.init() # initializing whole pygame module so we can use its
functions
pygame.display.set_caption("Snake")
def play_bg_music(self):
pygame.mixer.music.load("Resources\\bg_music_1.mp3") # loading music file
pygame.mixer.music.play() # playing loaded file
def render_bg(self):
bg = pygame.image.load("Resources\\background.jpg")
self.surface.blit(bg, (0, 0))
def play(self):
self.render_bg()
self.snake.slither()
self.food.draw()
self.display_score()
pygame.display.flip() # displaying the surface color
def show_game_over(self):
self.render_bg()
font = pygame.font.SysFont('arial', 30)
line1 = font.render(f"Game Over! Your Score is {self.snake.length}", True,
(255, 255, 255))
self.surface.blit(line1, (200, 300))
line2 = font.render("To play again press Enter. To exit press Escape",
True, (255, 255, 255))
self.surface.blit(line2, (200, 350))
pygame.display.flip()
def reset(self):
self.snake = Snake(self.surface, 1)
self.food = Food(self.surface)
if event.key == K_RETURN:
pygame.mixer.music.unpause() # un-pausing music on game
over
pause = False
try:
if not pause:
self.play()
except Exception:
self.show_game_over()
pause = True
self.reset()