game / app.py
sagar007's picture
Create app.py
3515cf9 verified
raw
history blame
3.26 kB
import gradio as gr
import numpy as np
from PIL import Image
import random
# Game state variables
ship_position = 50 # Ship's horizontal position (0-100)
enemies = [] # List of enemy positions
score = 0
# Function to generate a simple game screen as an image
def create_game_screen(ship_pos, enemy_list, score):
# Create a blank 200x200 image (black background)
img = np.zeros((200, 200, 3), dtype=np.uint8)
# Draw ship (white rectangle) at the bottom
ship_y = 180
img[ship_y:ship_y+10, max(0, ship_pos-5):min(200, ship_pos+5)] = [255, 255, 255]
# Draw enemies (red squares)
for enemy_x, enemy_y in enemy_list:
img[max(0, enemy_y-5):min(200, enemy_y+5), max(0, enemy_x-5):min(200, enemy_x+5)] = [255, 0, 0]
# Convert to PIL Image for Gradio
return Image.fromarray(img), f"Score: {score}"
# Function to update game state based on user action
def update_game(action):
global ship_position, enemies, score
# Move ship
if action == "Move Left" and ship_position > 10:
ship_position -= 10
elif action == "Move Right" and ship_position < 190:
ship_position += 10
# Shooting logic
elif action == "Shoot":
for i, (enemy_x, enemy_y) in enumerate(enemies[:]):
if abs(enemy_x - ship_position) < 15 and enemy_y > 150: # Rough hit detection
enemies.pop(i)
score += 10
break
# Spawn new enemies randomly
if random.random() < 0.3: # 30% chance to spawn an enemy
enemies.append([random.randint(0, 200), 0])
# Move enemies down
for enemy in enemies[:]:
enemy[1] += 10
if enemy[1] > 200: # Remove enemies that go off-screen
enemies.remove(enemy)
# Generate updated game screen
return create_game_screen(ship_position, enemies, score)
# Reset game state
def reset_game():
global ship_position, enemies, score
ship_position = 50
enemies = []
score = 0
return create_game_screen(ship_position, enemies, score)
# Gradio interface
with gr.Blocks(title="Blastar 1984 Simulator") as demo:
gr.Markdown("# Blastar 1984 Simulator")
gr.Markdown("A simplified version of Elon Musk's 1984 game. Move your ship and shoot enemies!")
# Display game screen and score
output_image = gr.Image(label="Game Screen")
output_text = gr.Textbox(label="Score")
# Buttons for controls
with gr.Row():
btn_left = gr.Button("Move Left")
btn_right = gr.Button("Move Right")
btn_shoot = gr.Button("Shoot")
btn_reset = gr.Button("Reset Game")
# Event handlers
btn_left.click(fn=update_game, inputs=gr.State(value="Move Left"), outputs=[output_image, output_text])
btn_right.click(fn=update_game, inputs=gr.State(value="Move Right"), outputs=[output_image, output_text])
btn_shoot.click(fn=update_game, inputs=gr.State(value="Shoot"), outputs=[output_image, output_text])
btn_reset.click(fn=reset_game, inputs=None, outputs=[output_image, output_text])
# Initial state
demo.load(fn=reset_game, inputs=None, outputs=[output_image, output_text])
# Launch the app (Hugging Face handles this automatically)
demo.launch()