about summary refs log tree commit diff stats
path: root/data/maps/the_great/rooms/Daedalus Entrance.txtpb
diff options
context:
space:
mode:
authorStar Rauchenberger <fefferburbia@gmail.com>2025-10-24 15:37:28 -0400
committerStar Rauchenberger <fefferburbia@gmail.com>2025-10-24 15:37:28 -0400
commit72a33fcff5150228b72f4c24e4285f8a0e52566a (patch)
treee574be64d1196b236aaeab125eb6410600649a94 /data/maps/the_great/rooms/Daedalus Entrance.txtpb
parent5322fdf9fc829566be5ec22f1f0fae0bd2d4c186 (diff)
downloadlingo2-archipelago-72a33fcff5150228b72f4c24e4285f8a0e52566a.tar.gz
lingo2-archipelago-72a33fcff5150228b72f4c24e4285f8a0e52566a.tar.bz2
lingo2-archipelago-72a33fcff5150228b72f4c24e4285f8a0e52566a.zip
Add white_ending flag to door
Diffstat (limited to 'data/maps/the_great/rooms/Daedalus Entrance.txtpb')
0 files changed, 0 insertions, 0 deletions
9-27 17:14:40 -0400 committer Star Rauchenberger <fefferburbia@gmail.com> 2025-09-27 17:14:40 -0400 Treat local letters as items for tracker' href='/lingo2-archipelago/commit/apworld/context.py?id=b0f474bee1c8e1111f7542bf4985136d9aedf340'>b0f474b ^
05827d2 ^
b0f474b ^











f3b490b ^









b0f474b ^





53e0509 ^
99191f3 ^
7544b11 ^
b0f474b ^







53e0509 ^
7544b11 ^
b0f474b ^






53e0509 ^
99191f3 ^
7544b11 ^
53e0509 ^
b0f474b ^












05827d2 ^
f3b490b ^
53e0509 ^









7544b11 ^





05827d2 ^


b0f474b ^
05827d2 ^




b0f474b ^


05827d2 ^

b0f474b ^







05827d2 ^



c7c64dc ^










05827d2 ^
b0f474b ^


05827d2 ^









b0f474b ^


05827d2 ^











b0f474b ^


05827d2 ^







b0f474b ^


05827d2 ^







b0f474b ^


05827d2 ^






b524e15 ^
b0f474b ^


b524e15 ^

b0f474b ^
b524e15 ^

53e0509 ^


99191f3 ^


b524e15 ^


b0f474b ^


b524e15 ^






b0f474b ^










f3b490b ^
53e0509 ^










b53d1f9 ^














7544b11 ^










05827d2 ^







b0f474b ^
05827d2 ^




99191f3 ^
05827d2 ^









655701e ^

c7c64dc ^








05827d2 ^






b0f474b ^







99191f3 ^


7544b11 ^
53e0509 ^
b0f474b ^










7544b11 ^





53e0509 ^

7a70828 ^
53e0509 ^









b524e15 ^
b0b7e55 ^


05827d2 ^
b0f474b ^
b524e15 ^
b0f474b ^

05827d2 ^
b0f474b ^


05827d2 ^
b0f474b ^





05827d2 ^
b0f474b ^

05827d2 ^
b0f474b ^
05827d2 ^
b0f474b ^
b524e15 ^
b0f474b ^

05827d2 ^
b0f474b ^






53e0509 ^
b0f474b ^











05827d2 ^
b0f474b ^













05827d2 ^
b0f474b ^













a0eda1c ^



b0f474b ^




53e0509 ^
f3b490b ^

53e0509 ^

99191f3 ^

7544b11 ^
f3b490b ^

7544b11 ^

b0f474b ^
















































b0f474b ^















f3b490b ^
53e0509 ^
f3b490b ^
53e0509 ^





f3b490b ^
53e0509 ^


99191f3 ^




7544b11 ^
f3b490b ^
7544b11 ^





f3b490b ^
7544b11 ^


b0f474b ^


05827d2 ^


b0f474b ^
05827d2 ^
b0f474b ^



05827d2 ^
b0f474b ^
05827d2 ^


b0f474b ^
05827d2 ^

b0f474b ^
05827d2 ^


cbfe9c4 ^

05827d2 ^








b0f474b ^
05827d2 ^
cbfe9c4 ^

b0f474b ^
05827d2 ^
b0f474b ^




53e0509 ^

