Game: Snake Game.


Learn with Hafiza Palwasha




How to design a game 'Snake Game' ?

Lecture No. 3

1. Search 'cmd prompt' in your computer as I did and shown below:


2. Now type 'pip install pygame' on the black cmd prompt window and then press enter as shown below:



3. After this, the installation will start automatically, so wait for installations and then the window will appear as shown below:



4. Now, installations done so Open Python IDLE and open a new file as shown below:


5. Now the new file will open like this:


6. Now you have to import all necessary modules as shown below:

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

# Clock for controlling the game's FPS
clock = pygame.time.Clock()

The output will be as shown below:

7. Define classes for snake and food as shown below:

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

The output will be as shown below:

8. Implement the game loop and handle events like quitting, changing direction, and collisions as shown below:

def game_loop():
    running = True
    snake = Snake()
    food = Food()

    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)

        snake.draw()
        pygame.draw.rect(win, RED, (food_pos[0], food_pos[1], SNAKE_SIZE, SNAKE_SIZE))

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()

if __name__ == "__main__":
    game_loop()

The output will be as shown below as a running black square in horizontal direction:

9. Save the file and run it, and a window pop up with a simple Snake game.

10. Use the arrow keys to control the snake and try to eat the red food squares without hitting the walls or the snake's body as I played shortly and paste the results here.


Homework Task

Now you have to do the following tasks to show your skills:
1. Rewrite this code for to change the food colour from red to green. (Hint: the RGB code for green colour id (0, 255, 0)).
2. Rewrite this code to show the scores of player. (You can take the help with this link).
3. Rewrite this code to increase the speed of snake according to the scores. (You can take the help with this link).
4. Now do the final project of this snake game having following features:
 * Displaying Scores, 
 * Speed of snake increases with the scores, 
 * Display game over when the player will out,
 * Adding sound effects when snake will eat food and game over.
(You can take help from this link).

Enter your comments if you are facing some difficulty.

Comments