Certainly! Here's a basic snake game coded in Python with explanations for each step:
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up the game window
width = 800
height = 600
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
# Define colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# Define snake properties
snake_size = 20
snake_speed = 15
# Define font for displaying score
font_style = pygame.font.SysFont(None, 30)
def display_score(score):
score_text = font_style.render("Score: " + str(score), True, white)
window.blit(score_text, [10, 10])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(window, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
# Initial position of the snake
x = width / 2
y = height / 2
# Movement of the snake
x_speed = 0
y_speed = 0
# Snake body
snake_pixels = []
snake_length = 1
# Food position
food_x = round(random.randrange(0, width - snake_size) / snake_size) * snake_size
food_y = round(random.randrange(0, height - snake_size) / snake_size) * snake_size
while not game_over:
while game_close:
window.fill(black)
game_over_text = font_style.render("Game Over! Press Q to Quit or C to Play Again", True, red)
window.blit(game_over_text, [width / 3, height / 3])
display_score(snake_length - 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:
run_game()
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:
x_speed = -snake_size
y_speed = 0
elif event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
elif event.key == pygame.K_UP:
y_speed = -snake_size
x_speed = 0
elif event.key == pygame.K_DOWN:
y_speed = snake_size
x_speed = 0
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
window.fill(black)
pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
display_score(snake_length - 1)
pygame.display.update()
if x == food_x and y == food_y:
food_x = round(random.randrange(0, width - snake_size) / snake_size) * snake_size
food_y = round(random.randrange(0, height - snake_size) / snake_size) * snake_size
snake_length += 1
clock = pygame.time.Clock()
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()
Explanation:
-
We start by importing the necessary modules: pygame for game development and random for generating random positions for the food.
-
We initialize Pygame using pygame.init().
-
We set up the game window by specifying the width and height and creating the window using pygame.display.set_mode(). We also set the caption of the window using pygame.display.set_caption().
-
We define colors as tuples of RGB values for black, white, and red.
-
We define the properties of the snake, such as its size and speed.
-
We define a font style for displaying the score using pygame.font.SysFont().
-
We create a function display_score() to render and display the score on the game window.
-
We create a function draw_snake() to draw the snake on the game window using rectangles.
-
We define the main game loop in the run_game() function.
-
Inside the game loop, we handle events such as key presses to control the snake's movement. We update the snake's position based on the current direction.
-
We check for collision with the boundaries of the window. If the snake collides with the boundaries, the game ends.
-
We draw the food on the game window using a rectangle.
-
We update the snake's body by appending the new position to the snake_pixels list and removing the tail if the snake's length exceeds the current length.
-
We check for collision with the snake's own body. If the snake collides with itself, the game ends.
-
We call the draw_snake() function to draw the snake on the game window.
-
We call the display_score() function to display the current score.
-
We update the game window using pygame.display.update().
-
If the snake's position matches the food's position, we generate a new random position for the food and increase the snake's length.
-
We control the game's speed using pygame.time.Clock() and clock.tick().
-
If the game is over, we display a "Game Over" message and prompt the player to quit or play again.
-
Finally, we call the function to start the game.
This is a basic implementation of the snake game in Python using Pygame. You can further enhance the game by adding more features, improving the graphics, and handling additional game states.