f3b490b ^
53e0509 ^
dcecbb8 ^


f3b490b ^


53e0509 ^



048b6bd ^
b53d1f9 ^










7544b11 ^



2125ccf ^
b0f474b ^
05827d2 ^




b914799 ^





b524e15 ^
05827d2 ^












b524e15 ^
05827d2 ^

















f0c59de ^
87cf89b ^

05827d2 ^
f0c59de ^
d5324ec ^

05827d2 ^
b0f474b ^
05827d2 ^






b0f474b ^
05827d2 ^






2125ccf ^
05827d2 ^



f0c59de ^







05827d2 ^
f0c59de ^
05827d2 ^
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723



                 
          





                      
                                          
                                                                                                         
                                                           
                             

                            
 
                                          
                               











                                                                                                                        









                                                                                                                        





                                     
                        
                
                     







                                                                                         
                               
                            






                                
                               
                           
                            
 












                                                                              
 
                                          









                                                                      





                                                                


                           
                          




                             


                               

                               







                                                                           



                                                                 










                                                                         
                                                                                


                               









                                                                                                


                               











                                                                      


                               







                                                                


                               







                                                                


                               






                                                        
                                        


                               

                                         
                                                                         

         


                                                                                


                                                                            


                                                                       


                               






                                                                   










                                                                  
                                          










                                                                    














                                                                                        










                                                                 







                                                                                       
                          




                                    
                                 









                                                                                       

                                                                              








                                                                       






                                                        







                                                                              


                                                                                                         
                                                                                               
                          










                                                                    





                                                                     

              
                                                               









                                                                         
                                 


                                                                                      
                                    
                                                                         
 

                         
 


                                                 
 





                                                                                 
 

                                                                           
 
                                      
 
                                                           
 

                                                                                                               
                                






                                                                                                                         
                                                                                                 











                                                                                                                   
                      













                                                                                                                  
 













                                                                                           



                                                      




                                                                      
                                                                       

                                                                                                           

                                                                         

                                                              
                                                                    

                                                                                                           

                                                                      
















































                                                             















                                                                       
                                          
                                                         
                                                                                                    





                                                          
                                    


              




                                                                 
                                                      
                                                                                                    





                                                       
                                    


              


                                                     


                                                                                                                 
                                                      
                                                



                                                             
                                        
                                                        


                                                        
                                          

 
                                                               


                        

                                           








                                                            
                                                                                      
                             

                                           
                                                                              
                                                                                    




                                                                                                   

                                 
                                                                          
                              


                                                                     


                                                                                                     



                                                                                                       
                                                            










                                                                                  



                                                                                                 
                       
                                           




                                                              





                                                                                 
                                        












                                                                               
                                                     

















                                                                                       
                         

                                                             
 
                                                                     

                                   
                                      
                                                     






                                                                                                
                                                                               






                                          
                            



                                                                 







                                                                                
                                       
                           
                     
import asyncio
import os
import pkgutil
import subprocess
import sys
from typing import Any

import websockets

import Utils
import settings
from BaseClasses import ItemClassification
from CommonClient import CommonContext, server_loop, gui_enabled, logger, get_base_parser, handle_url_arg
from NetUtils import Endpoint, decode, encode, ClientStatus
from Utils import async_start
from . import Lingo2World
from .tracker import Tracker

ALL_LETTERS = "abcdefghijklmnopqrstuvwxyz"
MESSAGE_MAX_SIZE = 16*1024*1024
PORT = 43182

KEY_STORAGE_MAPPING = {
    "a": (1, 0), "b": (1, 1), "c": (1, 2), "d": (1, 3), "e": (1, 4), "f": (1, 5), "g": (1, 6), "h": (1, 7), "i": (1, 8),
    "j": (1, 9), "k": (1, 10), "l": (1, 11), "m": (1, 12), "n": (2, 0), "o": (2, 1), "p": (2, 2), "q": (2, 3),
    "r": (2, 4), "s": (2, 5), "t": (2, 6), "u": (2, 7), "v": (2, 8), "w": (2, 9), "x": (2, 10), "y": (2, 11),
    "z": (2, 12),
}

REVERSE_KEY_STORAGE_MAPPING = {t: k for k, t in KEY_STORAGE_MAPPING.items()}


