Create a Streamlit app which contains a game. The game should be a clone of the game Snake. Do not use pygame as it is a webassebly project
To upload files, please first save the app
import streamlit as st
import numpy as np
st.title("Snake Game")
# Game settings
width, height = 20, 20
# Initialize game state
if 'snake' not in st.session_state:
st.session_state.snake = [(5, 5), (5, 4), (5, 3)] # Starting position
st.session_state.direction = (0, 1) # Starting direction (right)
st.session_state.food = (np.random.randint(0, width), np.random.randint(0, height))
st.session_state.score = 0
# Function to render the game
def render_board():
board = np.zeros((height, width))
for (x, y) in st.session_state.snake:
board[x, y] = 1 # Snake body
food_x, food_y = st.session_state.food
board[food_x, food_y] = 2 # Food
return board
# Control the snake direction
if st.button("Up"):
st.session_state.direction = (-1, 0)
if st.button("Down"):
st.session_state.direction = (1, 0)
if st.button("Left"):
st.session_state.direction = (0, -1)
if st.button("Right"):
st.session_state.direction = (0, 1)
# Update game state
if st.session_state.snake:
# Move the snake
head_x, head_y = st.session_state.snake[0]
dir_x, dir_y = st.session_state.direction
new_head = (head_x + dir_x, head_y + dir_y)
# Check for collision with food
if new_head == st.session_state.food:
st.session_state.snake.insert(0, new_head)
st.session_state.score += 1
# Spawn new food
st.session_state.food = (np.random.randint(0, width), np.random.randint(0, height))
else:
st.session_state.snake.insert(0, new_head)
st.session_state.snake.pop()
# Check for collisions with walls or self
if (new_head[0] < 0 or new_head[0] >= height or
new_head[1] < 0 or new_head[1] >= width or
st.session_state.snake.count(new_head) > 1):
st.write("Game Over!")
st.session_state.snake = [] # Reset game state
# Render game board
board = render_board()
st.write(board)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?