write a snake game on python
- User
write a snake game on python
- Assistant
write a snake game on python
Certainly! Below is a simple implementation of the classic Snake game using Python and the Pygame library.
Before running the game, make sure you have:
Python 3 installed on your system.
Pygame library installed. If not, you can install it using:
pip install pygame
Save the following code in a file named snake_game.py:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 640, 480
CELL_SIZE = 20
# Grid dimensions
GRID_WIDTH = WIDTH // CELL_SIZE
GRID_HEIGHT = HEIGHT // CELL_SIZE
# Colors (R, G, B)
WHITE = (255, 255, 255)
GRAY = (40, 40, 40)
BLACK = (0, 0, 0)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
# Directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# Initialize screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Clock object
clock = pygame.time.Clock()
# Fonts
font = pygame.font.SysFont('Arial', 25)
def draw_grid():
for x in range(0, WIDTH, CELL_SIZE):
pygame.draw.line(screen, GRAY, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, CELL_SIZE):
pygame.draw.line(screen, GRAY, (0, y), (WIDTH, y))
def random_position():
x = random.randint(0, GRID_WIDTH - 1) * CELL_SIZE
y = random.randint(0, GRID_HEIGHT - 1) * CELL_SIZE
return x, y
def game_over():
msg = font.render('Game Over!', True, RED)
screen.blit(msg, (WIDTH // 2 - msg.get_width() // 2, HEIGHT // 2 - msg.get_height() // 2))
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()
sys.exit()
def main():
# Initial snake settings
snake = [(WIDTH // 2, HEIGHT // 2)]
direction = RIGHT
speed = 10
# Initial food position
food = random_position()
while True:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key in [pygame.K_UP, pygame.K_w] and direction != DOWN:
direction = UP
elif event.key in [pygame.K_DOWN, pygame.K_s] and direction != UP:
direction = DOWN
elif event.key in [pygame.K_LEFT, pygame.K_a] and direction != RIGHT:
direction = LEFT
elif event.key in [pygame.K_RIGHT, pygame.K_d] and direction != LEFT:
direction = RIGHT
# Move snake
new_head = ((snake[0][0] + direction[0] * CELL_SIZE) % WIDTH,
(snake[0][1] + direction[1] * CELL_SIZE) % HEIGHT)
# Check collisions
if new_head in snake:
game_over()
snake.insert(0, new_head)
# Check if snake has eaten the food
if snake[0] == food:
food = random_position()
speed += 0.5 # Increase speed
else:
snake.pop()
# Drawing
screen.fill(BLACK)
draw_grid()
# Draw snake
for segment in snake:
pygame.draw.rect(screen, GREEN, (*segment, CELL_SIZE, CELL_SIZE))
# Draw food
pygame.draw.rect(screen, RED, (*food, CELL_SIZE, CELL_SIZE))
# Update display
pygame.display.flip()
# Control the speed of the game
clock.tick(speed)
if __name__ == "__main__":
main()
Install Pygame (if you haven't already):
pip install pygame
Save the code provided above into a file named snake_game.py.
Run the script from your terminal or command prompt:
python snake_game.py
Imports: The game uses the pygame library for rendering graphics and handling user input.
Constants: Screen dimensions, colors, and directions are defined for easy adjustments.
draw_grid() Function: Draws a grid on the screen to enhance the visual appeal.
random_position() Function: Generates a random position for the food within the grid.
game_over() Function: Displays a game over message and exits the game.
main() Function: Contains the main game loop:
Wrapping Behavior: The snake's position wraps around the screen edges using the modulus operator %.
Changing the Grid Size: Modify WIDTH, HEIGHT, and CELL_SIZE to change the size of the game window and the grid cells.
Adjusting Speed: The initial speed is set with speed = 10. Modify this value to make the game faster or slower.
Adding Boundaries: If you prefer the game to have boundaries (walls), remove the modulus operation in the new_head calculation and add a collision check:
new_head = (snake[0][0] + direction[0] * CELL_SIZE,
snake[0][1] + direction[1] * CELL_SIZE)
# Check for collision with walls
if (new_head[0] < 0 or new_head[0] >= WIDTH or
new_head[1] < 0 or new_head[1] >= HEIGHT):
game_over()
Enjoy playing your very own Snake game. Feel free to modify and enhance the code to add new features, such as a scoring system, sound effects, or obstacles.
If you have any questions or need further assistance, don't hesitate to ask!
Not yet included in a published release.