Spaces:
Sleeping
Sleeping
import gradio as gr | |
import random | |
def flappy_bird(_): | |
# Initialize or reset the game state | |
return get_game_state(2, 2, 0, 0), 0, 2, 2, 0, False | |
def update_game(command, height, gap_position, bird_position, score, game_over): | |
PIPE_WIDTH = 3 | |
GAME_HEIGHT = 5 | |
GAP_SIZE = 2 | |
if game_over: | |
return "Game Over! Your score: {}\nClick 'Start' to play again.".format(score), 0, 2, 2, 0, False | |
# Move bird based on command | |
bird_position += 1 if command.lower() != "flap" else -1 | |
# Check bounds | |
if bird_position < 0 or bird_position >= GAME_HEIGHT: | |
return "You hit the top/bottom! Game Over! Your score: {}".format(score), 0, 2, 2, 0, True | |
# Update pipe position | |
height = (height + 1) % (PIPE_WIDTH + GAME_HEIGHT) | |
# Check for collision or passing through the gap | |
if height == PIPE_WIDTH: | |
if bird_position not in range(gap_position, gap_position + GAP_SIZE): | |
return "You hit a pipe! Game Over! Your score: {}".format(score), 0, 2, 2, 0, True | |
else: | |
score += 1 | |
gap_position = random.randint(0, GAME_HEIGHT - GAP_SIZE) | |
return get_game_state(height, gap_position, bird_position, score), height, gap_position, bird_position, score, False | |
def get_game_state(height, gap_position, bird_position, score): | |
PIPE_WIDTH = 3 | |
GAME_HEIGHT = 5 | |
GAP_SIZE = 2 | |
game_state = "Score: {}\n".format(score) | |
for i in range(GAME_HEIGHT): | |
line = "" | |
if height < PIPE_WIDTH and (i < gap_position or i >= gap_position + GAP_SIZE): | |
line += "|" | |
else: | |
line += " " | |
line += "B" if i == bird_position else "_" | |
line += "\n" | |
game_state += line | |
return game_state | |
iface = gr.Interface( | |
fn=update_game, | |
inputs=[ | |
gr.Buttons(choices=["flap"], label="Control"), | |
gr.State(), | |
gr.State(), | |
gr.State(), | |
gr.State(), | |
gr.State() | |
], | |
outputs=[ | |
gr.Textbox(label="Game State"), | |
gr.State(), | |
gr.State(), | |
gr.State(), | |
gr.State(), | |
gr.State() | |
], | |
title="Simple Text-based Flappy Bird Game", | |
description="Click 'Start' to begin. Then click 'Flap' to move the bird up and avoid the pipes." | |
) | |
iface.add_component(gr.Button("Start").click(flappy_bird, [], ["game_state", "height", "gap_position", "bird_position", "score", "game_over"]), "above") | |
if __name__ == "__main__": | |
iface.launch() | |