build a gradio demo for snake game
- User
build a gradio demo for snake game
- Assistant
build a gradio demo for snake game
Certainly! Below is a Python implementation of the classic Snake game using Gradio to create an interactive web interface. This demo allows users to control the snake's direction using buttons and visualize the game in real-time.
Libraries Used:
gradio: For creating the web interface.PIL (Pillow): For image creation and manipulation.numpy: For efficient array handling.random: To place the food randomly on the grid.time: To control the game's speed.threading: To handle the game loop without blocking the interface.Game Mechanics:
Install Required Libraries:
Make sure you have the necessary libraries installed. You can install them using pip:
pip install gradio pillow numpy
Run the Game:
Save the provided code in a Python file, e.g., snake_gradio.py, and run it using:
python snake_gradio.py
This will launch a Gradio interface in your browser where you can play the Snake game.
import gradio as gr
from PIL import Image, ImageDraw
import numpy as np
import random
import time
import threading
# Game parameters
GRID_SIZE = 20
CELL_SIZE = 20
WIDTH = HEIGHT = 20 # 20x20 grid
INITIAL_SNAKE_LENGTH = 3
UPDATE_INTERVAL = 0.2 # seconds
# Directions
directions = {
"up": (0, -1),
"down": (0, 1),
"left": (-1, 0),
"right": (1, 0)
}
class SnakeGame:
def __init__(self):
self.reset()
def reset(self):
self.direction = "right"
self.score = 0
mid = WIDTH // 2
self.snake = [(mid - i, mid) for i in range(INITIAL_SNAKE_LENGTH)]
self.place_food()
self.game_over = False
def place_food(self):
while True:
self.food = (random.randint(0, WIDTH -1), random.randint(0, HEIGHT -1))
if self.food not in self.snake:
break
def change_direction(self, new_dir):
# Prevent the snake from reversing
opposite = {"up": "down", "down": "up", "left": "right", "right": "left"}
if new_dir != opposite.get(self.direction):
self.direction = new_dir
def step(self):
if self.game_over:
return
dx, dy = directions[self.direction]
head_x, head_y = self.snake[0]
new_head = (head_x + dx, head_y + dy)
# Check collisions
if (new_head[0] < 0 or new_head[0] >= WIDTH or
new_head[1] < 0 or new_head[1] >= HEIGHT or
new_head in self.snake):
self.game_over = True
return
self.snake.insert(0, new_head)
if new_head == self.food:
self.score += 1
self.place_food()
else:
self.snake.pop()
def get_image(self):
img = Image.new("RGB", (WIDTH * CELL_SIZE, HEIGHT * CELL_SIZE), "black")
draw = ImageDraw.Draw(img)
# Draw food
fx, fy = self.food
draw.rectangle([fx*CELL_SIZE, fy*CELL_SIZE, (fx+1)*CELL_SIZE, (fy+1)*CELL_SIZE], fill="red")
# Draw snake
for idx, (x, y) in enumerate(self.snake):
color = "green" if idx == 0 else "lightgreen"
draw.rectangle([x*CELL_SIZE, y*CELL_SIZE, (x+1)*CELL_SIZE, (y+1)*CELL_SIZE], fill=color)
return img
# Global game instance
game = SnakeGame()
lock = threading.Lock()
def game_loop():
while not game.game_over:
with lock:
game.step()
img = game.get_image()
score = game.score
img = img.resize((WIDTH * CELL_SIZE, HEIGHT * CELL_SIZE))
interface.update(img, score)
time.sleep(UPDATE_INTERVAL)
with lock:
interface.update(game.get_image().resize((WIDTH * CELL_SIZE, HEIGHT * CELL_SIZE)), game.score)
interface.end_game()
class Interface:
def __init__(self):
self.image = None
self.score = 0
self.status = "Game Running"
def update(self, image, score):
self.image = image
self.score = score
return self.image, f"Score: {self.score}"
def end_game(self):
self.status = "Game Over"
return self.image, f"Game Over! Final Score: {self.score}"
def change_dir(self, direction):
with lock:
if not game.game_over:
game.change_direction(direction)
return self.image, f"Score: {game.score}"
interface = gr.Interface(
fn=lambda img, score: (img, score),
inputs=[],
outputs=["image", "text"],
live=True,
title="Snake Game",
description="Use the buttons below to control the snake."
)
# Redefine the interface layout to include control buttons
with gr.Blocks() as demo:
gr.Markdown("## Snake Game")
image_output = gr.Image(type="pil", label="Game")
score_output = gr.Textbox(label="Score", value="Score: 0")
with gr.Row():
up_btn = gr.Button("Up")
left_btn = gr.Button("Left")
down_btn = gr.Button("Down")
right_btn = gr.Button("Right")
# Reset button
reset_btn = gr.Button("Reset Game")
def update_interface():
with lock:
img = game.get_image()
current_score = game.score
game_over = game.game_over
return img, f"Score: {current_score}" if not game_over else f"Game Over! Final Score: {current_score}"
def press_up():
game.change_direction("up")
return update_interface()
def press_down():
game.change_direction("down")
return update_interface()
def press_left():
game.change_direction("left")
return update_interface()
def press_right():
game.change_direction("right")
return update_interface()
def reset_game():
with lock:
game.reset()
return update_interface()
up_btn.click(press_up, None, [image_output, score_output])
down_btn.click(press_down, None, [image_output, score_output])
left_btn.click(press_left, None, [image_output, score_output])
right_btn.click(press_right, None, [image_output, score_output])
reset_btn.click(reset_game, None, [image_output, score_output])
# Game loop in a separate thread
threading.Thread(target=game_loop, daemon=True).start()
demo.launch()
Game Initialization:
SnakeGame class manages the game state, including the snake's position, direction, food placement, and score.User Controls:
Game Loop:
game_loop function), which updates the game state at regular intervals (UPDATE_INTERVAL).Rendering:
get_image method generates an image representation of the current game state using PIL, which is then displayed in the Gradio interface.Collision Detection:
Grid Size & Speed:
GRID_SIZE, CELL_SIZE, and UPDATE_INTERVAL to change the game's appearance and speed.Control Scheme:
Thread Safety:
lock) ensures that game state updates are thread-safe, preventing race conditions between user inputs and the game loop.Performance:
Enjoy playing the classic Snake game through your browser!
Not yet included in a published release.