Code snack game by python
- User
Code snack game by python
- Assistant
Code snack game by python
Sure! Below is a simple implementation of the classic Snake Game using Python and the Pygame library. This game allows you to control a snake using the arrow keys or W, A, S, D keys. The goal is to eat as many food items as possible without colliding with the walls or the snake's own body.
import pygame
import random
import sys
# Initialize Pygame
pygame.init()
# Game Window Dimensions
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
CELL_SIZE = 20
# Create the game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# Define Colors
BLACK = pygame.Color(0, 0, 0) # Background
WHITE = pygame.Color(255, 255, 255) # Food
GREEN = pygame.Color(0, 255, 0) # Snake
RED = pygame.Color(255, 0, 0) # Game Over text
# Game Clock (Controls the speed of the game)
clock = pygame.time.Clock()
FPS = 10 # Frames per second
# Initial snake position and body segments
snake_pos = [100, 50]
snake_body = [[100, 50],
[80, 50],
[60, 50]]
# Initial food position
food_pos = [random.randrange(1, (SCREEN_WIDTH // CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (SCREEN_HEIGHT // CELL_SIZE)) * CELL_SIZE]
food_spawn = True
# Initial direction
direction = 'RIGHT'
change_to = direction
# Initial score
score = 0
# Game Over Function
def game_over():
font = pygame.font.SysFont('times new roman', 50)
game_over_surface = font.render('Your Score: ' + str(score), True, RED)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4)
screen.fill(BLACK)
screen.blit(game_over_surface, game_over_rect)
pygame.display.flip()
pygame.time.wait(2000) # Pause for 2 seconds
pygame.quit()
sys.exit()
# Main Game Loop
while True:
# Event Handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Key Presses
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == ord('w'):
if direction != 'DOWN':
change_to = 'UP'
elif event.key == pygame.K_DOWN or event.key == ord('s'):
if direction != 'UP':
change_to = 'DOWN'
elif event.key == pygame.K_LEFT or event.key == ord('a'):
if direction != 'RIGHT':
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
if direction != 'LEFT':
change_to = 'RIGHT'
elif event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Validate direction to prevent snake from moving in the opposite direction instantly
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Update snake position based on direction
if direction == 'UP':
snake_pos[1] -= CELL_SIZE
if direction == 'DOWN':
snake_pos[1] += CELL_SIZE
if direction == 'LEFT':
snake_pos[0] -= CELL_SIZE
if direction == 'RIGHT':
snake_pos[0] += CELL_SIZE
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
# Check if the snake ate the food
if snake_pos == food_pos:
score += 10
food_spawn = False
else:
snake_body.pop() # Remove last segment if no food eaten
# Spawn new food if needed
if not food_spawn:
food_pos = [random.randrange(1, (SCREEN_WIDTH // CELL_SIZE)) * CELL_SIZE,
random.randrange(1, (SCREEN_HEIGHT // CELL_SIZE)) * CELL_SIZE]
food_spawn = True
# Clear screen
screen.fill(BLACK)
# Draw snake
for pos in snake_body:
pygame.draw.rect(screen, GREEN,
pygame.Rect(pos[0], pos[1], CELL_SIZE, CELL_SIZE))
# Draw food
pygame.draw.rect(screen, WHITE,
pygame.Rect(food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
# Check for collisions with boundaries
if (snake_pos[0] < 0 or snake_pos[0] >= SCREEN_WIDTH or
snake_pos[1] < 0 or snake_pos[1] >= SCREEN_HEIGHT):
game_over()
# Check for collisions with itself
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# Update the display
pygame.display.update()
# Control the game speed
clock.tick(FPS)
Install Python: Ensure you have Python installed. You can download it from python.org.
Install Pygame: Install the Pygame library using pip:
pip install pygame
Save the Code: Copy the code above into a file named snake_game.py.
Run the Game: Open a terminal or command prompt, navigate to the directory containing snake_game.py, and run:
python snake_game.py
Up Arrow or WDown Arrow or SLeft Arrow or ARight Arrow or DESCObjective: Eat as many food items (white squares) as possible to increase your score.
Growing Snake: Each time the snake eats food, it grows longer.
Game Over Conditions:
Initialization:
Snake and Food:
snake_pos keeps track of the snake's head position.snake_body is a list of positions representing the snake's segments.food_pos is randomly generated within the screen boundaries.Game Loop:
clock.tick(FPS) to control the game's frame rate.Game Over Function:
Feel free to modify the game to enhance your experience:
FPS variable to make the game faster or slower.SCREEN_WIDTH and SCREEN_HEIGHT for different window sizes.ModuleNotFoundError: No module named 'pygame', ensure that Pygame is installed correctly and you're using the same Python interpreter where Pygame is installed.Enjoy coding and playing your very own Snake Game! If you have any questions or need further assistance, feel free to ask.
Not yet included in a published release.