simple snake game
To upload files, please first save the app
import streamlit as st
import numpy as np
from PIL import Image
import time
# Set page config
st.set_page_config(page_title="Snake Game", layout="centered")
# Game constants
GRID_SIZE = 20
CELL_SIZE = 20
GAME_WIDTH = GRID_SIZE
GAME_HEIGHT = GRID_SIZE
GAME_SPEED = 0.2 # seconds between moves
# Initialize game state
if 'snake' not in st.session_state:
st.session_state.snake = [(GRID_SIZE // 2, GRID_SIZE // 2)] # Start in the middle
if 'food' not in st.session_state:
st.session_state.food = (np.random.randint(0, GRID_SIZE), np.random.randint(0, GRID_SIZE))
if 'direction' not in st.session_state:
st.session_state.direction = 'RIGHT'
if 'game_over' not in st.session_state:
st.session_state.game_over = False
if 'score' not in st.session_state:
st.session_state.score = 0
if 'high_score' not in st.session_state:
st.session_state.high_score = 0
# Title and instructions
st.title("🐍 Snake Game")
st.markdown("""
Use the buttons below to control the snake. Eat the food (red) to grow and earn points.
Don't hit the walls or yourself!
""")
# Create a blank canvas
def create_canvas():
# Create a blank white canvas
canvas = np.ones((GAME_HEIGHT * CELL_SIZE, GAME_WIDTH * CELL_SIZE, 3), dtype=np.uint8) * 255
# Draw snake (green)
for segment in st.session_state.snake:
x, y = segment
canvas[y * CELL_SIZE:(y + 1) * CELL_SIZE, x * CELL_SIZE:(x + 1) * CELL_SIZE] = [0, 200, 0]
# Make the head a different color (darker green)
head_x, head_y = st.session_state.snake[0]
canvas[head_y * CELL_SIZE:(head_y + 1) * CELL_SIZE, head_x * CELL_SIZE:(head_x + 1) * CELL_SIZE] = [0, 100, 0]
# Draw food (red)
food_x, food_y = st.session_state.food
canvas[food_y * CELL_SIZE:(food_y + 1) * CELL_SIZE, food_x * CELL_SIZE:(food_x + 1) * CELL_SIZE] = [200, 0, 0]
# Draw grid lines
for i in range(GRID_SIZE + 1):
# Horizontal lines
canvas[i * CELL_SIZE - 1:i * CELL_SIZE + 1, :] = [200, 200, 200]
# Vertical lines
canvas[:, i * CELL_SIZE - 1:i * CELL_SIZE + 1] = [200, 200, 200]
return canvas
# Game logic
def move_snake():
if st.session_state.game_over:
return
# Get the current head position
head_x, head_y = st.session_state.snake[0]
# Determine new head position based on direction
if st.session_state.direction == 'UP':
new_head = (head_x, head_y - 1)
elif st.session_state.direction == 'DOWN':
new_head = (head_x, head_y + 1)
elif st.session_state.direction == 'LEFT':
new_head = (head_x - 1, head_y)
elif st.session_state.direction == 'RIGHT':
new_head = (head_x + 1, head_y)
# Check if the snake hits the wall
new_x, new_y = new_head
if new_x < 0 or new_x >= GAME_WIDTH or new_y < 0 or new_y >= GAME_HEIGHT:
st.session_state.game_over = True
return
# Check if the snake hits itself
if new_head in st.session_state.snake[:-1]: # Exclude the tail which will move
st.session_state.game_over = True
return
# Add the new head to the snake
st.session_state.snake.insert(0, new_head)
# Check if the snake eats food
if new_head == st.session_state.food:
# Generate new food position
while True:
new_food = (np.random.randint(0, GRID_SIZE), np.random.randint(0, GRID_SIZE))
if new_food not in st.session_state.snake:
st.session_state.food = new_food
break
# Increase score
st.session_state.score += 10
# Update high score if needed
if st.session_state.score > st.session_state.high_score:
st.session_state.high_score = st.session_state.score
else:
# Remove the tail if no food was eaten
st.session_state.snake.pop()
# Reset game
def reset_game():
st.session_state.snake = [(GRID_SIZE // 2, GRID_SIZE // 2)]
st.session_state.food = (np.random.randint(0, GRID_SIZE), np.random.randint(0, GRID_SIZE))
st.session_state.direction = 'RIGHT'
st.session_state.game_over = False
st.session_state.score = 0
# Display scores
score_col, high_score_col = st.columns(2)
with score_col:
st.metric("Score", st.session_state.score)
with high_score_col:
st.metric("High Score", st.session_state.high_score)
# Display game board
canvas = create_canvas()
game_image = Image.fromarray(canvas)
st.image(game_image, use_column_width=True)
# Game controls
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
st.write("")
left_button = st.button("⬅️", key="left")
st.write("")
with col2:
up_button = st.button("⬆️", key="up")
st.write("")
down_button = st.button("⬇️", key="down")
with col3:
st.write("")
right_button = st.button("➡️", key="right")
st.write("")
# Handle button presses
if up_button and st.session_state.direction != 'DOWN':
st.session_state.direction = 'UP'
elif down_button and st.session_state.direction != 'UP':
st.session_state.direction = 'DOWN'
elif left_button and st.session_state.direction != 'RIGHT':
st.session_state.direction = 'LEFT'
elif right_button and st.session_state.direction != 'LEFT':
st.session_state.direction = 'RIGHT'
# Game over message and restart button
if st.session_state.game_over:
st.error("Game Over! Your score: " + str(st.session_state.score))
if st.button("Restart Game"):
reset_game()
else:
# Move the snake
move_snake()
# Add a rerun to make the game move automatically
time.sleep(GAME_SPEED)
st.rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?