# There is a distinction between an object's ID and its AP ID. The latter is stable between releases, whereas the former
# can change and is also namespaced based on the object type. We should only store AP IDs in multiworld state (such as
# slot data and data storage) to increase compatability between releases. The data we currently store is:
# - Port pairings for worldport shuffle (slot data)
# - Checked worldports for worldport shuffle (data storage)
# - Latched doors (data storage)
# The client generally deals in the actual object IDs rather than the stable IDs, although it does have to convert the
# port pairing IDs when reading them from slot data. The context (this file here) does the work of converting back and
# forth between the values. AP IDs are converted to IDs after reading them from data storage, and IDs are converted to
# AP IDs before sending them to data storage.
class Lingo2Manager:
    game_ctx: "Lingo2GameContext"
    client_ctx: "Lingo2ClientContext"
    tracker: Tracker

    keyboard: dict[str, int]
    worldports: set[int]
    goaled: bool
    latches: set[int]

    def __init__(self, game_ctx: "Lingo2GameContext", client_ctx: "Lingo2ClientContext"):
        self.game_ctx = game_ctx
        self.game_ctx.manager = self
        self.client_ctx = client_ctx
        self.client_ctx.manager = self
        self.tracker = Tracker(self)
        self.keyboard = {}
        self.worldports = set()
        self.latches = set()

        self.reset()

    def reset(self):
        for k in ALL_LETTERS:
            self.keyboard[k] = 0

        self.worldports = set()
        self.goaled = False
        self.latches = set()

    def update_keyboard(self, new_keyboard: dict[str, int]) -> dict[str, int]:
        ret: dict[str, int] = {}

        for k, v in new_keyboard.items():
            if v > self.keyboard.get(k, 0):
                self.keyboard[k] = v
                ret[k] = v

        if len(ret) > 0:
            self.tracker.refresh_state()
            self.game_ctx.send_accessible_locations()

        return ret

    # Input should be real IDs, not AP IDs
    def update_worldports(self, new_worldports: set[int]) -> set[int]:
        ret = new_worldports.difference(self.worldports)
        self.worldports.update(new_worldports)

        if len(ret) > 0:
            self.tracker.refresh_state()
            self.game_ctx.send_accessible_locations()

        return ret

    def update_latches(self, new_latches: set[int]) -> set[int]:
        ret = new_latches.difference(self.latches)
        self.latches.update(new_latches)

        return ret


class Lingo2GameContext:
    server: Endpoint | None
    manager: Lingo2Manager

    def __init__(self):
        self.server = None

    def send_connected(self):
        if self.server is None:
            return

        msg = {
            "cmd": "Connected",
            "user": self.manager.client_ctx.username,
            "seed_name": self.manager.client_ctx.seed_name,
            "version": self.manager.client_ctx.server_version,
            "generator_version": self.manager.client_ctx.generator_version,
            "team": self.manager.client_ctx.team,
            "slot": self.manager.client_ctx.slot,
            "checked_locations": self.manager.client_ctx.checked_locations,
            "slot_data": self.manager.client_ctx.slot_data,
        }

        async_start(self.send_msgs([msg]), name="game Connected")

    def send_connection_refused(self, text):
        if self.server is None:
            return

        msg = {
            "cmd": "ConnectionRefused",
            "text": text,
        }

        async_start(self.send_msgs([msg]), name="game ConnectionRefused")

    def send_item_sent_notification(self, item_name, receiver_name, item_flags):
        if self.server is None:
            return

        msg = {
            "cmd": "ItemSentNotif",
            "item_name": item_name,
            "receiver_name": receiver_name,
            "item_flags": item_flags,
        }

        async_start(self.send_msgs([msg]), name="item sent notif")

    def send_hint_received(self, item_name, location_name, receiver_name, item_flags, for_self):
        if self.server is None:
            return

        msg = {
            "cmd": "HintReceived",
            "item_name": item_name,
            "location_name": location_name,
            "receiver_name": receiver_name,
            "item_flags": item_flags,
            "self": int(for_self),
        }

        async_start(self.send_msgs([msg]), name="hint received notif")

    def send_item_received(self, items):
        if self.server is None:
            return

        msg = {
            "cmd": "ItemReceived",
            "items": items,
        }

        async_start(self.send_msgs([msg]), name="item received")

    def send_location_info(self, locations):
        if self.server is None:
            return

        msg = {
            "cmd": "LocationInfo",
            "locations": locations,
        }

        async_start(self.send_msgs([msg]), name="location info")

    def send_text_message(self, parts):
        if self.server is None:
            return

        msg = {
            "cmd": "TextMessage",
            "data": parts,
        }

        async_start(self.send_msgs([msg]), name="notif")

    def send_accessible_locations(self):
        if self.server is None:
            return

        msg = {
            "cmd": "AccessibleLocations",
            "locations": list(self.manager.tracker.accessible_locations),
        }

        if len(self.manager.tracker.accessible_worldports) > 0:
            msg["worldports"] = list(self.manager.tracker.accessible_worldports)

        if self.manager.tracker.goal_accessible and not self.manager.goaled:
            msg["goal"] = True

        async_start(self.send_msgs([msg]), name="accessible locations")

    def send_update_locations(self, locations):
        if self.server is None:
            return

        msg = {
            "cmd": "UpdateLocations",
            "locations": locations,
        }

        async_start(self.send_msgs([msg]), name="update locations")

    def send_update_keyboard(self, updates):
        if self.server is None:
            return

        msg = {
            "cmd": "UpdateKeyboard",
            "updates": updates,
        }

        async_start(self.send_msgs([msg]), name="update keyboard")

    # Input should be real IDs, not AP IDs
    def send_update_worldports(self, worldports):
        if self.server is None:
            return

        msg = {
            "cmd": "UpdateWorldports",
            "worldports": worldports,
        }

        async_start(self.send_msgs([msg]), name="update worldports")

    def send_path_reply(self, object_type: str, object_id: int | None, path: list[str]):
        if self.server is None:
            return

        msg = {
            "cmd": "PathReply",
            "type": object_type,
            "path": path,
        }

        if object_id is not None:
            msg["id"] = object_id

        async_start(self.send_msgs([msg]), name="path reply")

    def send_update_latches(self, latches):
        if self.server is None:
            return

        msg = {
            "cmd": "UpdateLatches",
            "latches": latches,
        }

        async_start(self.send_msgs([msg]), name="update latches")

    async def send_msgs(self, msgs: list[Any]) -> None:
        """ `msgs` JSON serializable """
        if not self.server or not self.server.socket.open or self.server.socket.closed:
            return
        await self.server.socket.send(encode(msgs))


