-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun_visualizer.py
More file actions
executable file
·190 lines (159 loc) · 6.16 KB
/
run_visualizer.py
File metadata and controls
executable file
·190 lines (159 loc) · 6.16 KB
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
#!/usr/bin/env python3
"""
Quick launcher for the Slither.io visualizer
Automatically creates and manages a virtual environment if needed.
"""
import sys
import subprocess
import os
from pathlib import Path
from urllib import error, request
import json
VENV_DIR = Path(__file__).parent / "visualizer_venv"
REQUIREMENTS_FILE = Path(__file__).parent / "visualizer_requirements.txt"
KNOWN_SERVER_HOSTS = [
("Localhost", "http://127.0.0.1:5055"),
("VPS", "http://81.17.103.197:5055")
]
def is_in_venv():
"""Check if we're running inside a virtual environment"""
return hasattr(sys, 'real_prefix') or (
hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
def create_venv():
"""Create a virtual environment"""
print("Creating virtual environment for visualizer...")
try:
subprocess.check_call([sys.executable, "-m", "venv", str(VENV_DIR)])
print("✓ Virtual environment created")
return True
except subprocess.CalledProcessError as e:
print(f"✗ Failed to create virtual environment: {e}")
return False
def get_venv_python():
"""Get the path to the Python executable in the venv"""
if sys.platform == "win32":
return VENV_DIR / "Scripts" / "python.exe"
return VENV_DIR / "bin" / "python"
def setup_venv():
"""Setup virtual environment if not already in one"""
if is_in_venv():
return True
if not VENV_DIR.exists():
print("Virtual environment not found.")
if not create_venv():
return False
# Re-run this script using the venv Python
venv_python = get_venv_python()
print(f"Switching to virtual environment...")
print("-" * 50)
os.execv(str(venv_python), [str(venv_python)] + sys.argv)
def check_dependencies():
"""Check if required packages are installed"""
try:
import pygame
import numpy
import requests
print("✓ All dependencies are installed")
return True
except ImportError as e:
print(f"✗ Missing dependency: {e}")
return False
def install_dependencies():
"""Install required packages"""
print("Installing dependencies...")
try:
subprocess.check_call([
sys.executable, "-m", "pip", "install", "--upgrade", "pip"
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if REQUIREMENTS_FILE.exists():
subprocess.check_call([
sys.executable, "-m", "pip", "install", "-r", str(REQUIREMENTS_FILE)
])
else:
# Fallback: install essential packages
subprocess.check_call([
sys.executable, "-m", "pip", "install", "pygame", "numpy", "requests"
])
print("✓ Dependencies installed successfully")
return True
except subprocess.CalledProcessError:
print("✗ Failed to install dependencies")
return False
def check_server_health(host):
"""Check whether a server responds to /health using only stdlib."""
try:
with request.urlopen(f"{host}/health", timeout=1.5) as response:
payload = json.loads(response.read().decode("utf-8"))
return True, payload
except (error.URLError, error.HTTPError, TimeoutError, json.JSONDecodeError, OSError):
return False, None
def choose_server_host():
"""Ask the user which backend host the visualizer should use."""
print("\nServer disponibili:")
statuses = []
for index, (label, host) in enumerate(KNOWN_SERVER_HOSTS, start=1):
is_online, payload = check_server_health(host)
statuses.append({
"label": label,
"host": host,
"online": is_online,
"payload": payload
})
status_label = "online" if is_online else "offline"
print(f" {index}. {label}: {host} [{status_label}]")
print(f" {len(KNOWN_SERVER_HOSTS) + 1}. Custom host")
localhost_online = statuses[0]["online"]
remote_online = len(statuses) > 1 and statuses[1]["online"]
if not localhost_online and remote_online:
print(f"Suggerimento: usa {statuses[1]['host']} perché localhost non risponde.")
choice = input(f"Seleziona il server [1]: ").strip()
if not choice or choice == '1':
return KNOWN_SERVER_HOSTS[0][1]
if choice == '2' and len(KNOWN_SERVER_HOSTS) >= 2:
return KNOWN_SERVER_HOSTS[1][1]
if choice == str(len(KNOWN_SERVER_HOSTS) + 1):
custom_host = input("Inserisci host custom (es. http://host:5055): ").strip().rstrip('/')
return custom_host or KNOWN_SERVER_HOSTS[0][1]
typed_host = choice.rstrip('/')
return typed_host if typed_host.startswith('http://') or typed_host.startswith('https://') else KNOWN_SERVER_HOSTS[0][1]
def main():
"""Main launcher"""
print("Slither.io Data Visualizer Launcher")
print("=" * 50)
# Check if visualizer.py exists
visualizer_path = Path(__file__).parent / "visualizer.py"
if not visualizer_path.exists():
print("✗ visualizer.py not found in the current directory.")
return 1
# Setup virtual environment (will restart script if needed)
setup_venv()
# At this point we're definitely in a venv
print(f"Running in virtual environment: {sys.prefix}")
# Check dependencies
if not check_dependencies():
print("\nAttempting to install dependencies...")
if not install_dependencies():
print("\nFailed to install dependencies. Please check the error messages above.")
return 1
selected_server = choose_server_host()
os.environ['SLITHER_SERVER_URL'] = selected_server
# Start the visualizer
print("\nStarting visualizer...")
print(f"Using backend server: {selected_server}")
print("Press Ctrl+C to stop")
print("-" * 50)
try:
# Import and run visualizer
import runpy
runpy.run_path(str(visualizer_path), run_name="__main__")
except KeyboardInterrupt:
print("\n\nVisualizer stopped by user")
return 0
except Exception as e:
print(f"\n✗ Visualizer error: {e}")
import traceback
traceback.print_exc()
return 1
if __name__ == "__main__":
sys.exit(main())