Learn with Hafiza Palwasha
How to design a game 'Snake Game with Score and time increment based on scores' ?
Lecture No. 3 (Task)
You have to download any two '.wav' files from this link and rename one of them as 'eat' and other as 'game_over' and place it exactly on the same folder where you save the python code as I am showing below:
Now use the following code to do this project task
import pygame
import random
# Initialize Pygame
pygame.init()
pygame.mixer.init()
# Constants
WIDTH, HEIGHT = 800, 600
SNAKE_SIZE = 20
FPS = 10
SPEED_INCREASE = 0.1 # Increase in speed per food eaten
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Create the game window
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Snake Game')
# Fonts
font = pygame.font.Font(None, 36)
# Sounds
eat_sound = pygame.mixer.Sound('eat.wav')
game_over_sound = pygame.mixer.Sound('game_over.wav')
# Clock for controlling the game's FPS
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.size = 1
self.elements = [[100, 100]]
self.dx, self.dy = 20, 0
def draw(self):
for element in self.elements:
pygame.draw.rect(win, BLACK, (element[0], element[1], SNAKE_SIZE, SNAKE_SIZE))
def move(self):
new_head = [self.elements[0][0] + self.dx, self.elements[0][1] + self.dy]
self.elements.insert(0, new_head)
if len(self.elements) > self.size:
self.elements.pop()
def change_direction(self, dx, dy):
self.dx, self.dy = dx, dy
def collision_with_food(self, food_pos):
if self.elements[0][0] == food_pos[0] and self.elements[0][1] == food_pos[1]:
self.size += 1
return True
return False
def collision_with_self(self):
return len(self.elements) != len(set(map(tuple, self.elements)))
class Food:
def __init__(self):
self.position = [random.randrange(1, (WIDTH // SNAKE_SIZE)) * SNAKE_SIZE,
random.randrange(1, (HEIGHT // SNAKE_SIZE)) * SNAKE_SIZE]
self.is_food_on_screen = True
def spawn_food(self):
if not self.is_food_on_screen:
self.position = [random.randrange(1, (WIDTH // SNAKE_SIZE)) * SNAKE_SIZE,
random.randrange(1, (HEIGHT // SNAKE_SIZE)) * SNAKE_SIZE]
self.is_food_on_screen = True
return self.position
def set_food_on_screen(self, choice):
self.is_food_on_screen = choice
def display_score(score):
text = font.render(f"Score: {score}", True, BLACK)
win.blit(text, (10, 10))
def increase_speed(base_speed, score):
return base_speed + int(SPEED_INCREASE * score)
def game_over_screen(score):
win.fill(WHITE)
text = font.render(f"Game Over! Your Score: {score}", True, BLACK)
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
win.blit(text, text_rect)
pygame.display.update()
pygame.time.wait(2000) # Show game over screen for 2 seconds before quitting
def game_loop():
running = True
snake = Snake()
food = Food()
score = 0
speed = FPS
while running:
win.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction(0, -SNAKE_SIZE)
elif event.key == pygame.K_DOWN:
snake.change_direction(0, SNAKE_SIZE)
elif event.key == pygame.K_LEFT:
snake.change_direction(-SNAKE_SIZE, 0)
elif event.key == pygame.K_RIGHT:
snake.change_direction(SNAKE_SIZE, 0)
snake.move()
if snake.collision_with_self() or (snake.elements[0][0] not in range(0, WIDTH) or
snake.elements[0][1] not in range(0, HEIGHT)):
running = False
pygame.mixer.Sound.play(game_over_sound)
game_over_screen(score)
break
food_pos = food.spawn_food()
if snake.collision_with_food(food_pos):
food.set_food_on_screen(False)
score += 1
speed = increase_speed(FPS, score)
pygame.mixer.Sound.play(eat_sound)
snake.draw()
pygame.draw.rect(win, RED, (food_pos[0], food_pos[1], SNAKE_SIZE, SNAKE_SIZE))
display_score(score)
pygame.display.update()
clock.tick(speed)
pygame.quit()
if __name__ == "__main__":
game_loop()
Comments
Post a Comment