Spaces:
Running
Running
File size: 10,112 Bytes
e04b366 53bbde1 e04b366 f9e5e02 e04b366 6881280 e04b366 53bbde1 27d644c 3f8359b 27d644c 3f8359b f9e5e02 6881280 5afbcd4 6881280 5afbcd4 6881280 5afbcd4 6881280 f9e5e02 6881280 5afbcd4 6881280 f9e5e02 6881280 f9e5e02 6881280 5afbcd4 6881280 27d644c 6881280 5afbcd4 6881280 3ab25b4 6881280 27d644c 6881280 27d644c 6881280 27d644c 3ab25b4 6881280 27d644c 3ab25b4 6881280 27d644c 6881280 f9e5e02 e04b366 27d644c e04b366 2804ca9 e04b366 5afbcd4 e04b366 6881280 f9e5e02 e04b366 53bbde1 e04b366 27d644c |
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 |
import streamlit as st
import os
import random
import time
from PIL import Image
import json
from datetime import datetime
from pathlib import Path
import asyncio
import threading
from typing import Optional
import queue
import atexit
# ๐ฎ Game Constants
GRID_WIDTH = 16
GRID_HEIGHT = 9
REFRESH_RATE = 5
INTERACTION_RADIUS = 2
POINTS_PER_INTERACTION = 1
# ๐ Timer Management
class GameTimer:
def __init__(self):
self.running = True
self._loop: Optional[asyncio.AbstractEventLoop] = None
self.update_queue = queue.Queue()
self.thread = threading.Thread(target=self._run_timer, daemon=True)
self.thread.start()
def _run_timer(self):
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._loop.run_until_complete(self._timer_loop())
async def _timer_loop(self):
while self.running:
try:
current_time = time.time()
self.update_queue.put(('update', current_time))
await asyncio.sleep(REFRESH_RATE)
except Exception as e:
print(f"Timer error: {e}")
await asyncio.sleep(1)
def stop(self):
self.running = False
if self._loop:
self._loop.stop()
# ๐จ Resource Management: Load and cache images, assign randomly but consistently for each (x, y)
@st.cache_resource(show_spinner="Loading game resources...")
def get_game_images():
image_folder = Path('game_images') # Directory containing the .png images
images = []
for file in image_folder.glob('*.png'):
images.append(Image.open(file))
return images
def initialize_map():
# Path to the cached map configuration
map_path = Path('map.json')
# Load or initialize the map with consistent image selections for each grid position
if map_path.exists():
with open(map_path, 'r') as f:
map_layout = json.load(f)
else:
# If the map doesn't exist, create a random mapping and save it
map_layout = {}
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
map_layout[f"{x},{y}"] = random.randint(0, len(get_game_images()) - 1)
with open(map_path, 'w') as f:
json.dump(map_layout, f)
return map_layout
# Cache the map layout for consistent use across sessions
map_layout = initialize_map()
# First define the load_game_state function
def load_game_state():
if 'player_name' in st.query_params:
st.session_state.player_name = st.query_params.player_name
st.session_state.position = {
'x': int(st.query_params.get('x', random.randint(0, GRID_WIDTH - 1))),
'y': int(st.query_params.get('y', random.randint(0, GRID_HEIGHT - 1)))
}
st.session_state.character_stats = {
'STR': int(st.query_params.get('STR', 10)),
'DEX': int(st.query_params.get('DEX', 10)),
'CON': int(st.query_params.get('CON', 10)),
'INT': int(st.query_params.get('INT', 10)),
'WIS': int(st.query_params.get('WIS', 10)),
'CHA': int(st.query_params.get('CHA', 10)),
'HP': int(st.query_params.get('HP', 20)),
'MAX_HP': int(st.query_params.get('MAX_HP', 40)),
'score': int(st.query_params.get('score', 0)),
'created_at': float(st.query_params.get('created_at', time.time()))
}
# Then initialize session state
if 'initialized' not in st.session_state:
st.session_state.initialized = False
st.session_state.game_state = {
'players': {},
'chat_messages': [],
'last_sync': time.time()
}
st.session_state.player_name = None
st.session_state.character_stats = {
'STR': 10,
'DEX': 10,
'CON': 10,
'INT': 10,
'WIS': 10,
'CHA': 10,
'HP': 20,
'MAX_HP': 40,
'score': 0,
'created_at': time.time()
}
st.session_state.position = {
'x': random.randint(0, GRID_WIDTH - 1),
'y': random.randint(0, GRID_HEIGHT - 1)
}
st.session_state.last_move = time.time()
st.session_state.nearby_players = []
# Now call load_game_state after it's been defined
load_game_state()
# ๐ฒ Game State Initialization
if 'initialized' not in st.session_state:
st.session_state.initialized = False
st.session_state.game_state = {
'players': {},
'chat_messages': [],
'last_sync': time.time()
}
st.session_state.player_name = None
st.session_state.character_stats = None
st.session_state.position = {
'x': random.randint(0, GRID_WIDTH - 1),
'y': random.randint(0, GRID_HEIGHT - 1)
}
st.session_state.last_move = time.time()
st.session_state.nearby_players = []
load_game_state()
# ๐ฎ Player State Management
def save_player_state():
if st.session_state.player_name:
player_data = {
'name': st.session_state.player_name,
'position': st.session_state.position,
'stats': st.session_state.character_stats,
'last_update': time.time()
}
os.makedirs('players', exist_ok=True)
with open(f"players/{st.session_state.player_name}.json", 'w') as f:
json.dump(player_data, f)
# ๐ Distance Calculation
def calculate_distance(pos1, pos2):
dx = min(abs(pos1['x'] - pos2['x']), GRID_WIDTH - abs(pos1['x'] - pos2['x']))
dy = min(abs(pos1['y'] - pos2['y']), GRID_HEIGHT - abs(pos1['y'] - pos2['y']))
return dx + dy
# ๐โโ๏ธ Movement System
def update_position(direction):
if direction == "up":
st.session_state.position['y'] = (st.session_state.position['y'] - 1) % GRID_HEIGHT
elif direction == "down":
st.session_state.position['y'] = (st.session_state.position['y'] + 1) % GRID_HEIGHT
elif direction == "left":
st.session_state.position['x'] = (st.session_state.position['x'] - 1) % GRID_WIDTH
elif direction == "right":
st.session_state.position['x'] = (st.session_state.position['x'] + 1) % GRID_WIDTH
st.session_state.last_move = time.time()
save_player_state()
# Modify the create_game_board function to use the map_layout
def create_game_board():
current_time = time.time()
all_players = load_all_players(current_time)['players']
images = get_game_images()
for y in range(GRID_HEIGHT):
cols = st.columns(GRID_WIDTH)
for x in range(GRID_WIDTH):
player_here = None
for player_name, player_data in all_players.items():
if player_data['position']['x'] == x and player_data['position']['y'] == y:
player_here = player_name
# Display the player or other players using the preloaded images
if x == st.session_state.position['x'] and y == st.session_state.position['y']:
cols[x].image(images[map_layout[f"{x},{y}"]], use_column_width=True)
score = st.session_state.character_stats.get('score', 0)
cols[x].markdown(f"**You** ({score} pts)")
elif player_here:
cols[x].image(images[map_layout[f"{x},{y}"]], use_column_width=True)
player_score = all_players[player_here]['stats'].get('score', 0)
cols[x].markdown(f"**{player_here}** ({player_score} pts)")
else:
cols[x].image(images[map_layout[f"{x},{y}"]], use_column_width=True)
# ๐ฎ Main Game Loop
def main():
# Initialize timer in session state
if 'game_timer' not in st.session_state:
st.session_state.game_timer = GameTimer()
st.sidebar.title("Player Info")
if st.session_state.player_name is None:
default_name = generate_fantasy_name()
player_name = st.sidebar.text_input("Enter your name or use generated name:", value=default_name)
if st.sidebar.button("Start Playing"):
st.session_state.player_name = player_name
if st.session_state.character_stats is None:
st.session_state.character_stats = {
'STR': sum(sorted([random.randint(1, 6) for _ in range(4)])[1:]),
'DEX': sum(sorted([random.randint(1, 6) for _ in range(4)])[1:]),
'CON': sum(sorted([random.randint(1, 6) for _ in range(4)])[1:]),
'INT': sum(sorted([random.randint(1, 6) for _ in range(4)])[1:]),
'WIS': sum(sorted([random.randint(1, 6) for _ in range(4)])[1:]),
'CHA': sum(sorted([random.randint(1, 6) for _ in range(4)])[1:]),
'HP': random.randint(1, 20) * 2 + random.randint(1, 20),
'MAX_HP': 40,
'score': 0,
'created_at': time.time()
}
save_player_state()
st.rerun()
else:
st.sidebar.markdown("### Nearby Players")
for player in st.session_state.nearby_players:
st.sidebar.markdown(
f"**{player['name']}** - {player['distance']} tiles away - {player['score']} pts\n"
f"Last seen: {player['last_seen']:.1f}s ago"
)
st.sidebar.markdown("### Movement Controls")
move_cols = st.sidebar.columns(3)
if move_cols[1].button("โฌ๏ธ", key="up"):
update_position("up")
st.rerun()
cols = st.sidebar.columns(3)
if cols[0].button("โฌ
๏ธ", key="left"):
update_position("left")
st.rerun()
if cols[1].button("โฌ๏ธ", key="down"):
update_position("down")
st.rerun()
if cols[2].button("โก๏ธ", key="right"):
update_position("right")
st.rerun()
st.title("Multiplayer Tile Game")
create_game_board()
# ๐งน Cleanup on exit
def cleanup():
if 'game_timer' in st.session_state:
st.session_state.game_timer.stop()
# Register cleanup
atexit.register(cleanup)
if __name__ == "__main__":
main()
|