class Lingo2ClientContext(CommonContext):
    manager: Lingo2Manager

    game = "Lingo 2"
    items_handling = 0b111

    slot_data: dict[str, Any] | None
    victory_data_storage_key: str

    def __init__(self, server_address: str | None = None, password: str | None = None):
        super().__init__(server_address, password)

    def make_gui(self):
        ui = super().make_gui()
        ui.base_title = "Archipelago Lingo 2 Client"
        return ui

    async def server_auth(self, password_requested: bool = False):
        if password_requested and not self.password:
            self.manager.game_ctx.send_connection_refused("Invalid password.")
        else:
            self.auth = self.username
            await self.send_connect()

    def handle_connection_loss(self, msg: str):
        super().handle_connection_loss(msg)

        exc_info = sys.exc_info()
        self.manager.game_ctx.send_connection_refused(str(exc_info[1]))

    def on_package(self, cmd: str, args: dict):
        if cmd == "RoomInfo":
            self.seed_name = args.get("seed_name", None)
        elif cmd == "Connected":
            self.slot_data = args.get("slot_data", None)

            self.manager.reset()

            self.manager.game_ctx.send_connected()

            self.manager.tracker.setup_slot(self.slot_data)
            self.manager.tracker.set_checked_locations(self.checked_locations)
            self.manager.game_ctx.send_accessible_locations()

            self.victory_data_storage_key = f"_read_client_status_{self.team}_{self.slot}"

            self.set_notify(self.get_datastorage_key("keyboard1"), self.get_datastorage_key("keyboard2"),
                            self.victory_data_storage_key, self.get_datastorage_key("latches"))
            msg_batch = [{
                "cmd": "Set",
                "key": self.get_datastorage_key("keyboard1"),
                "default": 0,
                "want_reply": True,
                "operations": [{"operation": "default", "value": 0}]
            }, {
                "cmd": "Set",
                "key": self.get_datastorage_key("keyboard2"),
                "default": 0,
                "want_reply": True,
                "operations": [{"operation": "default", "value": 0}]
            }, {
                "cmd": "Set",
                "key": self.get_datastorage_key("latches"),
                "default": [],
                "want_reply": True,
                "operations": [{"operation": "default", "value": []}]
            }]

            if self.slot_data.get("shuffle_worldports", False):
                self.set_notify(self.get_datastorage_key("worldports"))
                msg_batch.append({
                    "cmd": "Set",
                    "key": self.get_datastorage_key("worldports"),
                    "default": [],
                    "want_reply": True,
                    "operations": [{"operation": "default", "value": []}]
                })

            async_start(self.send_msgs(msg_batch), name="default keys")
        elif cmd == "RoomUpdate":
            if "checked_locations" in args:
                self.manager.tracker.set_checked_locations(self.checked_locations)
                self.manager.game_ctx.send_update_locations(args["checked_locations"])
        elif cmd == "ReceivedItems":
            self.manager.tracker.set_collected_items(self.items_received)

            cur_index = 0
            items = []

            for item in args["items"]:
                index = cur_index + args["index"]
                cur_index += 1

                item_msg = {
                    "id": item.item,
                    "index": index,
                    "flags": item.flags,
                    "text": self.item_names.lookup_in_slot(item.item, self.slot),
                }

                if item.player != self.slot:
                    item_msg["sender"] = self.player_names.get(item.player)

                items.append(item_msg)

            self.manager.game_ctx.send_item_received(items)

            if any(ItemClassification.progression in ItemClassification(item.flags) for item in args["items"]):
                self.manager.game_ctx.send_accessible_locations()
        elif cmd == "PrintJSON":
            if "receiving" in args and "item" in args and args["item"].player == self.slot:
                item_name = self.item_names.lookup_in_slot(args["item"].item, args["receiving"])
                location_name = self.location_names.lookup_in_slot(args["item"].location, args["item"].player)
                receiver_name = self.player_names.get(args["receiving"])

                if args["type"] == "Hint" and not args.get("found", False):
                    self.manager.game_ctx.send_hint_received(item_name, location_name, receiver_name, args["item"].flags,
                                                             int(args["receiving"]) == self.slot)
                elif args["receiving"] != self.slot:
                    self.manager.game_ctx.send_item_sent_notification(item_name, receiver_name, args["item"].flags)

            parts = []
            for message_part in args["data"]:
                if "type" not in message_part and "text" in message_part:
                    parts.append({"type": "text", "text": message_part["text"]})
                elif message_part["type"] == "player_id":
                    parts.append({
                        "type": "player",
                        "text": self.player_names.get(int(message_part["text"])),
                        "self": int(int(message_part["text"]) == self.slot),
                    })
                elif message_part["type"] == "item_id":
                    parts.append({
                        "type": "item",
                        "text": self.item_names.lookup_in_slot(int(message_part["text"]), message_part["player"]),
                        "flags": message_part["flags"],
                    })
                elif message_part["type"] == "location_id":
                    parts.append({
                        "type": "location",
                        "text": self.location_names.lookup_in_slot(int(message_part["text"]),
                                                                   message_part["player"])
                    })
                elif "text" in message_part:
                    parts.append({"type": "text", "text": message_part["text"]})

            self.manager.game_ctx.send_text_message(parts)
        elif cmd == "LocationInfo":
            locations = []

            for location in args["locations"]:
                locations.append({
                    "id": location.location,
                    "item": self.item_names.lookup_in_slot(location.item, location.player),
                    "player": self.player_names.get(location.player),
                    "flags": location.flags,
                    "self": int(location.player) == self.slot,
                })

            self.manager.game_ctx.send_location_info(locations)
        elif cmd == "Retrieved":
            for k, v in args["keys"].items():
                if k == self.victory_data_storage_key:
                    self.handle_status_update(v)
        elif cmd == "SetReply":
            if args["key"] == self.get_datastorage_key("keyboard1"):
                self.handle_keyboard_update(1, args)
            elif args["key"] == self.get_datastorage_key("keyboard2"):
                self.handle_keyboard_update(2, args)
            elif args["key"] == self.get_datastorage_key("worldports"):
                port_ids = set(Lingo2World.static_logic.port_id_by_ap_id[ap_id] for ap_id in args["value"])
                updates = self.manager.update_worldports(port_ids)
                if len(updates) > 0:
                    self.manager.game_ctx.send_update_worldports(updates)
            elif args["key"] == self.victory_data_storage_key:
                self.handle_status_update(args["value"])
            elif args["key"] == self.get_datastorage_key("latches"):
                door_ids = set(Lingo2World.static_logic.door_id_by_ap_id[ap_id] for ap_id in args["value"])
                updates = self.manager.update_latches(door_ids)
                if len(updates) > 0:
                    self.manager.game_ctx.send_update_latches(updates)

    def get_datastorage_key(self, name: str):
        return f"Lingo2_{self.slot}_{name}"

    async def update_keyboard(self, updates: dict[str, int]):
        kb1 = 0
        kb2 = 0

        for k, v in updates.items():
            if v == 0:
                continue

            effect = 0
            if v >= 1:
                effect |= 1
            if v == 2:
                effect |= 2

            pos = KEY_STORAGE_MAPPING[k]
            if pos[0] == 1:
                kb1 |= (effect << pos[1] * 2)
            else:
                kb2 |= (effect << pos[1] * 2)

        msgs = []

        if kb1 != 0:
            msgs.append({
                "cmd": "Set",
                "key": self.get_datastorage_key("keyboard1"),
                "want_reply": True,
                "operations": [{
                    "operation": "or",
                    "value": kb1
                }]
            })

        if kb2 != 0:
            msgs.append({
                "cmd": "Set",
                "key": self.get_datastorage_key("keyboard2"),
                "want_reply": True,
                "operations": [{
                    "operation": "or",
                    "value": kb2
                }]
            })

        if len(msgs) > 0:
            await self.send_msgs(msgs)

    def handle_keyboard_update(self, field: int, args: dict[str, Any]):
        keys = {}
        value = args["value"]

        for i in range(0, 13):
            if (value & (1 << (i * 2))) != 0:
                keys[REVERSE_KEY_STORAGE_MAPPING[(field, i)]] = 1
            if (value & (1 << (i * 2 + 1))) != 0:
                keys[REVERSE_KEY_STORAGE_MAPPING[(field, i)]] = 2

        updates = self.manager.update_keyboard(keys)
        if len(updates) > 0:
            self.manager.game_ctx.send_update_keyboard(updates)

    # Input should be real IDs, not AP IDs
    async def update_worldports(self, updates: set[int]):
        port_ap_ids = [Lingo2World.static_logic.objects.ports[port_id].ap_id for port_id in updates]
        await self.send_msgs([{
            "cmd": "Set",
            "key": self.get_datastorage_key("worldports"),
            "want_reply": True,
            "operations": [{
                "operation": "update",
                "value": port_ap_ids
            }]
        }])

    def handle_status_update(self, value: int):
        self.manager.goaled = (value == ClientStatus.CLIENT_GOAL)
        self.manager.tracker.refresh_state()
        self.manager.game_ctx.send_accessible_locations()

    async def update_latches(self, updates: set[int]):
        door_ap_ids = [Lingo2World.static_logic.objects.doors[door_id].ap_id for door_id in updates]
        await self.send_msgs([{
            "cmd": "Set",
            "key": self.get_datastorage_key("latches"),
            "want_reply": True,
            "operations": [{
                "operation": "update",
                "value": door_ap_ids
            }]
        }])


