Spaces:
Runtime error
Runtime error
File size: 13,095 Bytes
a8c7059 6f9585a a8c7059 6f9585a a8c7059 1544311 a8c7059 1544311 a8c7059 6f9585a a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 1544311 a8c7059 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | import gradio as gr
import json
import random
import time
from datetime import datetime
import pandas as pd
from utils import (
initialize_game_state,
create_box,
calculate_battle_result,
get_shop_items,
purchase_item,
get_leaderboard,
save_game_state,
load_game_state
)
from models import Box, Battle, Shop
# Global game state
game_state = {}
def authenticate_user(profile):
"""Handle user authentication"""
if profile is None:
return None, "β Please login to play", gr.update(visible=False)
user_id = profile["name"]
if user_id not in game_state:
game_state[user_id] = initialize_game_state(user_id)
return user_id, f"β
Welcome back, {user_id}!", gr.update(visible=True)
def create_user_box(user_id, box_name):
"""Create a new box for the user"""
if not box_name.strip():
return "β Please enter a box name", get_user_status(user_id)
box = create_box(box_name.strip())
game_state[user_id]["box"] = box
game_state[user_id]["coins"] = 100 # Starting coins
status = get_user_status(user_id)
return f"β
Box '{box_name}' created successfully! Starting with 100 coins.", status
def get_user_status(user_id):
"""Get current user status as formatted text"""
if user_id not in game_state:
return "β User not found"
user_data = game_state[user_id]
box = user_data.get("box")
if not box:
return "β No box created yet"
status = f"""
π¦ BOX STATUS: {box.name}
βοΈ Attack: {box.attack}
π‘οΈ Defense: {box.defense}
β€οΈ Health: {box.health}/{box.max_health}
β‘ Speed: {box.speed}
πͺ Coins: {user_data.get('coins', 0)}
π Wins: {user_data.get('wins', 0)}
π Losses: {user_data.get('losses', 0)}
π Level: {box.level}
β¨ XP: {box.xp}/{box.xp_to_next_level}
"""
return status.strip()
def battle_opponent(user_id, opponent_type="system"):
"""Battle against an opponent"""
if user_id not in game_state or not game_state[user_id].get("box"):
return "β Create a box first!", get_user_status(user_id)
user_box = game_state[user_id]["box"]
if opponent_type == "system":
# Create system box with level based on user level
system_level = max(1, user_box.level + random.randint(-2, 2))
opponent = create_box(f"System Bot Lv.{system_level}")
opponent.level = system_level
opponent.attack = 10 + system_level * 5
opponent.defense = 8 + system_level * 4
opponent.health = 50 + system_level * 20
opponent.max_health = opponent.health
opponent.speed = 5 + system_level * 2
else:
# For multiplayer - create a random opponent for demo
opponent = create_box(f"Player Box")
opponent.level = random.randint(1, 10)
opponent.attack = 15 + opponent.level * 3
opponent.defense = 12 + opponent.level * 2
opponent.health = 40 + opponent.level * 15
opponent.max_health = opponent.health
opponent.speed = 3 + opponent.level
battle_result = calculate_battle_result(user_box, opponent)
# Update user stats
if battle_result["winner"] == "user":
game_state[user_id]["wins"] = game_state[user_id].get("wins", 0) + 1
coins_earned = 20 + opponent.level * 5
game_state[user_id]["coins"] = game_state[user_id].get("coins", 0) + coins_earned
user_box.gain_xp(10 + opponent.level * 5)
result_text = f"""
π VICTORY!
π You defeated {opponent.name}!
πͺ Earned {coins_earned} coins
β¨ Gained {10 + opponent.level * 5} XP
"""
else:
game_state[user_id]["losses"] = game_state[user_id].get("losses", 0) + 1
coins_earned = 5
game_state[user_id]["coins"] = game_state[user_id].get("coins", 0) + coins_earned
result_text = f"""
π DEFEAT!
π You were defeated by {opponent.name}
πͺ Earned {coins_earned} coins (consolation prize)
"""
battle_log = f"""
βοΈ BATTLE LOG
{battle_result["log"]}
"""
return result_text.strip(), battle_log.strip(), get_user_status(user_id)
def show_shop(user_id):
"""Display shop items"""
if user_id not in game_state:
return "β Please login first", ""
user_coins = game_state[user_id].get("coins", 0)
items = get_shop_items()
shop_text = f"πͺ Your Coins: {user_coins}\n\nποΈ SHOP ITEMS:\n\n"
for i, item in enumerate(items, 1):
affordable = "β
" if user_coins >= item["cost"] else "β"
shop_text += f"{i}. {item['name']} - {item['cost']} coins {affordable}\n"
shop_text += f" {item['description']}\n"
shop_text += f" Effect: {item['effect']}\n\n"
return shop_text, ""
def buy_item(user_id, item_choice):
"""Purchase an item from the shop"""
if user_id not in game_state:
return "β Please login first", show_shop(user_id)
try:
item_num = int(item_choice)
items = get_shop_items()
if item_num < 1 or item_num > len(items):
return "β Invalid item number", show_shop(user_id)
item = items[item_num - 1]
result = purchase_item(game_state[user_id], item)
if result["success"]:
return f"β
{result['message']}", show_shop(user_id)
else:
return f"β {result['message']}", show_shop(user_id)
except ValueError:
return "β Please enter a valid number", show_shop(user_id)
def show_leaderboard():
"""Display the global leaderboard"""
leaderboard = get_leaderboard(game_state)
if not leaderboard:
return "π LEADERBOARD\n\nNo players yet. Be the first!"
board_text = "π GLOBAL LEADERBOARD\n\n"
for i, player in enumerate(leaderboard[:10], 1):
medal = "π₯" if i == 1 else "π₯" if i == 2 else "π₯" if i == 3 else "π
"
win_rate = (player['wins'] / (player['wins'] + player['losses']) * 100) if (player['wins'] + player['losses']) > 0 else 0
board_text += f"{medal} {i}. {player['name']}\n"
board_text += f" π Wins: {player['wins']} | π Losses: {player['losses']}\n"
board_text += f" π Win Rate: {win_rate:.1f}% | π¦ Box: {player['box_name']}\n\n"
return board_text
def auto_upgrade_system_boxes():
"""Automatically upgrade system boxes"""
while True:
time.sleep(30) # Every 30 seconds
# System boxes upgrade logic would go here
# For now, this is a placeholder
def create_interface():
"""Create the main game interface"""
with gr.Blocks(
title="Box Battle Arena - Accessible Fighting Game",
css="""
.accessibility-mode {
font-size: 18px;
line-height: 1.6;
}
.game-status {
background-color: #f0f0f0;
padding: 15px;
border-radius: 10px;
font-family: monospace;
}
""",
theme=gr.themes.Soft()
) as demo:
# Header with accessibility info
gr.HTML("""
<div style="text-align: center; margin-bottom: 20px;">
<h1>π₯ Box Battle Arena π₯</h1>
<p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">Built with anycoder</a></p>
<p>π This game is fully accessible for screen reader users</p>
<p>Use Tab to navigate, Enter to select, and screen reader will announce all actions</p>
</div>
""")
# Login section
with gr.Row():
with gr.Column(scale=1):
login_btn = gr.LoginButton()
user_info = gr.HTML("<p>π Please login with Hugging Face to play</p>")
>>>>>>> REPLACE REPLACE
# Main game area (hidden until login)
with gr.Group(visible=False) as game_area:
# Box Creation
with gr.Group():
gr.Markdown("## π¦ Create Your Box")
with gr.Row():
box_name_input = gr.Textbox(
label="Box Name",
placeholder="Enter your box name...",
elem_id="box_name_input"
)
create_box_btn = gr.Button("Create Box", variant="primary")
create_result = gr.Textbox(label="Creation Result", interactive=False)
# Status Display
with gr.Group():
gr.Markdown("## π Your Status")
user_status = gr.Textbox(
label="Current Status",
value="No box created yet",
interactive=False,
elem_classes=["game-status"]
)
# Battle Section
with gr.Group():
gr.Markdown("## βοΈ Battle Arena")
with gr.Row():
battle_system_btn = gr.Button("π€ Battle System Box", variant="primary")
battle_player_btn = gr.Button("π₯ Battle Player Box", variant="secondary")
battle_result = gr.Textbox(label="Battle Result", interactive=False)
battle_log = gr.Textbox(
label="Battle Log",
lines=10,
interactive=False,
elem_classes=["game-status"]
)
# Shop Section
with gr.Group():
gr.Markdown("## ποΈ Shop")
with gr.Row():
shop_btn = gr.Button("View Shop")
refresh_shop_btn = gr.Button("π Refresh")
shop_display = gr.Textbox(
label="Shop Items",
lines=15,
interactive=False,
elem_classes=["game-status"]
)
with gr.Row():
item_choice_input = gr.Number(
label="Item Number",
minimum=1,
maximum=10,
step=1
)
buy_btn = gr.Button("Buy Item", variant="primary")
shop_result = gr.Textbox(label="Purchase Result", interactive=False)
# Leaderboard
with gr.Group():
gr.Markdown("## π Leaderboard")
leaderboard_btn = gr.Button("View Leaderboard")
leaderboard_display = gr.Textbox(
label="Top Players",
lines=15,
interactive=False,
elem_classes=["game-status"]
)
# Event handlers
def handle_login(profile):
if profile:
user_id, msg, visibility = authenticate_user(profile)
return (
gr.update(value=f"β
Logged in as: {profile['name']}"),
gr.update(visible=True),
get_user_status(user_id) if user_id else "No box created yet"
)
return gr.update(), gr.update(visible=False), "No box created yet"
login_btn.success(
handle_login,
inputs=[login_btn],
outputs=[user_info, game_area, user_status]
)
create_box_btn.click(
create_user_box,
inputs=[box_name_input],
outputs=[create_result, user_status]
)
def battle_system():
return battle_opponent("demo_user")
def battle_player():
return battle_opponent("demo_user", "player")
def show_shop_demo():
return show_shop("demo_user")
def buy_item_demo(choice):
return buy_item("demo_user", choice)
battle_system_btn.click(
battle_system,
outputs=[battle_result, battle_log, user_status]
)
battle_player_btn.click(
battle_player,
outputs=[battle_result, battle_log, user_status]
)
shop_btn.click(
show_shop_demo,
outputs=[shop_display, shop_result]
)
buy_btn.click(
buy_item_demo,
inputs=[item_choice_input],
outputs=[shop_result, shop_display]
)
leaderboard_btn.click(
show_leaderboard,
outputs=[leaderboard_display]
)
refresh_shop_btn.click(
show_shop_demo,
outputs=[shop_display, shop_result]
)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_api=False,
prevent_thread_lock=False
) |