forked from ArchipelagoMW/Archipelago
- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAdventureClient.py
More file actions
Latest commit
520 lines (455 loc) · 23 KB
/
Copy pathAdventureClient.py
File metadata and controls
520 lines (455 loc) · 23 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
importasyncio
importhashlib
importjson
importtime
importos
importbsdiff4
importsubprocess
importzipfile
fromasyncioimportStreamReader, StreamWriter, CancelledError
fromtypingimportList
importUtils
fromsettingsimportget_settings
fromNetUtilsimportClientStatus
fromUtilsimportasync_start
fromCommonClientimportCommonContext, server_loop, gui_enabled, ClientCommandProcessor, logger, \
get_base_parser
fromworlds.adventureimportAdventureDeltaPatch
fromworlds.adventure.Locationsimportbase_location_id
fromworlds.adventure.RomimportAdventureForeignItemInfo, AdventureAutoCollectLocation, BatNoTouchLocation
fromworlds.adventure.Itemsimportbase_adventure_item_id, standard_item_max, item_table
fromworlds.adventure.Offsetsimportstatic_item_element_size, connector_port_offset
SYSTEM_MESSAGE_ID=0
CONNECTION_TIMING_OUT_STATUS= \
"Connection timing out. Please restart your emulator, then restart connector_adventure.lua"
CONNECTION_REFUSED_STATUS= \
"Connection Refused. Please start your emulator and make sure connector_adventure.lua is running"
CONNECTION_RESET_STATUS= \
"Connection was reset. Please restart your emulator, then restart connector_adventure.lua"
CONNECTION_TENTATIVE_STATUS="Initial Connection Made"
CONNECTION_CONNECTED_STATUS="Connected"
CONNECTION_INITIAL_STATUS="Connection has not been initiated"
SCRIPT_VERSION=1
classAdventureCommandProcessor(ClientCommandProcessor):
def__init__(self, ctx: CommonContext):
super().__init__(ctx)
def_cmd_2600(self):
"""Check 2600 Connection State"""
ifisinstance(self.ctx, AdventureContext):
logger.info(f"2600 Status: {self.ctx.atari_status}")
def_cmd_aconnect(self):
"""Discard current atari 2600 connection state"""
ifisinstance(self.ctx, AdventureContext):
self.ctx.atari_sync_task.cancel()
classAdventureContext(CommonContext):
command_processor=AdventureCommandProcessor
game='Adventure'
lua_connector_port: int=17242
def__init__(self, server_address, password):
super().__init__(server_address, password)
self.freeincarnates_used: int=-1
self.freeincarnate_pending: int=0
self.foreign_items: [AdventureForeignItemInfo] = []
self.autocollect_items: [AdventureAutoCollectLocation] = []
self.atari_streams: (StreamReader, StreamWriter) =None
self.atari_sync_task=None
self.messages= {}
self.locations_array=None
self.atari_status=CONNECTION_INITIAL_STATUS
self.awaiting_rom=False
self.display_msgs=True
self.deathlink_pending=False
self.set_deathlink=False
self.client_compatibility_mode=0
self.items_handling=0b111
self.checked_locations_sent: bool=False
self.port_offset=0
self.bat_no_touch_locations: [BatNoTouchLocation] = []
self.local_item_locations= {}
self.dragon_speed_info= {}
options=get_settings().adventure_options
self.display_msgs=options.display_msgs
asyncdefserver_auth(self, password_requested: bool=False):
ifpassword_requestedandnotself.password:
awaitsuper(AdventureContext, self).server_auth(password_requested)
ifnotself.auth:
self.auth=self.player_name
ifnotself.auth:
self.awaiting_rom=True
logger.info('Awaiting connection to adventure_connector to get Player information')
return
awaitself.send_connect()
def_set_message(self, msg: str, msg_id: int):
ifself.display_msgs:
self.messages[(time.time(), msg_id)] =msg
defon_package(self, cmd: str, args: dict):
ifcmd=='Connected':
self.locations_array=None
ifget_settings().adventure_options.as_dict().get("death_link", False):
self.set_deathlink=True
async_start(self.get_freeincarnates_used())
elifcmd=="RoomInfo":
self.seed_name=args['seed_name']
elifcmd=='Print':
msg=args['text']
if': !'notinmsg:
self._set_message(msg, SYSTEM_MESSAGE_ID)
elifcmd=="ReceivedItems":
msg=f"Received {', '.join([self.item_names.lookup_in_game(item.item) foriteminargs['items']])}"
self._set_message(msg, SYSTEM_MESSAGE_ID)
elifcmd=="Retrieved":
iff"adventure_{self.auth}_freeincarnates_used"inargs["keys"]:
self.freeincarnates_used=args["keys"][f"adventure_{self.auth}_freeincarnates_used"]
ifself.freeincarnates_usedisNone:
self.freeincarnates_used=0
self.freeincarnates_used+=self.freeincarnate_pending
self.send_pending_freeincarnates()
elifcmd=="SetReply":
ifargs["key"] ==f"adventure_{self.auth}_freeincarnates_used":
self.freeincarnates_used=args["value"]
ifself.freeincarnates_usedisNone:
self.freeincarnates_used=0
self.freeincarnates_used+=self.freeincarnate_pending
self.send_pending_freeincarnates()
defon_deathlink(self, data: dict):
self.deathlink_pending=True
super().on_deathlink(data)
defrun_gui(self):
fromkvuiimportGameManager
classAdventureManager(GameManager):
logging_pairs= [
("Client", "Archipelago")
]
base_title="Archipelago Adventure Client"
self.ui=AdventureManager(self)
self.ui_task=asyncio.create_task(self.ui.async_run(), name="UI")
asyncdefget_freeincarnates_used(self):
ifself.serverandnotself.server.socket.closed:
awaitself.send_msgs([{"cmd": "SetNotify", "keys": [f"adventure_{self.auth}_freeincarnates_used"]}])
awaitself.send_msgs([{"cmd": "Get", "keys": [f"adventure_{self.auth}_freeincarnates_used"]}])
defsend_pending_freeincarnates(self):
ifself.freeincarnate_pending>0:
async_start(self.send_pending_freeincarnates_impl(self.freeincarnate_pending))
self.freeincarnate_pending=0
asyncdefsend_pending_freeincarnates_impl(self, send_val: int) ->None:
awaitself.send_msgs([{"cmd": "Set", "key": f"adventure_{self.auth}_freeincarnates_used",
"default": 0, "want_reply": False,
"operations": [{"operation": "add", "value": send_val}]}])
asyncdefused_freeincarnate(self) ->None:
ifself.serverandnotself.server.socket.closed:
awaitself.send_msgs([{"cmd": "Set", "key": f"adventure_{self.auth}_freeincarnates_used",
"default": 0, "want_reply": True,
"operations": [{"operation": "add", "value": 1}]}])
else:
self.freeincarnate_pending=self.freeincarnate_pending+1
defconvert_item_id(ap_item_id: int):
static_item_index=ap_item_id-base_adventure_item_id
returnstatic_item_index*static_item_element_size
defget_payload(ctx: AdventureContext):
current_time=time.time()
items= []
dragon_speed_update= {}
diff_a_locked=ctx.diff_a_mode>0
diff_b_locked=ctx.diff_b_mode>0
freeincarnate_count=0
foriteminctx.items_received:
item_id_str=str(item.item)
ifbase_adventure_item_id<item.item<=standard_item_max:
items.append(convert_item_id(item.item))
elifitem_id_strinctx.dragon_speed_info:
ifitem.itemindragon_speed_update:
last_index=len(ctx.dragon_speed_info[item_id_str]) -1
dragon_speed_update[item.item] =ctx.dragon_speed_info[item_id_str][last_index]
else:
dragon_speed_update[item.item] =ctx.dragon_speed_info[item_id_str][0]
elifitem.item==item_table["Left Difficulty Switch"].id:
diff_a_locked=False
elifitem.item==item_table["Right Difficulty Switch"].id:
diff_b_locked=False
elifitem.item==item_table["Freeincarnate"].id:
freeincarnate_count=freeincarnate_count+1
freeincarnates_available=0
ifctx.freeincarnates_used>=0:
freeincarnates_available=freeincarnate_count- (ctx.freeincarnates_used+ctx.freeincarnate_pending)
ret=json.dumps(
{
"items": items,
"messages": {f'{key[0]}:{key[1]}': valueforkey, valueinctx.messages.items()
ifkey[0] >current_time-10},
"deathlink": ctx.deathlink_pending,
"dragon_speeds": dragon_speed_update,
"difficulty_a_locked": diff_a_locked,
"difficulty_b_locked": diff_b_locked,
"freeincarnates_available": freeincarnates_available,
"bat_logic": ctx.bat_logic
}
)
ctx.deathlink_pending=False
returnret
asyncdefparse_locations(data: List, ctx: AdventureContext):
locations=data
# for loc_name, loc_data in location_table.items():
# if flags["EventFlag"][280] & 1 and not ctx.finished_game:
# await ctx.send_msgs([
# {"cmd": "StatusUpdate",
# "status": 30}
# ])
# ctx.finished_game = True
iflocations==ctx.locations_array:
return
ctx.locations_array=locations
iflocationsisnotNone:
awaitctx.send_msgs([{"cmd": "LocationChecks", "locations": locations}])
defsend_ap_foreign_items(adventure_context):
foreign_item_json_list= []
autocollect_item_json_list= []
bat_no_touch_locations_json_list= []
forfiinadventure_context.foreign_items:
foreign_item_json_list.append(fi.get_dict())
forfiinadventure_context.autocollect_items:
autocollect_item_json_list.append(fi.get_dict())
forntlinadventure_context.bat_no_touch_locations:
bat_no_touch_locations_json_list.append(ntl.get_dict())
payload=json.dumps(
{
"foreign_items": foreign_item_json_list,
"autocollect_items": autocollect_item_json_list,
"local_item_locations": adventure_context.local_item_locations,
"bat_no_touch_locations": bat_no_touch_locations_json_list
}
)
print("sending foreign items")
msg=payload.encode()
(reader, writer) =adventure_context.atari_streams
writer.write(msg)
writer.write(b'\n')
defsend_checked_locations_if_needed(adventure_context):
ifnotadventure_context.checked_locations_sentandadventure_context.checked_locationsisnotNone:
iflen(adventure_context.checked_locations) ==0:
return
checked_short_ids= []
forlocationinadventure_context.checked_locations:
checked_short_ids.append(location-base_location_id)
print("Sending checked locations")
payload=json.dumps(
{
"checked_locations": checked_short_ids,
}
)
msg=payload.encode()
(reader, writer) =adventure_context.atari_streams
writer.write(msg)
writer.write(b'\n')
adventure_context.checked_locations_sent=True
asyncdefatari_sync_task(ctx: AdventureContext):
logger.info("Starting Atari 2600 connector. Use /2600 for status information")
whilenotctx.exit_event.is_set():
try:
error_status=None
ifctx.atari_streams:
(reader, writer) =ctx.atari_streams
msg=get_payload(ctx).encode()
writer.write(msg)
writer.write(b'\n')
try:
awaitasyncio.wait_for(writer.drain(), timeout=1.5)
try:
# Data will return a dict with 1+ fields
# 1. A keepalive response of the Players Name (always)
# 2. romhash field with sha256 hash of the ROM memory region
# 3. locations, messages, and deathLink
# 4. freeincarnate, to indicate a freeincarnate was used
data=awaitasyncio.wait_for(reader.readline(), timeout=5)
data_decoded=json.loads(data.decode())
if'scriptVersion'notindata_decodedordata_decoded['scriptVersion'] !=SCRIPT_VERSION:
msg="You are connecting with an incompatible Lua script version. Ensure your connector " \
"Lua and AdventureClient are from the same Archipelago installation."
logger.info(msg, extra={'compact_gui': True})
ctx.gui_error('Error', msg)
error_status=CONNECTION_RESET_STATUS
ifctx.seed_nameandbytes(ctx.seed_name, encoding='ASCII') !=ctx.seed_name_from_data:
msg="The server is running a different multiworld than your client is. " \
"(invalid seed_name)"
logger.info(msg, extra={'compact_gui': True})
ctx.gui_error('Error', msg)
error_status=CONNECTION_RESET_STATUS
if'romhash'indata_decoded:
ifctx.rom_hash.upper() !=data_decoded['romhash'].upper():
msg="The rom hash does not match the client rom hash data"
print("got "+data_decoded['romhash'])
print("expected "+str(ctx.rom_hash))
logger.info(msg, extra={'compact_gui': True})
ctx.gui_error('Error', msg)
error_status=CONNECTION_RESET_STATUS
ifctx.authisNone:
ctx.auth=ctx.player_name
ifctx.awaiting_rom:
awaitctx.server_auth(False)
if'locations'indata_decodedandctx.gameandctx.atari_status==CONNECTION_CONNECTED_STATUS \
andnoterror_statusandctx.auth:
# Not just a keep alive ping, parse
async_start(parse_locations(data_decoded['locations'], ctx))
if'deathLink'indata_decodedanddata_decoded['deathLink'] >0and'DeathLink'inctx.tags:
dragon_name="a dragon"
ifdata_decoded['deathLink'] ==1:
dragon_name="Rhindle"
elifdata_decoded['deathLink'] ==2:
dragon_name="Yorgle"
elifdata_decoded['deathLink'] ==3:
dragon_name="Grundle"
print (ctx.auth+" has been eaten by "+dragon_name )
awaitctx.send_death(ctx.auth+" has been eaten by "+dragon_name)
# TODO - also if player reincarnates with a dragon onscreen ' dies to avoid being eaten by '
if'victory'indata_decodedandnotctx.finished_game:
awaitctx.send_msgs([{"cmd": "StatusUpdate", "status": ClientStatus.CLIENT_GOAL}])
ctx.finished_game=True
if'freeincarnate'indata_decoded:
awaitctx.used_freeincarnate()
ifctx.set_deathlink:
awaitctx.update_death_link(True)
send_checked_locations_if_needed(ctx)
exceptasyncio.TimeoutError:
logger.debug("Read Timed Out, Reconnecting")
error_status=CONNECTION_TIMING_OUT_STATUS
writer.close()
ctx.atari_streams=None
exceptConnectionResetErrorase:
logger.debug("Read failed due to Connection Lost, Reconnecting")
error_status=CONNECTION_RESET_STATUS
writer.close()
ctx.atari_streams=None
exceptTimeoutError:
logger.debug("Connection Timed Out, Reconnecting")
error_status=CONNECTION_TIMING_OUT_STATUS
writer.close()
ctx.atari_streams=None
exceptConnectionResetError:
logger.debug("Connection Lost, Reconnecting")
error_status=CONNECTION_RESET_STATUS
writer.close()
ctx.atari_streams=None
exceptCancelledError:
logger.debug("Connection Cancelled, Reconnecting")
error_status=CONNECTION_RESET_STATUS
writer.close()
ctx.atari_streams=None
pass
exceptExceptionase:
print("unknown exception "+e)
raise
ifctx.atari_status==CONNECTION_TENTATIVE_STATUS:
ifnoterror_status:
logger.info("Successfully Connected to 2600")
ctx.atari_status=CONNECTION_CONNECTED_STATUS
ctx.checked_locations_sent=False
send_ap_foreign_items(ctx)
send_checked_locations_if_needed(ctx)
else:
ctx.atari_status=f"Was tentatively connected but error occurred: {error_status}"
eliferror_status:
ctx.atari_status=error_status
logger.info("Lost connection to 2600 and attempting to reconnect. Use /2600 for status updates")
else:
try:
port=ctx.lua_connector_port+ctx.port_offset
logger.debug(f"Attempting to connect to 2600 on port {port}")
print(f"Attempting to connect to 2600 on port {port}")
ctx.atari_streams=awaitasyncio.wait_for(
asyncio.open_connection("localhost",
port),
timeout=10)
ctx.atari_status=CONNECTION_TENTATIVE_STATUS
exceptTimeoutError:
logger.debug("Connection Timed Out, Trying Again")
ctx.atari_status=CONNECTION_TIMING_OUT_STATUS
continue
exceptConnectionRefusedError:
logger.debug("Connection Refused, Trying Again")
ctx.atari_status=CONNECTION_REFUSED_STATUS
awaitasyncio.sleep(1)
continue
exceptCancelledError:
pass
exceptCancelledError:
pass
print("exiting atari sync task")
asyncdefrun_game(romfile):
options=get_settings().adventure_options
auto_start=options.rom_start
rom_args=options.rom_args
ifauto_startisTrue:
importwebbrowser
webbrowser.open(romfile)
elifos.path.isfile(auto_start):
open_args= [auto_start, romfile]
ifrom_argsisnotNone:
open_args.insert(1, rom_args)
subprocess.Popen(open_args,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
asyncdefpatch_and_run_game(patch_file, ctx):
base_name=os.path.splitext(patch_file)[0]
comp_path=base_name+'.a26'
try:
base_rom=AdventureDeltaPatch.get_source_data()
exceptExceptionasmsg:
logger.info(msg, extra={'compact_gui': True})
ctx.gui_error('Error', msg)
withopen(Utils.local_path("data", "adventure_basepatch.bsdiff4"), "rb") asfile:
basepatch=bytes(file.read())
base_patched_rom_data=bsdiff4.patch(base_rom, basepatch)
withzipfile.ZipFile(patch_file, 'r') aspatch_archive:
ifnotAdventureDeltaPatch.check_version(patch_archive):
logger.error("apadvn version doesn't match this client. Make sure your generator and client are the same")
raiseException("apadvn version doesn't match this client.")
ctx.foreign_items=AdventureDeltaPatch.read_foreign_items(patch_archive)
ctx.autocollect_items=AdventureDeltaPatch.read_autocollect_items(patch_archive)
ctx.local_item_locations=AdventureDeltaPatch.read_local_item_locations(patch_archive)
ctx.dragon_speed_info=AdventureDeltaPatch.read_dragon_speed_info(patch_archive)
ctx.seed_name_from_data, ctx.player_name=AdventureDeltaPatch.read_rom_info(patch_archive)
ctx.diff_a_mode, ctx.diff_b_mode=AdventureDeltaPatch.read_difficulty_switch_info(patch_archive)
ctx.bat_logic=AdventureDeltaPatch.read_bat_logic(patch_archive)
ctx.bat_no_touch_locations=AdventureDeltaPatch.read_bat_no_touch(patch_archive)
ctx.rom_deltas=AdventureDeltaPatch.read_rom_deltas(patch_archive)
ctx.auth=ctx.player_name
patched_rom_data=AdventureDeltaPatch.apply_rom_deltas(base_patched_rom_data, ctx.rom_deltas)
rom_hash=hashlib.sha256()
rom_hash.update(patched_rom_data)
ctx.rom_hash=rom_hash.hexdigest()
ctx.port_offset=patched_rom_data[connector_port_offset]
withopen(comp_path, "wb") aspatched_rom_file:
patched_rom_file.write(patched_rom_data)
async_start(run_game(comp_path))
if__name__=='__main__':
Utils.init_logging("AdventureClient")
asyncdefmain():
parser=get_base_parser()
parser.add_argument('patch_file', default="", type=str, nargs="?",
help='Path to an ADVNTURE.BIN rom file')
parser.add_argument('port', default=17242, type=int, nargs="?",
help='port for adventure_connector connection')
args=parser.parse_args()
ctx=AdventureContext(args.connect, args.password)
ctx.server_task=asyncio.create_task(server_loop(ctx), name="ServerLoop")
ifgui_enabled:
ctx.run_gui()
ctx.run_cli()
ctx.atari_sync_task=asyncio.create_task(atari_sync_task(ctx), name="Adventure Sync")
ifargs.patch_file:
ext=args.patch_file.split(".")[len(args.patch_file.split(".")) -1].lower()
ifext=="apadvn":
logger.info("apadvn file supplied, beginning patching process...")
async_start(patch_and_run_game(args.patch_file, ctx))
else:
logger.warning(f"Unknown patch file extension {ext}")
ifargs.portisint:
ctx.lua_connector_port=args.port
awaitctx.exit_event.wait()
ctx.server_address=None
awaitctx.shutdown()
ifctx.atari_sync_task:
awaitctx.atari_sync_task
print("finished atari_sync_task (main)")
importcolorama
colorama.just_fix_windows_console()
asyncio.run(main())
colorama.deinit()