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