Spaces:
Sleeping
Sleeping
import gradio as gr | |
import random | |
def flappy_bird(command, height=0, gap_position=2, bird_position=2, score=0, game_over=False): | |
PIPE_WIDTH = 3 | |
GAME_HEIGHT = 5 | |
GAP_SIZE = 2 | |
if game_over: | |
return "Game Over! Your score: {}\nType 'start' to play again.".format(score), 0, 2, 2, 0, False | |
if command.lower() == "start": | |
return get_game_state(2, 2, 0, 0), 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( | |
flappy_bird, | |
inputs=[ | |
gr.Textbox(label="Enter 'flap' to move up or 'start' to start/restart the game"), | |
gr.Hidden(value=0), | |
gr.Hidden(value=2), | |
gr.Hidden(value=2), | |
gr.Hidden(value=0), | |
gr.Hidden(value=False) | |
], | |
outputs=[ | |
gr.Textbox(label="Game State"), | |
gr.Hidden(), | |
gr.Hidden(), | |
gr.Hidden(), | |
gr.Hidden(), | |
gr.Hidden() | |
], | |
title="Simple Text-based Flappy Bird Game", | |
description="Type 'flap' to move the bird up and avoid the pipes. Start the game by typing 'start'." | |
) | |
if __name__ == "__main__": | |
iface.launch() | |