async def pipe_loop(manager: Lingo2Manager):
    while not manager.client_ctx.exit_event.is_set():
        try:
            socket = await websockets.connect("ws://localhost", port=PORT, ping_timeout=None, ping_interval=None,
                                              max_size=MESSAGE_MAX_SIZE)
            manager.game_ctx.server = Endpoint(socket)
            logger.info("Connected to Lingo 2!")
            if manager.client_ctx.auth is not None:
                manager.game_ctx.send_connected()
                manager.game_ctx.send_accessible_locations()
            async for data in manager.game_ctx.server.socket:
                for msg in decode(data):
                    await process_game_cmd(manager, msg)
        except ConnectionRefusedError:
            logger.info("Could not connect to Lingo 2.")
        finally:
            manager.game_ctx.server = None


async def process_game_cmd(manager: Lingo2Manager, args: dict):
    cmd = args["cmd"]

    if cmd == "Connect":
        manager.client_ctx.seed_name = None

        server = args.get("server")
        player = args.get("player")
        password = args.get("password")

        if password != "":
            server_address = f"{player}:{password}@{server}"
        else:
            server_address = f"{player}:None@{server}"

        async_start(manager.client_ctx.connect(server_address), name="client connect")
    elif cmd == "Disconnect":
        manager.client_ctx.seed_name = None

        async_start(manager.client_ctx.disconnect(), name="client disconnect")
    elif cmd in ["Sync", "LocationChecks", "Say", "StatusUpdate", "LocationScouts"]:
        async_start(manager.client_ctx.send_msgs([args]), name="client forward")
    elif cmd == "UpdateKeyboard":
        updates = manager.update_keyboard(args["keyboard"])
        if len(updates) > 0:
            async_start(manager.client_ctx.update_keyboard(updates), name="client update keyboard")
    elif cmd == "CheckWorldport":
        port_id = args["port_id"]
        port_ap_id = Lingo2World.static_logic.objects.ports[port_id].ap_id
        worldports = {port_id}

        # Also check the reverse port if it's a two-way connection.
        port_pairings = manager.client_ctx.slot_data["port_pairings"]
        if str(port_ap_id) in port_pairings and\
                port_pairings.get(str(port_pairings[str(port_ap_id)]), None) == port_ap_id:
            worldports.add(Lingo2World.static_logic.port_id_by_ap_id[port_pairings[str(port_ap_id)]])

        updates = manager.update_worldports(worldports)
        if len(updates) > 0:
            async_start(manager.client_ctx.update_worldports(updates), name="client update worldports")
            manager.game_ctx.send_update_worldports(updates)
    elif cmd == "GetPath":
        path = None

        if args["type"] == "location":
            path = manager.tracker.get_path_to_location(args["id"])
        elif args["type"] == "worldport":
            path = manager.tracker.get_path_to_port(args["id"])
        elif args["type"] == "goal":
            path = manager.tracker.get_path_to_goal()

        manager.game_ctx.send_path_reply(args["type"], args.get("id", None), path)
    elif cmd == "LatchDoor":
        updates = manager.update_latches({args["door"]})
        if len(updates) > 0:
            async_start(manager.client_ctx.update_latches(updates), name="client update latches")
    elif cmd == "Quit":
        manager.client_ctx.exit_event.set()


