awacke1 commited on
Commit
53bbde1
ยท
verified ยท
1 Parent(s): c166997

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -5
app.py CHANGED
@@ -9,6 +9,11 @@ from pathlib import Path
9
  import base64
10
  from io import BytesIO
11
  import numpy as np
 
 
 
 
 
12
 
13
  # ๐ŸŽฎ Game Constants
14
  GRID_WIDTH = 16
@@ -17,7 +22,40 @@ REFRESH_RATE = 5
17
  INTERACTION_RADIUS = 2
18
  POINTS_PER_INTERACTION = 1
19
 
20
- # ๐Ÿ“ Name Generation - Independent function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def generate_fantasy_name():
22
  prefixes = ['Aer', 'Bal', 'Cal', 'Dor', 'El', 'Fae', 'Gor', 'Hel', 'Il', 'Jor',
23
  'Kal', 'Lyr', 'Mel', 'Nym', 'Oro', 'Pyr', 'Qar', 'Ryn', 'Syl', 'Tyr']
@@ -59,19 +97,22 @@ def create_autorefresh():
59
  refresh_html = """
60
  <script>
61
  let lastUpdate = Date.now();
62
- let serverTimeOffset = 0;
63
 
64
  function checkForUpdates() {
65
  const now = Date.now();
66
  if (now - lastUpdate >= 5000) {
67
  lastUpdate = now;
68
  window.parent.document.querySelector('.stApp').classList.add('refreshing');
69
- setTimeout(() => window.location.reload(), 100);
70
  }
71
  }
72
 
73
  function startAutoRefresh() {
74
- setInterval(checkForUpdates, 1000);
 
 
 
75
  document.addEventListener('visibilitychange', function() {
76
  if (!document.hidden) {
77
  lastUpdate = Date.now() - 4900;
@@ -84,6 +125,13 @@ def create_autorefresh():
84
  } else {
85
  window.addEventListener('load', startAutoRefresh);
86
  }
 
 
 
 
 
 
 
87
  </script>
88
  """
89
  st.components.v1.html(refresh_html, height=0)
@@ -218,7 +266,16 @@ def create_game_board():
218
  # ๐ŸŽฎ Main Game Loop
219
  def main():
220
  create_autorefresh()
221
- update_nearby_players()
 
 
 
 
 
 
 
 
 
222
 
223
  st.sidebar.title("Player Info")
224
 
@@ -267,6 +324,7 @@ def main():
267
  st.rerun()
268
 
269
  if st.sidebar.button("Clear Game State"):
 
270
  st.query_params.clear()
271
  clear_caches()
272
  st.rerun()
@@ -274,5 +332,13 @@ def main():
274
  st.title("Multiplayer Tile Game")
275
  create_game_board()
276
 
 
 
 
 
 
 
 
 
277
  if __name__ == "__main__":
278
  main()
 
9
  import base64
10
  from io import BytesIO
11
  import numpy as np
12
+ import asyncio
13
+ import threading
14
+ from typing import Optional
15
+ import queue
16
+ import atexit
17
 
18
  # ๐ŸŽฎ Game Constants
19
  GRID_WIDTH = 16
 
22
  INTERACTION_RADIUS = 2
23
  POINTS_PER_INTERACTION = 1
24
 
25
+ # ๐Ÿ•’ Timer Management
26
+ class GameTimer:
27
+ def __init__(self):
28
+ self.running = True
29
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
30
+ self.update_queue = queue.Queue()
31
+ self.thread = threading.Thread(target=self._run_timer, daemon=True)
32
+ self.thread.start()
33
+
34
+ def _run_timer(self):
35
+ self._loop = asyncio.new_event_loop()
36
+ asyncio.set_event_loop(self._loop)
37
+ self._loop.run_until_complete(self._timer_loop())
38
+
39
+ async def _timer_loop(self):
40
+ while self.running:
41
+ try:
42
+ current_time = time.time()
43
+ self.update_queue.put(('update', current_time))
44
+ await asyncio.sleep(REFRESH_RATE)
45
+ except Exception as e:
46
+ print(f"Timer error: {e}")
47
+ await asyncio.sleep(1)
48
+
49
+ def stop(self):
50
+ self.running = False
51
+ if self._loop:
52
+ self._loop.stop()
53
+
54
+ # Initialize timer in session state
55
+ if 'game_timer' not in st.session_state:
56
+ st.session_state.game_timer = GameTimer()
57
+
58
+ # ๐Ÿ“ Name Generation
59
  def generate_fantasy_name():
60
  prefixes = ['Aer', 'Bal', 'Cal', 'Dor', 'El', 'Fae', 'Gor', 'Hel', 'Il', 'Jor',
61
  'Kal', 'Lyr', 'Mel', 'Nym', 'Oro', 'Pyr', 'Qar', 'Ryn', 'Syl', 'Tyr']
 
97
  refresh_html = """
98
  <script>
99
  let lastUpdate = Date.now();
100
+ let updateInterval = null;
101
 
102
  function checkForUpdates() {
103
  const now = Date.now();
104
  if (now - lastUpdate >= 5000) {
105
  lastUpdate = now;
106
  window.parent.document.querySelector('.stApp').classList.add('refreshing');
107
+ window.location.reload();
108
  }
109
  }
110
 
111
  function startAutoRefresh() {
112
+ if (!updateInterval) {
113
+ updateInterval = setInterval(checkForUpdates, 1000);
114
+ }
115
+
116
  document.addEventListener('visibilitychange', function() {
117
  if (!document.hidden) {
118
  lastUpdate = Date.now() - 4900;
 
125
  } else {
126
  window.addEventListener('load', startAutoRefresh);
127
  }
128
+
129
+ // Cleanup on unload
130
+ window.addEventListener('unload', function() {
131
+ if (updateInterval) {
132
+ clearInterval(updateInterval);
133
+ }
134
+ });
135
  </script>
136
  """
137
  st.components.v1.html(refresh_html, height=0)
 
266
  # ๐ŸŽฎ Main Game Loop
267
  def main():
268
  create_autorefresh()
269
+
270
+ # Process any queued updates
271
+ try:
272
+ while not st.session_state.game_timer.update_queue.empty():
273
+ update_type, timestamp = st.session_state.game_timer.update_queue.get_nowait()
274
+ if update_type == 'update':
275
+ update_nearby_players()
276
+ save_player_state()
277
+ except queue.Empty:
278
+ pass
279
 
280
  st.sidebar.title("Player Info")
281
 
 
324
  st.rerun()
325
 
326
  if st.sidebar.button("Clear Game State"):
327
+ st.session_state.game_timer.stop()
328
  st.query_params.clear()
329
  clear_caches()
330
  st.rerun()
 
332
  st.title("Multiplayer Tile Game")
333
  create_game_board()
334
 
335
+ # ๐Ÿงน Cleanup on exit
336
+ def cleanup():
337
+ if 'game_timer' in st.session_state:
338
+ st.session_state.game_timer.stop()
339
+
340
+ # Register cleanup
341
+ atexit.register(cleanup)
342
+
343
  if __name__ == "__main__":
344
  main()