build a gradio demo for a snake game
- User
build a gradio demo for a snake game
- Assistant
build a gradio demo for a snake game
Creating a Snake game using Gradio can be an exciting way to leverage Gradio's interactive capabilities to build simple browser-based games. While Gradio is primarily designed for creating machine learning demos, its flexibility with components like Canvas allows for the development of interactive applications such as games.
Below is a step-by-step guide to building a basic Snake game using Gradio. This implementation will include:
Canvas component to render the game and buttons to control the snake's direction.Before we begin, ensure you have the following installed:
pip install gradiopip install pillowimport gradio as gr
import random
from PIL import Image, ImageDraw
import numpy as np
# Define constants
WIDTH, HEIGHT = 20, 20 # Grid size
PIXEL_SIZE = 20 # Size of each grid square in pixels
SPEED = 0.2 # Game speed (seconds per move)
We'll use a dictionary to keep track of the game state, including the snake's position, direction, food position, and game over status.
# Initialize game state
def init_game():
return {
"snake": [(WIDTH // 2, HEIGHT // 2)],
"direction": "RIGHT",
"food": place_food([(WIDTH // 2, HEIGHT // 2)]),
"game_over": False
}
def place_food(snake):
while True:
position = (random.randint(0, WIDTH -1), random.randint(0, HEIGHT -1))
if position not in snake:
return position
This function updates the game's state based on the current direction, moves the snake, checks for collisions, and places new food when necessary.
def update(state):
if state["game_over"]:
return state, render_game(state)
head_x, head_y = state["snake"][0]
direction = state["direction"]
# Calculate new head position
if direction == "UP":
new_head = (head_x, head_y -1)
elif direction == "DOWN":
new_head = (head_x, head_y +1)
elif direction == "LEFT":
new_head = (head_x -1, head_y)
elif direction == "RIGHT":
new_head = (head_x +1, head_y)
# Check for 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 state["snake"]):
state["game_over"] = True
return state, render_game(state)
# Move snake
state["snake"].insert(0, new_head)
# Check if food is eaten
if new_head == state["food"]:
state["food"] = place_food(state["snake"])
else:
state["snake"].pop()
return state, render_game(state)
This function draws the current state of the game on a canvas.
def render_game(state):
img = Image.new('RGB', (WIDTH * PIXEL_SIZE, HEIGHT * PIXEL_SIZE), color='black')
draw = ImageDraw.Draw(img)
# Draw food
food_x, food_y = state["food"]
draw.rectangle([food_x*PIXEL_SIZE, food_y*PIXEL_SIZE,
(food_x+1)*PIXEL_SIZE, (food_y+1)*PIXEL_SIZE],
fill='red')
# Draw snake
for segment in state["snake"]:
x, y = segment
draw.rectangle([x*PIXEL_SIZE, y*PIXEL_SIZE,
(x+1)*PIXEL_SIZE, (y+1)*PIXEL_SIZE],
fill='green')
if state["game_over"]:
draw.text((WIDTH*PIXEL_SIZE//2 - 40, HEIGHT*PIXEL_SIZE//2 -10),
"Game Over", fill='white')
return img
Functions to handle user inputs (direction changes).
def change_direction(state, new_direction):
# Prevent the snake from reversing
opposite_directions = {"UP":"DOWN", "DOWN":"UP",
"LEFT":"RIGHT", "RIGHT":"LEFT"}
if new_direction != opposite_directions.get(state["direction"]):
state["direction"] = new_direction
return state, render_game(state)
We'll use Gradio's update function alongside a timer to move the snake automatically.
import time
def game_loop(state):
while not state["game_over"]:
state, img = update(state)
yield img
time.sleep(SPEED)
yield img
Now, we'll set up the Gradio interface with control buttons and a canvas to display the game.
def start_game():
state = init_game()
img = render_game(state)
return state, img
with gr.Blocks() as demo:
gr.Markdown("# Snake Game")
with gr.Row():
canvas = gr.Image(type="pil", interactive=False, label="Game")
with gr.Row():
btn_up = gr.Button("Up")
btn_left = gr.Button("Left")
btn_down = gr.Button("Down")
btn_right = gr.Button("Right")
state = gr.State(init_game())
# Initialize the game
initial_state, initial_img = start_game()
state.value = initial_state
canvas.value = initial_img
# Direction controls
btn_up.click(change_direction, inputs=[state], outputs=[state, canvas],
kwargs={"new_direction": "UP"})
btn_left.click(change_direction, inputs=[state], outputs=[state, canvas],
kwargs={"new_direction": "LEFT"})
btn_down.click(change_direction, inputs=[state], outputs=[state, canvas],
kwargs={"new_direction": "DOWN"})
btn_right.click(change_direction, inputs=[state], outputs=[state, canvas],
kwargs={"new_direction": "RIGHT"})
# Auto move using a loop
def auto_move(state):
if not state["game_over"]:
state, img = update(state)
return state, img
while True:
state, img = auto_move(state.value)
canvas.value = img
time.sleep(SPEED)
if state["game_over"]:
break
demo.launch()
Save the complete code in a Python file, for example, snake_game.py, and run it using:
python snake_game.py
This will launch a local web server, and you'll be provided with a URL (typically http://127.0.0.1:7860/) where you can play the game.
time.sleep, which might not be the most efficient or responsive for faster-paced games.While Gradio is not specifically designed for game development, its flexible components allow for the creation of simple interactive applications like the Snake game demonstrated above. This example serves as a foundational approach, and with further customization, more interactive features can be incorporated.
Not yet included in a published release.