Game: Snake Game (Task 2).


Learn with Hafiza Palwasha




How to design a game 'Snake Game with Score' ?

Lecture No. 3 (Task)

import pygame
import random

# Initialize Pygame
pygame.init()

# Constants
WIDTH, HEIGHT = 800, 600
SNAKE_SIZE = 20
FPS = 10

# 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)

# 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 game_loop():
    running = True
    snake = Snake()
    food = Food()
    score = 0

    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

        food_pos = food.spawn_food()
        if snake.collision_with_food(food_pos):
            food.set_food_on_screen(False)
            score += 1

        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(FPS)

    pygame.quit()


if __name__ == "__main__":
    game_loop()

Comments