async def run_game():
    exe_file = settings.get_settings().lingo2_options.exe_file

    # This ensures we can use Steam features without having to open the game
    # through steam.
    steam_appid_path = os.path.join(os.path.dirname(exe_file), "steam_appid.txt")
    with open(steam_appid_path, "w") as said_handle:
        said_handle.write("2523310")

    if Lingo2World.zip_path is not None:
        # This is a packaged apworld.
        init_scene = pkgutil.get_data(__name__, "client/run_from_apworld.tscn")
        init_path = Utils.local_path("data", "lingo2_init.tscn")

        with open(init_path, "wb") as file_handle:
            file_handle.write(init_scene)

        subprocess.Popen(
            [
                exe_file,
                "--scene",
                init_path,
                "--",
                str(Lingo2World.zip_path.absolute()),
            ],
            cwd=os.path.dirname(exe_file),
        )
    else:
        # The world is unzipped and being run in source.
        subprocess.Popen(
            [
                exe_file,
                "--scene",
                Utils.local_path("worlds", "lingo2", "client", "run_from_source.tscn"),
                "--",
                Utils.local_path("worlds", "lingo2", "client"),
            ],
            cwd=os.path.dirname(exe_file),
        )


def client_main(*launch_args: str) -> None:
    async def main(args):
        if settings.get_settings().lingo2_options.start_game:
            async_start(run_game())

        client_ctx = Lingo2ClientContext(args.connect, args.password)
        client_ctx.auth = args.name

        game_ctx = Lingo2GameContext()
        manager = Lingo2Manager(game_ctx, client_ctx)

        client_ctx.server_task = asyncio.create_task(server_loop(client_ctx), name="ServerLoop")

        if gui_enabled:
            client_ctx.run_gui()
        client_ctx.run_cli()

        pipe_task = asyncio.create_task(pipe_loop(manager), name="GameWatcher")

        try:
            await pipe_task
        except Exception as e:
            logger.exception(e)

        await client_ctx.exit_event.wait()
        client_ctx.ui.stop()
        await client_ctx.shutdown()

    Utils.init_logging("Lingo2Client", exception_logger="Client")
    import colorama

    parser = get_base_parser(description="Lingo 2 Archipelago Client")
    parser.add_argument('--name', default=None, help="Slot Name to connect as.")
    parser.add_argument("url", nargs="?", help="Archipelago connection url")
    args = parser.parse_args(launch_args)

    args = handle_url_arg(args, parser=parser)

    colorama.just_fix_windows_console()
    asyncio.run(main(args))
    colorama.deinit()