pyttd 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pyttd might be problematic. Click here for more details.
- pyttd/__init__.py +44 -0
- pyttd/client.py +1356 -0
- pyttd/commands.py +415 -0
- pyttd/game_state.py +344 -0
- pyttd/protocol.py +341 -0
- pyttd/py.typed +0 -0
- pyttd-1.0.0.dist-info/METADATA +253 -0
- pyttd-1.0.0.dist-info/RECORD +12 -0
- pyttd-1.0.0.dist-info/WHEEL +5 -0
- pyttd-1.0.0.dist-info/entry_points.txt +2 -0
- pyttd-1.0.0.dist-info/licenses/LICENSE +21 -0
- pyttd-1.0.0.dist-info/top_level.txt +1 -0
pyttd/client.py
ADDED
|
@@ -0,0 +1,1356 @@
|
|
|
1
|
+
"""Client Implementation
|
|
2
|
+
|
|
3
|
+
Main client class that implements the OpenTTD multiplayer protocol.
|
|
4
|
+
Handles connection, authentication, map synchronization, and game state management.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import hashlib
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Optional, Callable, Dict, Any, List, Tuple, Union
|
|
13
|
+
from enum import Enum
|
|
14
|
+
|
|
15
|
+
from .protocol import (
|
|
16
|
+
NetworkConnection,
|
|
17
|
+
Packet,
|
|
18
|
+
PacketType,
|
|
19
|
+
NetworkError,
|
|
20
|
+
coordinate_to_tile,
|
|
21
|
+
tile_to_coordinate,
|
|
22
|
+
)
|
|
23
|
+
from .game_state import GameState, CompanyID, CompanyInfo, VehicleInfo, ClientInfo, VehicleType
|
|
24
|
+
from .commands import CommandPacket, CommandBuilder, Commands, DoCommandFlag, RailType
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ClientStatus(Enum):
|
|
31
|
+
"""Client connection status"""
|
|
32
|
+
|
|
33
|
+
DISCONNECTED = "disconnected"
|
|
34
|
+
CONNECTING = "connecting"
|
|
35
|
+
JOINED = "joined"
|
|
36
|
+
AUTHENTICATING = "authenticating"
|
|
37
|
+
DOWNLOADING_MAP = "downloading_map"
|
|
38
|
+
ACTIVE = "active"
|
|
39
|
+
ERROR = "error"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class DesyncError(Exception):
|
|
43
|
+
"""Raised when client desyncs from server"""
|
|
44
|
+
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AuthenticationError(Exception):
|
|
49
|
+
"""Raised when authentication fails"""
|
|
50
|
+
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class OpenTTDClient:
|
|
55
|
+
"""Main client class"""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
server: str,
|
|
60
|
+
port: int = 3979,
|
|
61
|
+
player_name: str = "AI_Player",
|
|
62
|
+
company_name: str = "AI Co",
|
|
63
|
+
password: str = "",
|
|
64
|
+
company_password: str = "",
|
|
65
|
+
timeout: float = 30.0,
|
|
66
|
+
):
|
|
67
|
+
"""
|
|
68
|
+
Initialize OpenTTD client
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
server: Server IP address or hostname
|
|
72
|
+
port: Server port (default 3979)
|
|
73
|
+
player_name: Name for this player
|
|
74
|
+
company_name: Name for the company (when creating new company)
|
|
75
|
+
password: Server password if required
|
|
76
|
+
company_password: Company password if required
|
|
77
|
+
timeout: Connection timeout in seconds
|
|
78
|
+
"""
|
|
79
|
+
self.server = server
|
|
80
|
+
self.port = port
|
|
81
|
+
self.player_name = player_name
|
|
82
|
+
self.company_name = company_name
|
|
83
|
+
self.password = password
|
|
84
|
+
self.company_password = company_password
|
|
85
|
+
self.timeout = timeout
|
|
86
|
+
|
|
87
|
+
# Network connection
|
|
88
|
+
self.connection = NetworkConnection(server, port, timeout)
|
|
89
|
+
self.status = ClientStatus.DISCONNECTED
|
|
90
|
+
|
|
91
|
+
# Game state
|
|
92
|
+
self.game_state = GameState()
|
|
93
|
+
# Join as COMPANY_NEW_COMPANY to request company creation
|
|
94
|
+
self.game_state.company_id = CompanyID.COMPANY_NEW_COMPANY
|
|
95
|
+
|
|
96
|
+
# Client configuration
|
|
97
|
+
self.client_revision = "14.1" # Should match OpenTTD version
|
|
98
|
+
self.language_id = 0 # English
|
|
99
|
+
|
|
100
|
+
# Connection state
|
|
101
|
+
self._running = False
|
|
102
|
+
self._network_thread: Optional[threading.Thread] = None
|
|
103
|
+
|
|
104
|
+
# Company creation state
|
|
105
|
+
self.pending_company_name: Optional[str] = None
|
|
106
|
+
self._last_ack_frame = 0
|
|
107
|
+
self._token = 0
|
|
108
|
+
self._last_ack_time = 0.0
|
|
109
|
+
|
|
110
|
+
# Map synchronization
|
|
111
|
+
self._map_buffer = bytearray()
|
|
112
|
+
self._expected_map_size = 0
|
|
113
|
+
|
|
114
|
+
# Command queue
|
|
115
|
+
self._command_queue: List[CommandPacket] = []
|
|
116
|
+
self._command_callback: Optional[Callable[[Commands, bool, str], None]] = None
|
|
117
|
+
|
|
118
|
+
# Event callbacks
|
|
119
|
+
self._event_callbacks: Dict[str, List[Callable]] = {
|
|
120
|
+
"connected": [],
|
|
121
|
+
"disconnected": [],
|
|
122
|
+
"map_complete": [],
|
|
123
|
+
"game_joined": [],
|
|
124
|
+
"command_result": [],
|
|
125
|
+
"chat_message": [],
|
|
126
|
+
"desync": [],
|
|
127
|
+
"error": [],
|
|
128
|
+
"company_created": [],
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
def on(self, event: str, callback: Callable) -> None:
|
|
132
|
+
"""Register event callback"""
|
|
133
|
+
if event in self._event_callbacks:
|
|
134
|
+
self._event_callbacks[event].append(callback)
|
|
135
|
+
|
|
136
|
+
def _emit_event(self, event: str, *args: Any) -> None:
|
|
137
|
+
"""Emit event to registered callbacks"""
|
|
138
|
+
if event in self._event_callbacks:
|
|
139
|
+
for callback in self._event_callbacks[event]:
|
|
140
|
+
try:
|
|
141
|
+
callback(*args)
|
|
142
|
+
except Exception as e:
|
|
143
|
+
logger.error(f"Error in event callback {event}: {e}")
|
|
144
|
+
|
|
145
|
+
def connect(self) -> bool:
|
|
146
|
+
"""
|
|
147
|
+
Connect to the server and complete join process
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
True if successfully connected and joined, False otherwise
|
|
151
|
+
"""
|
|
152
|
+
try:
|
|
153
|
+
logger.info(f"Connecting to {self.server}:{self.port}")
|
|
154
|
+
self.status = ClientStatus.CONNECTING
|
|
155
|
+
|
|
156
|
+
# Establish TCP connection
|
|
157
|
+
self.connection.connect()
|
|
158
|
+
|
|
159
|
+
# Start network thread
|
|
160
|
+
self._running = True
|
|
161
|
+
self._network_thread = threading.Thread(target=self._network_loop, daemon=True)
|
|
162
|
+
self._network_thread.start()
|
|
163
|
+
|
|
164
|
+
# Send join packet
|
|
165
|
+
self._send_join()
|
|
166
|
+
|
|
167
|
+
# Wait for connection to be established (with timeout)
|
|
168
|
+
timeout_start = time.time()
|
|
169
|
+
while self.status not in [ClientStatus.ACTIVE, ClientStatus.ERROR]:
|
|
170
|
+
if time.time() - timeout_start > self.timeout:
|
|
171
|
+
logger.error("Connection timeout")
|
|
172
|
+
self.disconnect()
|
|
173
|
+
return False
|
|
174
|
+
time.sleep(0.1)
|
|
175
|
+
|
|
176
|
+
if self.status == ClientStatus.ACTIVE:
|
|
177
|
+
logger.info("Successfully connected and joined game")
|
|
178
|
+
self._emit_event("connected")
|
|
179
|
+
return True
|
|
180
|
+
else:
|
|
181
|
+
logger.error("Failed to connect")
|
|
182
|
+
return False
|
|
183
|
+
|
|
184
|
+
except Exception as e:
|
|
185
|
+
logger.error(f"Connection failed: {e}")
|
|
186
|
+
self.status = ClientStatus.ERROR
|
|
187
|
+
self._emit_event("error", str(e))
|
|
188
|
+
return False
|
|
189
|
+
|
|
190
|
+
def disconnect(self) -> None:
|
|
191
|
+
"""Disconnect from server"""
|
|
192
|
+
logger.info("Disconnecting from server")
|
|
193
|
+
|
|
194
|
+
self._running = False
|
|
195
|
+
|
|
196
|
+
if self.connection.is_connected():
|
|
197
|
+
try:
|
|
198
|
+
# Send quit packet
|
|
199
|
+
packet = Packet(PacketType.CLIENT_QUIT)
|
|
200
|
+
self.connection.send_packet(packet)
|
|
201
|
+
except:
|
|
202
|
+
pass # Ignore errors during disconnect
|
|
203
|
+
|
|
204
|
+
self.connection.close()
|
|
205
|
+
self.status = ClientStatus.DISCONNECTED
|
|
206
|
+
|
|
207
|
+
if self._network_thread and self._network_thread.is_alive():
|
|
208
|
+
self._network_thread.join(timeout=1.0)
|
|
209
|
+
|
|
210
|
+
self._emit_event("disconnected")
|
|
211
|
+
|
|
212
|
+
def is_connected(self) -> bool:
|
|
213
|
+
"""Check if connected to server"""
|
|
214
|
+
return self.status == ClientStatus.ACTIVE
|
|
215
|
+
|
|
216
|
+
# ============================================
|
|
217
|
+
# Game Data Query Methods
|
|
218
|
+
# ============================================
|
|
219
|
+
|
|
220
|
+
def get_game_info(self) -> Dict[str, Any]:
|
|
221
|
+
"""Get game information"""
|
|
222
|
+
# Use real game data from SERVER_GAME_INFO if available
|
|
223
|
+
if hasattr(self, "_real_game_data") and self._real_game_data:
|
|
224
|
+
real_data = self._real_game_data
|
|
225
|
+
return {
|
|
226
|
+
"client_id": self.game_state.client_id,
|
|
227
|
+
"company_id": self.game_state.company_id,
|
|
228
|
+
"frame": real_data.get("ticks_playing", self.game_state.frame),
|
|
229
|
+
"frame_max": self.game_state.frame_max,
|
|
230
|
+
"date": real_data.get("current_year", self.game_state.game_date),
|
|
231
|
+
"calendar_date": real_data.get("calendar_date", 0),
|
|
232
|
+
"start_year": real_data.get("start_year", 1950),
|
|
233
|
+
"current_year": real_data.get("current_year", 1950),
|
|
234
|
+
"map_size": f"{real_data.get('map_width', self.game_state.map_info.size_x)}x{real_data.get('map_height', self.game_state.map_info.size_y)}",
|
|
235
|
+
"companies": real_data.get("companies_on", len(self.game_state.companies)),
|
|
236
|
+
"companies_max": real_data.get("companies_max", 15),
|
|
237
|
+
"clients": real_data.get("clients_on", len(self.game_state.clients)),
|
|
238
|
+
"clients_max": real_data.get("clients_max", 255),
|
|
239
|
+
"spectators": real_data.get("spectators_on", 0),
|
|
240
|
+
"vehicles": len(self.game_state.vehicles),
|
|
241
|
+
"server_name": real_data.get("server_name", "Unknown"),
|
|
242
|
+
"ticks_playing": real_data.get("ticks_playing", 0),
|
|
243
|
+
"synchronized": self.game_state.frame == self.game_state.frame_max,
|
|
244
|
+
"status": self.status.value,
|
|
245
|
+
}
|
|
246
|
+
else:
|
|
247
|
+
# Fallback to old method if no real game data available
|
|
248
|
+
return {
|
|
249
|
+
"client_id": self.game_state.client_id,
|
|
250
|
+
"company_id": self.game_state.company_id,
|
|
251
|
+
"frame": self.game_state.frame,
|
|
252
|
+
"frame_max": self.game_state.frame_max,
|
|
253
|
+
"date": self.game_state.game_date,
|
|
254
|
+
"map_size": f"{self.game_state.map_info.size_x}x{self.game_state.map_info.size_y}",
|
|
255
|
+
"companies": len(self.game_state.companies),
|
|
256
|
+
"clients": len(self.game_state.clients),
|
|
257
|
+
"vehicles": len(self.game_state.vehicles),
|
|
258
|
+
"synchronized": self.game_state.frame == self.game_state.frame_max,
|
|
259
|
+
"status": self.status.value,
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
def get_companies(self) -> Dict[int, Any]:
|
|
263
|
+
"""Get information about all companies"""
|
|
264
|
+
from dataclasses import asdict
|
|
265
|
+
|
|
266
|
+
return {cid: asdict(company) for cid, company in self.game_state.companies.items()}
|
|
267
|
+
|
|
268
|
+
def get_our_company(self) -> Optional[Any]:
|
|
269
|
+
"""Get our company information if we're in a company"""
|
|
270
|
+
if self.game_state.company_id is not None and self.game_state.company_id != 255:
|
|
271
|
+
return self.game_state.companies.get(self.game_state.company_id)
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
def get_clients(self) -> Dict[int, Any]:
|
|
275
|
+
"""Get information about all connected clients"""
|
|
276
|
+
from dataclasses import asdict
|
|
277
|
+
|
|
278
|
+
return {cid: asdict(client) for cid, client in self.game_state.clients.items()}
|
|
279
|
+
|
|
280
|
+
def get_vehicles(self) -> Dict[int, Any]:
|
|
281
|
+
"""Get information about all vehicles"""
|
|
282
|
+
from dataclasses import asdict
|
|
283
|
+
|
|
284
|
+
return {vid: asdict(vehicle) for vid, vehicle in self.game_state.vehicles.items()}
|
|
285
|
+
|
|
286
|
+
def get_our_vehicles(self) -> Dict[int, Any]:
|
|
287
|
+
"""Get vehicles belonging to our company"""
|
|
288
|
+
if self.game_state.company_id is None or self.game_state.company_id == 255:
|
|
289
|
+
return {}
|
|
290
|
+
from dataclasses import asdict
|
|
291
|
+
|
|
292
|
+
return {
|
|
293
|
+
vid: asdict(vehicle)
|
|
294
|
+
for vid, vehicle in self.game_state.vehicles.items()
|
|
295
|
+
if vehicle.company_id == self.game_state.company_id
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
def get_map_info(self) -> Dict[str, Any]:
|
|
299
|
+
"""Get map information"""
|
|
300
|
+
return {
|
|
301
|
+
"size_x": self.game_state.map_info.size_x,
|
|
302
|
+
"size_y": self.game_state.map_info.size_y,
|
|
303
|
+
"total_tiles": self.game_state.map_info.size_x * self.game_state.map_info.size_y,
|
|
304
|
+
"has_map_data": hasattr(self.game_state.map_info, "compressed_data")
|
|
305
|
+
and self.game_state.map_info.compressed_data is not None,
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
def send_command(self, command: CommandPacket) -> bool:
|
|
309
|
+
"""
|
|
310
|
+
Send command to server for execution
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
command: Command packet to send
|
|
314
|
+
|
|
315
|
+
Returns:
|
|
316
|
+
True if command was sent successfully
|
|
317
|
+
"""
|
|
318
|
+
if not self.is_connected():
|
|
319
|
+
logger.warning("Cannot send command: not connected")
|
|
320
|
+
return False
|
|
321
|
+
|
|
322
|
+
try:
|
|
323
|
+
packet = Packet(PacketType.CLIENT_COMMAND)
|
|
324
|
+
packet.write_uint8(command.company)
|
|
325
|
+
packet.write_uint16(command.command_id) # Fixed: uint16 not uint32
|
|
326
|
+
packet.write_uint16(0) # err_msg field (STR_NULL = 0)
|
|
327
|
+
packet.write_buffer(command.encode_parameters())
|
|
328
|
+
packet.write_uint8(command.callback_id)
|
|
329
|
+
|
|
330
|
+
self.connection.send_packet(packet)
|
|
331
|
+
logger.info(
|
|
332
|
+
f"Sent command: {command.command_id} (company={command.company}, p1={command.p1}, p2={command.p2}, text='{command.text}')"
|
|
333
|
+
)
|
|
334
|
+
return True
|
|
335
|
+
|
|
336
|
+
except Exception as e:
|
|
337
|
+
logger.error(f"Failed to send command: {e}")
|
|
338
|
+
return False
|
|
339
|
+
|
|
340
|
+
def build_rail(
|
|
341
|
+
self, start: Tuple[int, int], end: Tuple[int, int], rail_type: RailType = RailType.RAIL
|
|
342
|
+
) -> bool:
|
|
343
|
+
"""
|
|
344
|
+
Build railroad track between two coordinates
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
start: Starting coordinate (x, y)
|
|
348
|
+
end: Ending coordinate (x, y)
|
|
349
|
+
rail_type: Type of rail (0=normal, 1=electric, etc.)
|
|
350
|
+
|
|
351
|
+
Returns:
|
|
352
|
+
True if command was sent successfully
|
|
353
|
+
"""
|
|
354
|
+
start_tile = coordinate_to_tile(start[0], start[1], self.game_state.map_info.size_x)
|
|
355
|
+
end_tile = coordinate_to_tile(end[0], end[1], self.game_state.map_info.size_x)
|
|
356
|
+
|
|
357
|
+
command = CommandBuilder.build_rail(
|
|
358
|
+
start_tile, end_tile, rail_type, int(self.game_state.company_id)
|
|
359
|
+
)
|
|
360
|
+
return self.send_command(command)
|
|
361
|
+
|
|
362
|
+
def build_train_depot(
|
|
363
|
+
self, x: int, y: int, direction: int = 0, rail_type: RailType = RailType.RAIL
|
|
364
|
+
) -> bool:
|
|
365
|
+
"""Build a train depot at coordinates"""
|
|
366
|
+
tile = coordinate_to_tile(x, y, self.game_state.map_info.size_x)
|
|
367
|
+
command = CommandBuilder.build_train_depot(
|
|
368
|
+
tile, direction, rail_type, int(self.game_state.company_id)
|
|
369
|
+
)
|
|
370
|
+
return self.send_command(command)
|
|
371
|
+
|
|
372
|
+
def build_train(self, depot_x: int, depot_y: int, engine_id: int = 0) -> bool:
|
|
373
|
+
"""Build a train at depot"""
|
|
374
|
+
depot_tile = coordinate_to_tile(depot_x, depot_y, self.game_state.map_info.size_x)
|
|
375
|
+
command = CommandBuilder.build_vehicle(
|
|
376
|
+
depot_tile, engine_id, int(self.game_state.company_id)
|
|
377
|
+
)
|
|
378
|
+
return self.send_command(command)
|
|
379
|
+
|
|
380
|
+
# ============================================
|
|
381
|
+
# Enhanced Building and Construction Methods
|
|
382
|
+
# ============================================
|
|
383
|
+
|
|
384
|
+
def create_company(self, company_name: str = "Bot Company", password: str = "") -> bool:
|
|
385
|
+
"""Create a new company (happens automatically when joining with COMPANY_NEW_COMPANY)"""
|
|
386
|
+
if not self.is_connected():
|
|
387
|
+
logger.warning("Cannot create company: not connected")
|
|
388
|
+
return False
|
|
389
|
+
|
|
390
|
+
# Store the company name for when we get assigned to the new company
|
|
391
|
+
self.pending_company_name = company_name
|
|
392
|
+
|
|
393
|
+
logger.info(
|
|
394
|
+
f"Company creation will happen automatically during join process: {company_name}"
|
|
395
|
+
)
|
|
396
|
+
# Note: When client joins with COMPANY_NEW_COMPANY, the server checks company limits
|
|
397
|
+
# and then the client automatically sends CMD_COMPANY_CTRL during the join sequence
|
|
398
|
+
return True
|
|
399
|
+
|
|
400
|
+
def build_railway_line(
|
|
401
|
+
self, start: Tuple[int, int], end: Tuple[int, int], rail_type: RailType = RailType.RAIL
|
|
402
|
+
) -> bool:
|
|
403
|
+
"""Build a complete railway line between two points"""
|
|
404
|
+
if not self.is_connected():
|
|
405
|
+
logger.warning("Cannot build railway: not connected")
|
|
406
|
+
return False
|
|
407
|
+
|
|
408
|
+
# Simple straight line implementation
|
|
409
|
+
# In a real implementation, this would include pathfinding
|
|
410
|
+
success = self.build_rail(start, end, rail_type)
|
|
411
|
+
if success:
|
|
412
|
+
logger.info(f"Built railway from {start} to {end}")
|
|
413
|
+
return success
|
|
414
|
+
|
|
415
|
+
def build_station_with_rail(
|
|
416
|
+
self, x: int, y: int, direction: int = 0, platform_length: int = 4, num_platforms: int = 1
|
|
417
|
+
) -> bool:
|
|
418
|
+
"""Build a railway station with connecting rails"""
|
|
419
|
+
if not self.is_connected():
|
|
420
|
+
logger.warning("Cannot build station: not connected")
|
|
421
|
+
return False
|
|
422
|
+
|
|
423
|
+
# Build the station
|
|
424
|
+
success = True
|
|
425
|
+
try:
|
|
426
|
+
# This would need proper station building implementation
|
|
427
|
+
logger.info(
|
|
428
|
+
f"Building station at ({x}, {y}) with {num_platforms} platforms, length {platform_length}"
|
|
429
|
+
)
|
|
430
|
+
# For now, just build a simple rail station
|
|
431
|
+
# Real implementation would use CMD_BUILD_RAIL_STATION
|
|
432
|
+
return False # Not implemented yet
|
|
433
|
+
except Exception as e:
|
|
434
|
+
logger.error(f"Failed to build station: {e}")
|
|
435
|
+
return False
|
|
436
|
+
|
|
437
|
+
def buy_and_start_train(
|
|
438
|
+
self,
|
|
439
|
+
depot_x: int,
|
|
440
|
+
depot_y: int,
|
|
441
|
+
engine_id: int = 0,
|
|
442
|
+
destination_station: Optional[Tuple[int, int]] = None,
|
|
443
|
+
) -> bool:
|
|
444
|
+
"""Buy a train and set up basic orders"""
|
|
445
|
+
if not self.is_connected():
|
|
446
|
+
logger.warning("Cannot buy train: not connected")
|
|
447
|
+
return False
|
|
448
|
+
|
|
449
|
+
# Build the train
|
|
450
|
+
success = self.build_train(depot_x, depot_y, engine_id)
|
|
451
|
+
if not success:
|
|
452
|
+
return False
|
|
453
|
+
|
|
454
|
+
# If destination provided, add orders (not implemented yet)
|
|
455
|
+
if destination_station:
|
|
456
|
+
logger.info(f"Train built, destination orders not yet implemented")
|
|
457
|
+
|
|
458
|
+
return True
|
|
459
|
+
|
|
460
|
+
def terraform_area(self, x: int, y: int, width: int, height: int, new_height: int) -> bool:
|
|
461
|
+
"""Terraform an area to a specific height"""
|
|
462
|
+
if not self.is_connected():
|
|
463
|
+
logger.warning("Cannot terraform: not connected")
|
|
464
|
+
return False
|
|
465
|
+
|
|
466
|
+
# This would require implementing terraform commands
|
|
467
|
+
logger.info(f"Terraforming area ({x},{y}) to ({x+width},{y+height}) at height {new_height}")
|
|
468
|
+
return False # Not implemented yet
|
|
469
|
+
|
|
470
|
+
def clear_area(self, x: int, y: int, width: int, height: int) -> bool:
|
|
471
|
+
"""Clear an area of all objects"""
|
|
472
|
+
if not self.is_connected():
|
|
473
|
+
logger.warning("Cannot clear area: not connected")
|
|
474
|
+
return False
|
|
475
|
+
|
|
476
|
+
success_count = 0
|
|
477
|
+
total_tiles = width * height
|
|
478
|
+
|
|
479
|
+
for dx in range(width):
|
|
480
|
+
for dy in range(height):
|
|
481
|
+
tile_x = x + dx
|
|
482
|
+
tile_y = y + dy
|
|
483
|
+
# Use landscape clear command
|
|
484
|
+
# This is a simplified version - real implementation would batch commands
|
|
485
|
+
try:
|
|
486
|
+
# Would use CMD_LANDSCAPE_CLEAR command here
|
|
487
|
+
success_count += 1
|
|
488
|
+
except Exception as e:
|
|
489
|
+
logger.debug(f"Failed to clear tile ({tile_x}, {tile_y}): {e}")
|
|
490
|
+
|
|
491
|
+
logger.info(
|
|
492
|
+
f"Cleared {success_count}/{total_tiles} tiles in area ({x},{y}) to ({x+width},{y+height})"
|
|
493
|
+
)
|
|
494
|
+
return success_count > total_tiles * 0.8 # Consider success if 80%+ cleared
|
|
495
|
+
|
|
496
|
+
def send_chat(self, message: str, destination_type: int = 0, destination: int = 0) -> bool:
|
|
497
|
+
"""Send chat message"""
|
|
498
|
+
if not self.is_connected():
|
|
499
|
+
return False
|
|
500
|
+
|
|
501
|
+
try:
|
|
502
|
+
packet = Packet(PacketType.CLIENT_CHAT)
|
|
503
|
+
packet.write_uint8(3) # Network action (3 = NETWORK_ACTION_CHAT)
|
|
504
|
+
packet.write_uint8(destination_type) # Destination type
|
|
505
|
+
packet.write_uint32(destination) # Destination ID
|
|
506
|
+
packet.write_string(message)
|
|
507
|
+
packet.write_uint64(0) # Data (for money transfers, etc.)
|
|
508
|
+
|
|
509
|
+
self.connection.send_packet(packet)
|
|
510
|
+
return True
|
|
511
|
+
|
|
512
|
+
except Exception as e:
|
|
513
|
+
logger.error(f"Failed to send chat: {e}")
|
|
514
|
+
return False
|
|
515
|
+
|
|
516
|
+
# ============================================
|
|
517
|
+
# Company Management and Economy Methods
|
|
518
|
+
# ============================================
|
|
519
|
+
|
|
520
|
+
def increase_loan(self, amount: int) -> bool:
|
|
521
|
+
"""Increase company loan by specified amount"""
|
|
522
|
+
if not self.is_connected() or self.game_state.company_id == CompanyID.COMPANY_SPECTATOR:
|
|
523
|
+
logger.warning("Cannot increase loan: not in a company")
|
|
524
|
+
return False
|
|
525
|
+
|
|
526
|
+
command = CommandBuilder.increase_loan(amount, int(self.game_state.company_id))
|
|
527
|
+
success = self.send_command(command)
|
|
528
|
+
if success:
|
|
529
|
+
logger.info(f"💰 Requested loan increase of £{amount:,}")
|
|
530
|
+
return success
|
|
531
|
+
|
|
532
|
+
def decrease_loan(self, amount: int) -> bool:
|
|
533
|
+
"""Decrease company loan by specified amount"""
|
|
534
|
+
if not self.is_connected() or self.game_state.company_id == CompanyID.COMPANY_SPECTATOR:
|
|
535
|
+
logger.warning("Cannot decrease loan: not in a company")
|
|
536
|
+
return False
|
|
537
|
+
|
|
538
|
+
command = CommandBuilder.decrease_loan(amount, int(self.game_state.company_id))
|
|
539
|
+
success = self.send_command(command)
|
|
540
|
+
if success:
|
|
541
|
+
logger.info(f"💳 Requested loan decrease of £{amount:,}")
|
|
542
|
+
return success
|
|
543
|
+
|
|
544
|
+
def rename_company(self, new_name: str) -> bool:
|
|
545
|
+
"""Rename the company"""
|
|
546
|
+
if not self.is_connected() or self.game_state.company_id == CompanyID.COMPANY_SPECTATOR:
|
|
547
|
+
logger.warning("Cannot rename company: not in a company")
|
|
548
|
+
return False
|
|
549
|
+
|
|
550
|
+
if len(new_name.strip()) == 0:
|
|
551
|
+
logger.warning("Cannot rename company to empty name")
|
|
552
|
+
return False
|
|
553
|
+
|
|
554
|
+
command = CommandBuilder.rename_company(new_name, int(self.game_state.company_id))
|
|
555
|
+
success = self.send_command(command)
|
|
556
|
+
if success:
|
|
557
|
+
logger.info(f"🏢 Requested company rename to: '{new_name}'")
|
|
558
|
+
self.company_name = new_name # Update our local record
|
|
559
|
+
return success
|
|
560
|
+
|
|
561
|
+
def rename_president(self, new_name: str) -> bool:
|
|
562
|
+
"""Rename the company president/manager"""
|
|
563
|
+
if not self.is_connected() or self.game_state.company_id == CompanyID.COMPANY_SPECTATOR:
|
|
564
|
+
logger.warning("Cannot rename president: not in a company")
|
|
565
|
+
return False
|
|
566
|
+
|
|
567
|
+
if len(new_name.strip()) == 0:
|
|
568
|
+
logger.warning("Cannot rename president to empty name")
|
|
569
|
+
return False
|
|
570
|
+
|
|
571
|
+
command = CommandBuilder.rename_president(new_name, int(self.game_state.company_id))
|
|
572
|
+
success = self.send_command(command)
|
|
573
|
+
if success:
|
|
574
|
+
logger.info(f"👤 Requested president rename to: '{new_name}'")
|
|
575
|
+
return success
|
|
576
|
+
|
|
577
|
+
def set_company_colour(self, scheme: int = 0, primary: bool = True, colour: int = 0) -> bool:
|
|
578
|
+
"""Set company livery colour scheme"""
|
|
579
|
+
if not self.is_connected() or self.game_state.company_id == CompanyID.COMPANY_SPECTATOR:
|
|
580
|
+
logger.warning("Cannot set company colour: not in a company")
|
|
581
|
+
return False
|
|
582
|
+
|
|
583
|
+
command = CommandBuilder.set_company_colour(
|
|
584
|
+
scheme, primary, colour, int(self.game_state.company_id)
|
|
585
|
+
)
|
|
586
|
+
success = self.send_command(command)
|
|
587
|
+
if success:
|
|
588
|
+
logger.info(
|
|
589
|
+
f"🎨 Requested colour change: scheme={scheme}, primary={primary}, colour={colour}"
|
|
590
|
+
)
|
|
591
|
+
return success
|
|
592
|
+
|
|
593
|
+
def give_money(self, amount: int, dest_company: int) -> bool:
|
|
594
|
+
"""Transfer money to another company"""
|
|
595
|
+
if not self.is_connected() or self.game_state.company_id == CompanyID.COMPANY_SPECTATOR:
|
|
596
|
+
logger.warning("Cannot give money: not in a company")
|
|
597
|
+
return False
|
|
598
|
+
|
|
599
|
+
if amount <= 0:
|
|
600
|
+
logger.warning("Cannot give negative or zero money")
|
|
601
|
+
return False
|
|
602
|
+
|
|
603
|
+
command = CommandBuilder.give_money(amount, dest_company, int(self.game_state.company_id))
|
|
604
|
+
success = self.send_command(command)
|
|
605
|
+
if success:
|
|
606
|
+
logger.info(f"💸 Requested money transfer: £{amount:,} to Company {dest_company}")
|
|
607
|
+
return success
|
|
608
|
+
|
|
609
|
+
def get_company_finances(self) -> dict:
|
|
610
|
+
"""Get current company financial information"""
|
|
611
|
+
our_company = self.get_our_company()
|
|
612
|
+
if not our_company:
|
|
613
|
+
return {}
|
|
614
|
+
|
|
615
|
+
# Convert CompanyInfo to dict for finances
|
|
616
|
+
from dataclasses import asdict
|
|
617
|
+
|
|
618
|
+
finances = asdict(our_company)
|
|
619
|
+
|
|
620
|
+
# Calculate derived values
|
|
621
|
+
finances["net_worth"] = finances["money"] + finances["value"] - finances["loan"]
|
|
622
|
+
finances["available_credit"] = finances["max_loan"] - finances["loan"]
|
|
623
|
+
finances["debt_ratio"] = (
|
|
624
|
+
finances["loan"] / max(finances["value"], 1) if finances["value"] > 0 else 1.0
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
return finances
|
|
628
|
+
|
|
629
|
+
def get_company_performance(self) -> dict:
|
|
630
|
+
"""Get company performance metrics"""
|
|
631
|
+
finances = self.get_company_finances()
|
|
632
|
+
if not finances:
|
|
633
|
+
return {}
|
|
634
|
+
|
|
635
|
+
# Basic performance metrics
|
|
636
|
+
performance = {
|
|
637
|
+
"company_value": finances.get("value", 0),
|
|
638
|
+
"performance_rating": finances.get("performance", 0),
|
|
639
|
+
"money": finances.get("money", 0),
|
|
640
|
+
"loan": finances.get("loan", 0),
|
|
641
|
+
"net_worth": finances.get("net_worth", 0),
|
|
642
|
+
"age_years": 2024 - finances.get("inaugurated_year", 2024), # Approximate age
|
|
643
|
+
"is_profitable": finances.get("money", 0) > 0,
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
return performance
|
|
647
|
+
|
|
648
|
+
def get_economic_status(self) -> dict:
|
|
649
|
+
"""Get general economic information about the game"""
|
|
650
|
+
return {
|
|
651
|
+
"inflation_payment": self.game_state.economy.inflation_rates.get("payment", 1.0),
|
|
652
|
+
"inflation_construction": self.game_state.economy.inflation_rates.get(
|
|
653
|
+
"construction", 1.0
|
|
654
|
+
),
|
|
655
|
+
"interest_rate": self.game_state.economy.interest_rate,
|
|
656
|
+
"max_loan_default": self.game_state.economy.max_loan,
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
def calculate_loan_interest(self, loan_amount: Optional[int] = None) -> int:
|
|
660
|
+
"""Calculate annual loan interest for given amount (or current loan)"""
|
|
661
|
+
if loan_amount is None:
|
|
662
|
+
finances = self.get_company_finances()
|
|
663
|
+
if finances:
|
|
664
|
+
loan_amount = finances.get("loan", 0)
|
|
665
|
+
else:
|
|
666
|
+
loan_amount = 0
|
|
667
|
+
|
|
668
|
+
interest_rate = self.game_state.economy.interest_rate
|
|
669
|
+
return int(loan_amount * interest_rate / 100)
|
|
670
|
+
|
|
671
|
+
# ============================================
|
|
672
|
+
# AI/Bot Helper Methods
|
|
673
|
+
# ============================================
|
|
674
|
+
|
|
675
|
+
def find_suitable_depot_location(
|
|
676
|
+
self, near_x: int, near_y: int, search_radius: int = 10
|
|
677
|
+
) -> Optional[Tuple[int, int]]:
|
|
678
|
+
"""Find a suitable location for building a depot near given coordinates"""
|
|
679
|
+
# This would analyze the map to find flat, empty land
|
|
680
|
+
# For now, return a simple offset
|
|
681
|
+
return (near_x + 2, near_y + 2)
|
|
682
|
+
|
|
683
|
+
def find_best_route(
|
|
684
|
+
self, start: Tuple[int, int], end: Tuple[int, int]
|
|
685
|
+
) -> List[Tuple[int, int]]:
|
|
686
|
+
"""Find the best route between two points (simplified pathfinding)"""
|
|
687
|
+
# Simple straight-line pathfinding for now
|
|
688
|
+
# Real implementation would consider terrain, existing infrastructure, cost
|
|
689
|
+
path = []
|
|
690
|
+
x1, y1 = start
|
|
691
|
+
x2, y2 = end
|
|
692
|
+
|
|
693
|
+
# Simple straight line
|
|
694
|
+
steps = max(abs(x2 - x1), abs(y2 - y1))
|
|
695
|
+
if steps == 0:
|
|
696
|
+
return [start]
|
|
697
|
+
|
|
698
|
+
for i in range(steps + 1):
|
|
699
|
+
x = x1 + (x2 - x1) * i // steps
|
|
700
|
+
y = y1 + (y2 - y1) * i // steps
|
|
701
|
+
path.append((x, y))
|
|
702
|
+
|
|
703
|
+
return path
|
|
704
|
+
|
|
705
|
+
def estimate_construction_cost(
|
|
706
|
+
self, start: Tuple[int, int], end: Tuple[int, int], construction_type: str = "rail"
|
|
707
|
+
) -> int:
|
|
708
|
+
"""Estimate the cost of construction between two points"""
|
|
709
|
+
# Simplified cost estimation
|
|
710
|
+
distance = abs(end[0] - start[0]) + abs(end[1] - start[1])
|
|
711
|
+
|
|
712
|
+
cost_per_tile = {"rail": 100, "road": 80, "station": 500, "depot": 1000, "bridge": 2000}
|
|
713
|
+
|
|
714
|
+
return distance * cost_per_tile.get(construction_type, 100)
|
|
715
|
+
|
|
716
|
+
def can_afford(self, estimated_cost: int) -> bool:
|
|
717
|
+
"""Check if we can afford a construction project"""
|
|
718
|
+
finances = self.get_company_finances()
|
|
719
|
+
if not finances:
|
|
720
|
+
return False
|
|
721
|
+
|
|
722
|
+
available_money = finances["money"] + finances.get("max_loan", 500000) - finances["loan"]
|
|
723
|
+
return bool(available_money >= estimated_cost * 1.2) # 20% safety margin
|
|
724
|
+
|
|
725
|
+
def get_vehicle_statistics(self) -> Dict[str, Any]:
|
|
726
|
+
"""Get statistics about our vehicles"""
|
|
727
|
+
our_vehicles = self.get_our_vehicles()
|
|
728
|
+
|
|
729
|
+
stats = {
|
|
730
|
+
"total_vehicles": len(our_vehicles),
|
|
731
|
+
"by_type": {"train": 0, "road": 0, "ship": 0, "aircraft": 0},
|
|
732
|
+
"total_profit": 0,
|
|
733
|
+
"average_age": 0,
|
|
734
|
+
"running_costs": 0,
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
if not our_vehicles:
|
|
738
|
+
return stats
|
|
739
|
+
|
|
740
|
+
total_age = 0
|
|
741
|
+
for vehicle in our_vehicles.values():
|
|
742
|
+
vtype = getattr(vehicle, "vehicle_type", VehicleType.TRAIN)
|
|
743
|
+
# Convert VehicleType enum to string for the dictionary key
|
|
744
|
+
vtype_str = vtype.name.lower() if hasattr(vtype, "name") else str(vtype).lower()
|
|
745
|
+
by_type = stats["by_type"]
|
|
746
|
+
if isinstance(by_type, dict) and vtype_str in by_type:
|
|
747
|
+
by_type[vtype_str] = int(by_type[vtype_str]) + 1
|
|
748
|
+
|
|
749
|
+
total_profit = stats["total_profit"]
|
|
750
|
+
running_costs = stats["running_costs"]
|
|
751
|
+
if isinstance(total_profit, (int, float)):
|
|
752
|
+
stats["total_profit"] = int(total_profit) + int(
|
|
753
|
+
getattr(vehicle, "profit_last_year", 0)
|
|
754
|
+
)
|
|
755
|
+
if isinstance(running_costs, (int, float)):
|
|
756
|
+
stats["running_costs"] = int(running_costs) + int(
|
|
757
|
+
getattr(vehicle, "running_cost", 0)
|
|
758
|
+
)
|
|
759
|
+
total_age += getattr(vehicle, "age", 0)
|
|
760
|
+
|
|
761
|
+
stats["average_age"] = total_age / len(our_vehicles)
|
|
762
|
+
return stats
|
|
763
|
+
|
|
764
|
+
def auto_manage_company(self) -> Dict[str, Any]:
|
|
765
|
+
"""Perform automatic company management tasks"""
|
|
766
|
+
if not self.is_connected():
|
|
767
|
+
return {"error": "Not connected"}
|
|
768
|
+
|
|
769
|
+
actions_taken = []
|
|
770
|
+
|
|
771
|
+
# Check finances
|
|
772
|
+
finances = self.get_company_finances()
|
|
773
|
+
if finances and finances["money"] < 10000:
|
|
774
|
+
actions_taken.append("Low money warning")
|
|
775
|
+
|
|
776
|
+
# Check vehicle performance
|
|
777
|
+
vehicle_stats = self.get_vehicle_statistics()
|
|
778
|
+
if vehicle_stats["total_vehicles"] > 0:
|
|
779
|
+
avg_profit = vehicle_stats["total_profit"] / vehicle_stats["total_vehicles"]
|
|
780
|
+
if avg_profit < 0:
|
|
781
|
+
actions_taken.append("Vehicles losing money")
|
|
782
|
+
|
|
783
|
+
# Basic maintenance checks
|
|
784
|
+
our_vehicles = self.get_our_vehicles()
|
|
785
|
+
old_vehicles = [v for v in our_vehicles.values() if getattr(v, "age", 0) > 20]
|
|
786
|
+
if old_vehicles:
|
|
787
|
+
actions_taken.append(f"{len(old_vehicles)} vehicles need replacement")
|
|
788
|
+
|
|
789
|
+
return {
|
|
790
|
+
"actions_taken": actions_taken,
|
|
791
|
+
"finances": finances,
|
|
792
|
+
"vehicle_stats": vehicle_stats,
|
|
793
|
+
"recommendation": (
|
|
794
|
+
"Consider expanding rail network"
|
|
795
|
+
if finances and finances["money"] > 50000
|
|
796
|
+
else "Focus on profitability"
|
|
797
|
+
),
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
# ============================================
|
|
801
|
+
# Advanced Chat and Communication
|
|
802
|
+
# ============================================
|
|
803
|
+
|
|
804
|
+
def send_chat_to_company(self, message: str, company_id: int) -> bool:
|
|
805
|
+
"""Send a chat message to a specific company"""
|
|
806
|
+
return self.send_chat(message, destination_type=1, destination=company_id)
|
|
807
|
+
|
|
808
|
+
def send_chat_to_client(self, message: str, client_id: int) -> bool:
|
|
809
|
+
"""Send a private message to a specific client"""
|
|
810
|
+
return self.send_chat(message, destination_type=2, destination=client_id)
|
|
811
|
+
|
|
812
|
+
def broadcast_status(self) -> bool:
|
|
813
|
+
"""Broadcast our current status to all players"""
|
|
814
|
+
info = self.get_game_info()
|
|
815
|
+
company = self.get_our_company()
|
|
816
|
+
finances = self.get_company_finances()
|
|
817
|
+
|
|
818
|
+
if company and finances:
|
|
819
|
+
status_msg = (
|
|
820
|
+
f"Bot Status: {info['vehicles']} vehicles, "
|
|
821
|
+
f"£{finances['money']:,} money, "
|
|
822
|
+
f"Frame {info['frame']}"
|
|
823
|
+
)
|
|
824
|
+
else:
|
|
825
|
+
status_msg = f"Bot Status: Spectating, Frame {info['frame']}"
|
|
826
|
+
|
|
827
|
+
return self.send_chat(status_msg)
|
|
828
|
+
|
|
829
|
+
def respond_to_chat(self, sender: str, message: str) -> bool:
|
|
830
|
+
"""Respond intelligently to chat messages directed at us"""
|
|
831
|
+
message_lower = message.lower()
|
|
832
|
+
|
|
833
|
+
if "status" in message_lower or "info" in message_lower:
|
|
834
|
+
return self.broadcast_status()
|
|
835
|
+
elif "help" in message_lower:
|
|
836
|
+
help_msg = "Bot Commands: 'status', 'help', 'finances', 'vehicles'"
|
|
837
|
+
return self.send_chat(help_msg)
|
|
838
|
+
elif "finances" in message_lower:
|
|
839
|
+
finances = self.get_company_finances()
|
|
840
|
+
if finances:
|
|
841
|
+
msg = f"Finances: £{finances['money']:,} cash, £{finances['loan']:,} loan"
|
|
842
|
+
return self.send_chat(msg)
|
|
843
|
+
elif "vehicles" in message_lower:
|
|
844
|
+
stats = self.get_vehicle_statistics()
|
|
845
|
+
msg = f"Vehicles: {stats['total_vehicles']} total, Profit: £{stats['total_profit']:,}"
|
|
846
|
+
return self.send_chat(msg)
|
|
847
|
+
|
|
848
|
+
return False
|
|
849
|
+
|
|
850
|
+
def _network_loop(self) -> None:
|
|
851
|
+
"""Main network processing loop (runs in separate thread)"""
|
|
852
|
+
logger.debug("Starting network loop")
|
|
853
|
+
|
|
854
|
+
try:
|
|
855
|
+
while self._running and self.connection.is_connected():
|
|
856
|
+
try:
|
|
857
|
+
packet = self.connection.receive_packet()
|
|
858
|
+
if packet:
|
|
859
|
+
self._handle_packet(packet)
|
|
860
|
+
except Exception as e:
|
|
861
|
+
logger.error(f"Error in network loop: {e}")
|
|
862
|
+
break
|
|
863
|
+
except Exception as e:
|
|
864
|
+
logger.error(f"Network loop error: {e}")
|
|
865
|
+
finally:
|
|
866
|
+
self.status = ClientStatus.ERROR
|
|
867
|
+
self._running = False
|
|
868
|
+
logger.debug("Network loop ended")
|
|
869
|
+
|
|
870
|
+
def _handle_packet(self, packet: Packet) -> None:
|
|
871
|
+
"""Handle received packet based on type"""
|
|
872
|
+
try:
|
|
873
|
+
if packet.type is None:
|
|
874
|
+
logger.error("Received packet with no type")
|
|
875
|
+
return
|
|
876
|
+
handler_name = f"_handle_{packet.type.name.lower()}"
|
|
877
|
+
if hasattr(self, handler_name):
|
|
878
|
+
getattr(self, handler_name)(packet)
|
|
879
|
+
else:
|
|
880
|
+
# Log packet data for unhandled packets
|
|
881
|
+
packet_data = packet.remaining_bytes()
|
|
882
|
+
logger.debug(
|
|
883
|
+
f"No handler for packet type: {packet.type} (size: {len(packet_data)} bytes)"
|
|
884
|
+
)
|
|
885
|
+
except Exception as e:
|
|
886
|
+
packet_type_str = packet.type.name if packet.type else "unknown"
|
|
887
|
+
logger.error(f"Error handling packet {packet_type_str}: {e}")
|
|
888
|
+
|
|
889
|
+
def _send_join(self) -> None:
|
|
890
|
+
"""Send join packet to server"""
|
|
891
|
+
packet = Packet(PacketType.CLIENT_JOIN)
|
|
892
|
+
packet.write_string(self.client_revision)
|
|
893
|
+
packet.write_uint32(503868772) # newgrf_version (matches official client)
|
|
894
|
+
packet.write_string(self.player_name)
|
|
895
|
+
# Join with COMPANY_NEW_COMPANY to request automatic company creation
|
|
896
|
+
company_id_to_join = int(CompanyID.COMPANY_NEW_COMPANY)
|
|
897
|
+
packet.write_uint8(company_id_to_join) # Company to join
|
|
898
|
+
logger.debug(
|
|
899
|
+
f"CLIENT_JOIN: Requesting to join company_id={company_id_to_join} (COMPANY_NEW_COMPANY)"
|
|
900
|
+
)
|
|
901
|
+
packet.write_uint8(0) # Language field (always 0 in OpenTTD 14.1)
|
|
902
|
+
|
|
903
|
+
self.connection.send_packet(packet)
|
|
904
|
+
logger.debug("Sent CLIENT_JOIN packet")
|
|
905
|
+
|
|
906
|
+
def _handle_server_full(self, packet: Packet) -> None:
|
|
907
|
+
"""Handle server full packet"""
|
|
908
|
+
logger.error("Server is full")
|
|
909
|
+
self.status = ClientStatus.ERROR
|
|
910
|
+
self._emit_event("error", "Server is full")
|
|
911
|
+
|
|
912
|
+
def _handle_server_banned(self, packet: Packet) -> None:
|
|
913
|
+
"""Handle server banned packet"""
|
|
914
|
+
logger.error("Banned from server")
|
|
915
|
+
self.status = ClientStatus.ERROR
|
|
916
|
+
self._emit_event("error", "Banned from server")
|
|
917
|
+
|
|
918
|
+
def _handle_server_error(self, packet: Packet) -> None:
|
|
919
|
+
"""Handle server error packet"""
|
|
920
|
+
error_code = packet.read_uint8()
|
|
921
|
+
error_msg = f"Server error: {NetworkError(error_code).name}"
|
|
922
|
+
logger.error(error_msg)
|
|
923
|
+
self.status = ClientStatus.ERROR
|
|
924
|
+
self._emit_event("error", error_msg)
|
|
925
|
+
|
|
926
|
+
def _handle_server_shutdown(self, packet: Packet) -> None:
|
|
927
|
+
"""Handle server shutdown notification"""
|
|
928
|
+
logger.info("Server is shutting down")
|
|
929
|
+
self.status = ClientStatus.ERROR
|
|
930
|
+
self._emit_event("error", "Server shutdown")
|
|
931
|
+
|
|
932
|
+
def _handle_server_need_game_password(self, packet: Packet) -> None:
|
|
933
|
+
"""Handle game password request"""
|
|
934
|
+
logger.debug("Server requires game password")
|
|
935
|
+
self.status = ClientStatus.AUTHENTICATING
|
|
936
|
+
|
|
937
|
+
packet = Packet(PacketType.CLIENT_GAME_PASSWORD)
|
|
938
|
+
packet.write_uint8(0) # Password type
|
|
939
|
+
packet.write_string(self.password)
|
|
940
|
+
self.connection.send_packet(packet)
|
|
941
|
+
|
|
942
|
+
def _handle_server_need_company_password(self, packet: Packet) -> None:
|
|
943
|
+
"""Handle company password request"""
|
|
944
|
+
logger.debug("Server requires company password")
|
|
945
|
+
|
|
946
|
+
# Read generation seed and network ID (for password hashing)
|
|
947
|
+
generation_seed = packet.read_uint32()
|
|
948
|
+
network_id = packet.read_string()
|
|
949
|
+
|
|
950
|
+
packet = Packet(PacketType.CLIENT_COMPANY_PASSWORD)
|
|
951
|
+
packet.write_uint8(1) # Password type (company)
|
|
952
|
+
packet.write_string(self.company_password)
|
|
953
|
+
self.connection.send_packet(packet)
|
|
954
|
+
|
|
955
|
+
def _handle_server_welcome(self, packet: Packet) -> None:
|
|
956
|
+
"""Handle welcome packet - we're authenticated!"""
|
|
957
|
+
self.game_state.client_id = packet.read_uint32()
|
|
958
|
+
generation_seed = packet.read_uint32()
|
|
959
|
+
network_id = packet.read_string()
|
|
960
|
+
|
|
961
|
+
logger.info(f"Welcomed to server! Client ID: {self.game_state.client_id}")
|
|
962
|
+
self.status = ClientStatus.JOINED
|
|
963
|
+
|
|
964
|
+
# Request map data
|
|
965
|
+
packet = Packet(PacketType.CLIENT_GETMAP)
|
|
966
|
+
packet.write_uint32(0) # NewGRF version
|
|
967
|
+
self.connection.send_packet(packet)
|
|
968
|
+
|
|
969
|
+
def _handle_server_client_info(self, packet: Packet) -> None:
|
|
970
|
+
"""Handle client info packet"""
|
|
971
|
+
client_id = packet.read_uint32()
|
|
972
|
+
company_id = CompanyID(packet.read_uint8())
|
|
973
|
+
client_name = packet.read_string()
|
|
974
|
+
|
|
975
|
+
client_info = ClientInfo(client_id=client_id, company_id=company_id, name=client_name)
|
|
976
|
+
self.game_state.add_client(client_info)
|
|
977
|
+
|
|
978
|
+
logger.debug(f"Client info: {client_name} (ID: {client_id}, Company: {company_id})")
|
|
979
|
+
|
|
980
|
+
def _handle_server_wait(self, packet: Packet) -> None:
|
|
981
|
+
"""Handle wait packet - other clients downloading map"""
|
|
982
|
+
clients_ahead = packet.read_uint8()
|
|
983
|
+
logger.info(f"Waiting for map download ({clients_ahead} clients ahead)")
|
|
984
|
+
|
|
985
|
+
def _handle_server_map_begin(self, packet: Packet) -> None:
|
|
986
|
+
"""Handle map download begin"""
|
|
987
|
+
current_frame = packet.read_uint32()
|
|
988
|
+
logger.info("Starting map download")
|
|
989
|
+
self.status = ClientStatus.DOWNLOADING_MAP
|
|
990
|
+
self._map_buffer.clear()
|
|
991
|
+
|
|
992
|
+
def _handle_server_map_size(self, packet: Packet) -> None:
|
|
993
|
+
"""Handle map size packet"""
|
|
994
|
+
self._expected_map_size = packet.read_uint32()
|
|
995
|
+
logger.info(f"Map size: {self._expected_map_size} bytes")
|
|
996
|
+
|
|
997
|
+
def _handle_server_map_data(self, packet: Packet) -> None:
|
|
998
|
+
"""Handle map data packet"""
|
|
999
|
+
data = packet.remaining_bytes()
|
|
1000
|
+
self._map_buffer.extend(data)
|
|
1001
|
+
|
|
1002
|
+
if self._expected_map_size > 0:
|
|
1003
|
+
progress = len(self._map_buffer) / self._expected_map_size * 100
|
|
1004
|
+
logger.debug(f"Map download progress: {progress:.1f}%")
|
|
1005
|
+
else:
|
|
1006
|
+
logger.debug(f"Map download: {len(self._map_buffer)} bytes received")
|
|
1007
|
+
|
|
1008
|
+
def _handle_server_map_done(self, packet: Packet) -> None:
|
|
1009
|
+
"""Handle map download complete"""
|
|
1010
|
+
logger.info("Map download complete")
|
|
1011
|
+
|
|
1012
|
+
# Store compressed map data
|
|
1013
|
+
self.game_state.set_map_data(bytes(self._map_buffer))
|
|
1014
|
+
|
|
1015
|
+
# Send map acknowledgment
|
|
1016
|
+
packet = Packet(PacketType.CLIENT_MAP_OK)
|
|
1017
|
+
self.connection.send_packet(packet)
|
|
1018
|
+
|
|
1019
|
+
self._emit_event("map_complete")
|
|
1020
|
+
|
|
1021
|
+
def _handle_server_join(self, packet: Packet) -> None:
|
|
1022
|
+
"""Handle successful join - we're now active!"""
|
|
1023
|
+
joining_client_id = packet.read_uint32()
|
|
1024
|
+
|
|
1025
|
+
if joining_client_id == self.game_state.client_id:
|
|
1026
|
+
logger.info("Successfully joined game!")
|
|
1027
|
+
self.status = ClientStatus.ACTIVE
|
|
1028
|
+
|
|
1029
|
+
# If we joined with COMPANY_NEW_COMPANY, automatically send company creation command
|
|
1030
|
+
# This matches OpenTTD's network_client.cpp line 901 behavior
|
|
1031
|
+
if self.game_state.company_id == CompanyID.COMPANY_NEW_COMPANY:
|
|
1032
|
+
logger.info(
|
|
1033
|
+
f"Sending automatic CMD_COMPANY_CTRL for company creation (current company_id: {self.game_state.company_id})"
|
|
1034
|
+
)
|
|
1035
|
+
command = CommandBuilder.create_company()
|
|
1036
|
+
self.send_command(command)
|
|
1037
|
+
logger.info("CMD_COMPANY_CTRL sent, waiting for server response...")
|
|
1038
|
+
|
|
1039
|
+
self._emit_event("game_joined")
|
|
1040
|
+
|
|
1041
|
+
def _handle_server_frame(self, packet: Packet) -> None:
|
|
1042
|
+
"""Handle frame synchronization packet"""
|
|
1043
|
+
try:
|
|
1044
|
+
frame = packet.read_uint32()
|
|
1045
|
+
frame_max = packet.read_uint32()
|
|
1046
|
+
|
|
1047
|
+
# Optional random seeds for desync detection and token
|
|
1048
|
+
seed1 = seed2 = 0
|
|
1049
|
+
token = None
|
|
1050
|
+
|
|
1051
|
+
# The remaining data could be: [seed1, [seed2,]] [token]
|
|
1052
|
+
# We need to try different combinations
|
|
1053
|
+
remaining_bytes = packet.size() - packet.buffer.tell()
|
|
1054
|
+
logger.debug(f"SERVER_FRAME has {remaining_bytes} remaining bytes after frame data")
|
|
1055
|
+
|
|
1056
|
+
if remaining_bytes >= 4:
|
|
1057
|
+
seed1 = packet.read_uint32()
|
|
1058
|
+
remaining_bytes -= 4
|
|
1059
|
+
logger.debug(f"Read seed1={seed1}, {remaining_bytes} bytes remaining")
|
|
1060
|
+
|
|
1061
|
+
if remaining_bytes >= 4:
|
|
1062
|
+
seed2 = packet.read_uint32()
|
|
1063
|
+
remaining_bytes -= 4
|
|
1064
|
+
logger.debug(f"Read seed2={seed2}, {remaining_bytes} bytes remaining")
|
|
1065
|
+
|
|
1066
|
+
if remaining_bytes >= 1:
|
|
1067
|
+
token = packet.read_uint8()
|
|
1068
|
+
logger.info(f"Received token {token} in SERVER_FRAME")
|
|
1069
|
+
self._token = token
|
|
1070
|
+
elif remaining_bytes >= 1:
|
|
1071
|
+
# Could be just a token without seeds
|
|
1072
|
+
token = packet.read_uint8()
|
|
1073
|
+
logger.info(f"Received token {token} in SERVER_FRAME (no seeds)")
|
|
1074
|
+
self._token = token
|
|
1075
|
+
|
|
1076
|
+
self.game_state.update_frame(frame, frame_max, seed1, seed2)
|
|
1077
|
+
|
|
1078
|
+
# Send acknowledgment (only if frame has advanced and we're fully active)
|
|
1079
|
+
# Real OpenTTD clients send ACKs much less frequently - roughly every 75 frames or 2 seconds
|
|
1080
|
+
if frame > self._last_ack_frame and self.status == ClientStatus.ACTIVE:
|
|
1081
|
+
current_time = time.time()
|
|
1082
|
+
# Match real client behavior: ACK every ~2 seconds, not every frame
|
|
1083
|
+
if current_time - self._last_ack_time > 2.0 or frame - self._last_ack_frame >= 75:
|
|
1084
|
+
self._last_ack_frame = frame
|
|
1085
|
+
self._last_ack_time = current_time
|
|
1086
|
+
self._send_ack()
|
|
1087
|
+
except EOFError as e:
|
|
1088
|
+
logger.error(f"Frame packet too short: {e}")
|
|
1089
|
+
raise
|
|
1090
|
+
|
|
1091
|
+
def _handle_server_sync(self, packet: Packet) -> None:
|
|
1092
|
+
"""Handle sync check packet"""
|
|
1093
|
+
try:
|
|
1094
|
+
frame = packet.read_uint32()
|
|
1095
|
+
seed1 = packet.read_uint32()
|
|
1096
|
+
seed2 = 0
|
|
1097
|
+
try:
|
|
1098
|
+
seed2 = packet.read_uint32()
|
|
1099
|
+
except EOFError:
|
|
1100
|
+
pass # No seed2 in packet
|
|
1101
|
+
|
|
1102
|
+
# Accept server's sync seeds without validation since we don't simulate game state
|
|
1103
|
+
# Real desync detection would require maintaining full game simulation state
|
|
1104
|
+
logger.debug(f"Sync check at frame {frame}, seeds: {seed1}, {seed2}")
|
|
1105
|
+
|
|
1106
|
+
# Update seeds after desync check
|
|
1107
|
+
self.game_state.random_seed1 = seed1
|
|
1108
|
+
self.game_state.random_seed2 = seed2
|
|
1109
|
+
|
|
1110
|
+
# Don't send ACK for sync packets - only SERVER_FRAME packets should trigger ACKs
|
|
1111
|
+
# The server expects ACKs only in response to SERVER_FRAME packets with tokens
|
|
1112
|
+
except EOFError as e:
|
|
1113
|
+
logger.error(f"Sync packet too short: {e}")
|
|
1114
|
+
# Don't re-raise - continue processing
|
|
1115
|
+
|
|
1116
|
+
def _handle_server_command(self, packet: Packet) -> None:
|
|
1117
|
+
"""Handle command execution packet"""
|
|
1118
|
+
company = packet.read_uint8()
|
|
1119
|
+
command_id_raw = packet.read_uint32()
|
|
1120
|
+
try:
|
|
1121
|
+
command_id: Union[Commands, int] = Commands(command_id_raw)
|
|
1122
|
+
except ValueError:
|
|
1123
|
+
logger.debug(f"Unknown command ID {command_id_raw}, continuing...")
|
|
1124
|
+
command_id = command_id_raw
|
|
1125
|
+
# Command parameters would be decoded here based on command type
|
|
1126
|
+
callback_id = packet.read_uint8()
|
|
1127
|
+
frame = packet.read_uint32()
|
|
1128
|
+
|
|
1129
|
+
logger.debug(f"Received command: {command_id} for company {company} at frame {frame}")
|
|
1130
|
+
|
|
1131
|
+
def _handle_server_chat(self, packet: Packet) -> None:
|
|
1132
|
+
"""Handle chat message"""
|
|
1133
|
+
action = packet.read_uint8()
|
|
1134
|
+
client_id = packet.read_uint32()
|
|
1135
|
+
message = packet.read_string()
|
|
1136
|
+
data = packet.read_uint64()
|
|
1137
|
+
|
|
1138
|
+
client = self.game_state.get_client(client_id)
|
|
1139
|
+
sender_name = client.name if client else f"Client {client_id}"
|
|
1140
|
+
|
|
1141
|
+
logger.info(f"Chat [{sender_name}]: {message}")
|
|
1142
|
+
self._emit_event("chat_message", sender_name, message, data)
|
|
1143
|
+
|
|
1144
|
+
def _handle_server_quit(self, packet: Packet) -> None:
|
|
1145
|
+
"""Handle client quit notification"""
|
|
1146
|
+
client_id = packet.read_uint32()
|
|
1147
|
+
self.game_state.remove_client(client_id)
|
|
1148
|
+
|
|
1149
|
+
logger.debug(f"Client {client_id} left the game")
|
|
1150
|
+
|
|
1151
|
+
def _handle_server_company_update(self, packet: Packet) -> None:
|
|
1152
|
+
"""Handle company update packet - contains company password flags only"""
|
|
1153
|
+
try:
|
|
1154
|
+
logger.debug(f"📊 Received COMPANY_UPDATE packet (size: {packet.size()} bytes)")
|
|
1155
|
+
|
|
1156
|
+
# Parse the actual COMPANY_UPDATE format from OpenTTD source:
|
|
1157
|
+
# uint16 company_passworded (bitfield of which companies have passwords)
|
|
1158
|
+
company_passworded = packet.read_uint16()
|
|
1159
|
+
|
|
1160
|
+
logger.debug(f"📊 Company password flags: 0x{company_passworded:04x}")
|
|
1161
|
+
|
|
1162
|
+
# Note: This packet doesn't contain financial data or company details
|
|
1163
|
+
# That information comes from the map data or command responses
|
|
1164
|
+
|
|
1165
|
+
except Exception as e:
|
|
1166
|
+
logger.debug(f"Error in company update handler: {e}")
|
|
1167
|
+
|
|
1168
|
+
def _handle_server_config_update(self, packet: Packet) -> None:
|
|
1169
|
+
"""Handle config update packet - contains max_companies and server_name only"""
|
|
1170
|
+
try:
|
|
1171
|
+
logger.debug(f"⚙️ Received CONFIG_UPDATE packet (size: {packet.size()} bytes)")
|
|
1172
|
+
|
|
1173
|
+
# Parse the actual CONFIG_UPDATE format from OpenTTD source:
|
|
1174
|
+
# uint8 max_companies
|
|
1175
|
+
# string server_name
|
|
1176
|
+
max_companies = packet.read_uint8()
|
|
1177
|
+
server_name = packet.read_string()
|
|
1178
|
+
|
|
1179
|
+
logger.info(
|
|
1180
|
+
f"⚙️ Server config: max_companies={max_companies}, server_name='{server_name}'"
|
|
1181
|
+
)
|
|
1182
|
+
|
|
1183
|
+
# Update our game state
|
|
1184
|
+
if hasattr(self.game_state, "max_companies"):
|
|
1185
|
+
self.game_state.max_companies = max_companies
|
|
1186
|
+
if hasattr(self.game_state, "server_name"):
|
|
1187
|
+
self.game_state.server_name = server_name
|
|
1188
|
+
|
|
1189
|
+
except Exception as e:
|
|
1190
|
+
logger.debug(f"Error reading config update: {e}")
|
|
1191
|
+
|
|
1192
|
+
def _handle_server_game_info(self, packet: Packet) -> None:
|
|
1193
|
+
"""Handle SERVER_GAME_INFO packet - contains real-time game state data"""
|
|
1194
|
+
try:
|
|
1195
|
+
logger.debug(f"Received SERVER_GAME_INFO packet (size: {packet.size()} bytes)")
|
|
1196
|
+
|
|
1197
|
+
# Parse SERVER_GAME_INFO packet format based on OpenTTD 14.1 source
|
|
1198
|
+
# SerializeNetworkGameInfo in network_game_info.cpp lines 187-254
|
|
1199
|
+
|
|
1200
|
+
game_info_version = packet.read_uint8() # NETWORK_GAME_INFO_VERSION
|
|
1201
|
+
logger.debug(f"Game info version: {game_info_version}")
|
|
1202
|
+
|
|
1203
|
+
# Parse based on version - OpenTTD 14.1 uses version 7
|
|
1204
|
+
if game_info_version >= 7:
|
|
1205
|
+
# NETWORK_GAME_INFO_VERSION = 7
|
|
1206
|
+
ticks_playing = packet.read_uint64()
|
|
1207
|
+
logger.debug(f"Ticks playing: {ticks_playing}")
|
|
1208
|
+
else:
|
|
1209
|
+
ticks_playing = 0
|
|
1210
|
+
|
|
1211
|
+
if game_info_version >= 6:
|
|
1212
|
+
# NETWORK_GAME_INFO_VERSION = 6
|
|
1213
|
+
newgrf_serialisation = packet.read_uint8() # NST_GRFID_MD5 or NST_GRFID_MD5_NAME
|
|
1214
|
+
logger.debug(f"NewGRF serialization type: {newgrf_serialisation}")
|
|
1215
|
+
else:
|
|
1216
|
+
newgrf_serialisation = 0
|
|
1217
|
+
|
|
1218
|
+
if game_info_version >= 5:
|
|
1219
|
+
# NETWORK_GAME_INFO_VERSION = 5
|
|
1220
|
+
gamescript_version = packet.read_uint32()
|
|
1221
|
+
gamescript_name = packet.read_string()
|
|
1222
|
+
logger.debug(f"GameScript: {gamescript_name} v{gamescript_version}")
|
|
1223
|
+
|
|
1224
|
+
if game_info_version >= 4:
|
|
1225
|
+
# NETWORK_GAME_INFO_VERSION = 4 - NewGRF data
|
|
1226
|
+
num_grfs = packet.read_uint8()
|
|
1227
|
+
logger.debug(f"Number of GRFs: {num_grfs}")
|
|
1228
|
+
|
|
1229
|
+
# Skip GRF data for now - we just need the game state
|
|
1230
|
+
for i in range(num_grfs):
|
|
1231
|
+
# Skip GRF ID (uint32) and MD5 (16 bytes)
|
|
1232
|
+
packet.read_uint32() # GRF ID
|
|
1233
|
+
for j in range(16): # MD5 hash
|
|
1234
|
+
packet.read_uint8()
|
|
1235
|
+
# Skip name if present
|
|
1236
|
+
if game_info_version >= 6 and newgrf_serialisation == 1: # NST_GRFID_MD5_NAME
|
|
1237
|
+
packet.read_string() # GRF name
|
|
1238
|
+
|
|
1239
|
+
if game_info_version >= 3:
|
|
1240
|
+
# NETWORK_GAME_INFO_VERSION = 3 - KEY DATA WE WANT!
|
|
1241
|
+
calendar_date = packet.read_uint32()
|
|
1242
|
+
calendar_start = packet.read_uint32()
|
|
1243
|
+
|
|
1244
|
+
# Convert to readable date format (days since 0 AD)
|
|
1245
|
+
# OpenTTD date 0 = 1 Jan 0 AD, but display starts from year 1
|
|
1246
|
+
current_year = 1 + (calendar_date // 365)
|
|
1247
|
+
start_year = 1 + (calendar_start // 365)
|
|
1248
|
+
|
|
1249
|
+
logger.info(
|
|
1250
|
+
f"REAL GAME DATE: Current year {current_year}, Started year {start_year}"
|
|
1251
|
+
)
|
|
1252
|
+
|
|
1253
|
+
else:
|
|
1254
|
+
calendar_date = 0
|
|
1255
|
+
calendar_start = 0
|
|
1256
|
+
current_year = 1950 # Fallback
|
|
1257
|
+
start_year = 1950
|
|
1258
|
+
|
|
1259
|
+
if game_info_version >= 2:
|
|
1260
|
+
# NETWORK_GAME_INFO_VERSION = 2 - COMPANY DATA WE WANT!
|
|
1261
|
+
companies_max = packet.read_uint8()
|
|
1262
|
+
companies_on = packet.read_uint8() # This is the REAL company count!
|
|
1263
|
+
packet.read_uint8() # Skip old max-spectators field
|
|
1264
|
+
|
|
1265
|
+
logger.info(f"REAL COMPANY DATA: {companies_on}/{companies_max} companies active")
|
|
1266
|
+
|
|
1267
|
+
else:
|
|
1268
|
+
companies_max = 15
|
|
1269
|
+
companies_on = 0
|
|
1270
|
+
|
|
1271
|
+
# NETWORK_GAME_INFO_VERSION = 1 - Basic server info
|
|
1272
|
+
server_name = packet.read_string()
|
|
1273
|
+
server_revision = packet.read_string()
|
|
1274
|
+
use_password = packet.read_bool()
|
|
1275
|
+
clients_max = packet.read_uint8()
|
|
1276
|
+
clients_on = packet.read_uint8() # This is the REAL client count!
|
|
1277
|
+
spectators_on = packet.read_uint8()
|
|
1278
|
+
map_width = packet.read_uint16()
|
|
1279
|
+
map_height = packet.read_uint16()
|
|
1280
|
+
landscape = packet.read_uint8()
|
|
1281
|
+
dedicated = packet.read_bool()
|
|
1282
|
+
|
|
1283
|
+
# Update our game state with the REAL data
|
|
1284
|
+
self.game_state.frame = ticks_playing # Use ticks as frame count
|
|
1285
|
+
|
|
1286
|
+
# Store the real data for get_game_info()
|
|
1287
|
+
self._real_game_data = {
|
|
1288
|
+
"current_year": current_year,
|
|
1289
|
+
"start_year": start_year,
|
|
1290
|
+
"companies_on": companies_on,
|
|
1291
|
+
"companies_max": companies_max,
|
|
1292
|
+
"clients_on": clients_on,
|
|
1293
|
+
"clients_max": clients_max,
|
|
1294
|
+
"spectators_on": spectators_on,
|
|
1295
|
+
"map_width": map_width,
|
|
1296
|
+
"map_height": map_height,
|
|
1297
|
+
"server_name": server_name,
|
|
1298
|
+
"ticks_playing": ticks_playing,
|
|
1299
|
+
"calendar_date": calendar_date,
|
|
1300
|
+
"calendar_start": calendar_start,
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
logger.info(
|
|
1304
|
+
f"UPDATED GAME STATE - Year: {current_year}, Companies: {companies_on}/{companies_max}, Clients: {clients_on}/{clients_max}"
|
|
1305
|
+
)
|
|
1306
|
+
|
|
1307
|
+
except Exception as e:
|
|
1308
|
+
logger.error(f"Error parsing SERVER_GAME_INFO: {e}")
|
|
1309
|
+
# Log raw packet data for debugging
|
|
1310
|
+
remaining_data = packet.remaining_bytes()
|
|
1311
|
+
logger.error(f"Raw packet data: {remaining_data.hex()}")
|
|
1312
|
+
|
|
1313
|
+
def _handle_server_move(self, packet: Packet) -> None:
|
|
1314
|
+
"""Handle server move packet - client has been moved to a different company"""
|
|
1315
|
+
try:
|
|
1316
|
+
client_id = packet.read_uint8()
|
|
1317
|
+
company_id = packet.read_uint8()
|
|
1318
|
+
|
|
1319
|
+
logger.info(f"Client {client_id} moved to company {company_id}")
|
|
1320
|
+
|
|
1321
|
+
# If this is us being moved to a new company
|
|
1322
|
+
if client_id == self.game_state.client_id:
|
|
1323
|
+
# Update our company state
|
|
1324
|
+
old_company_id = self.game_state.company_id
|
|
1325
|
+
self.game_state.company_id = CompanyID(company_id)
|
|
1326
|
+
logger.info(f"Company ID changed: {old_company_id} -> {company_id}")
|
|
1327
|
+
|
|
1328
|
+
# If we were creating a company and got assigned to one
|
|
1329
|
+
if company_id != CompanyID.COMPANY_SPECTATOR and self.pending_company_name:
|
|
1330
|
+
logger.info(f"Successfully created and joined company {company_id}")
|
|
1331
|
+
|
|
1332
|
+
# Try to set the company name (this might require a separate command)
|
|
1333
|
+
# For now, just clear the pending name
|
|
1334
|
+
self.pending_company_name = None
|
|
1335
|
+
|
|
1336
|
+
self._emit_event("company_created", company_id)
|
|
1337
|
+
elif company_id == CompanyID.COMPANY_SPECTATOR:
|
|
1338
|
+
logger.info("Moved to spectator mode")
|
|
1339
|
+
else:
|
|
1340
|
+
logger.info(f"Joined existing company {company_id}")
|
|
1341
|
+
|
|
1342
|
+
except Exception as e:
|
|
1343
|
+
logger.error(f"Error handling server move: {e}")
|
|
1344
|
+
|
|
1345
|
+
def _send_ack(self) -> None:
|
|
1346
|
+
"""Send frame acknowledgment to server"""
|
|
1347
|
+
try:
|
|
1348
|
+
packet = Packet(PacketType.CLIENT_ACK)
|
|
1349
|
+
packet.write_uint32(self.game_state.frame)
|
|
1350
|
+
# The server always expects the token to be present
|
|
1351
|
+
packet.write_uint8(self._token)
|
|
1352
|
+
|
|
1353
|
+
logger.info(f"Sending ACK for frame {self.game_state.frame} with token {self._token}")
|
|
1354
|
+
self.connection.send_packet(packet)
|
|
1355
|
+
except Exception as e:
|
|
1356
|
+
logger.error(f"Failed to send ACK: {e}")
|