Step 1: Install Pygame
First, you need to install the Pygame library. You can install it using pip:
bashpip install pygame
Step 2: Set Up the Game Environment
Create a new Python file named snake_game.py
and import the necessary modules.
Step 3: Initialize Pygame and Set Up the Game Window
pythonimport pygame
import time
import random
pygame.init()
# Set up display
WIDTH, HEIGHT = 640, 480
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
# Snake settings
SNAKE_BLOCK = 10
SNAKE_SPEED = 15
# Font settings
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
Step 4: Define Utility Functions
Add functions to display the score, draw the snake, and display messages on the screen.
pythondef our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(win, GREEN, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
win.blit(mesg, [WIDTH / 6, HEIGHT / 3])
def display_score(score):
value = score_font.render("Your Score: " + str(score), True, WHITE)
win.blit(value, [0, 0])
Step 5: Define the Main Game Loop
Create the main game loop that handles game events, updates the game state, and renders the game.
pythondef gameLoop():
game_over = False
game_close = False
x1 = WIDTH / 2
y1 = HEIGHT / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
foody = round(random.randrange(0, HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
clock = pygame.time.Clock()
while not game_over:
while game_close:
win.fill(BLACK)
message("You Lost! Press Q-Quit or C-Play Again", RED)
display_score(Length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -SNAKE_BLOCK
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = SNAKE_BLOCK
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -SNAKE_BLOCK
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = SNAKE_BLOCK
x1_change = 0
if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
win.fill(BLUE)
pygame.draw.rect(win, RED, [foodx, foody, SNAKE_BLOCK, SNAKE_BLOCK])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(SNAKE_BLOCK, snake_List)
display_score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
foody = round(random.randrange(0, HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(SNAKE_SPEED)
pygame.quit()
quit()
gameLoop()
Explanation of the Code
- Initialization: We initialize Pygame and set up the game window, colors, snake settings, and font settings.
- Utility Functions:
our_snake
: Draws the snake on the screen.message
: Displays a message on the screen.display_score
: Displays the current score.
- Main Game Loop (
gameLoop
): - Initializes game state variables.
- Handles game over and game close states.
- Processes user input for snake movement.
- Updates the game state (snake position, food position, score).
- Renders the game (draws the snake, food, and score).
- Handles game over conditions (snake hitting the wall or itself).
- Keeps the game running at a constant speed using the clock.
Code With Me 278
0 Comments