taikyokushogi 0.1.0

Taikyoku Shogi engine — the largest known shogi variant (36x36 board, 804 pieces, 209 piece types)
Documentation
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
#!/usr/bin/env python3
"""Taikyoku Shogi Web GUI - play in browser against random player or watch random vs random."""

import json
import sys
import os
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Try Rust backend first, fall back to pure Python
try:
    import taikyokushogi
    USE_RUST = True
    print("Using Rust backend (taikyokushogi)")
except ImportError:
    USE_RUST = False
    print("Rust backend not found, using pure Python")

if not USE_RUST:
    from taikyoku_engine.board import TaikyokuBoard
    from taikyoku_engine.pieces import (
        BOARD_SIZE, BLACK, WHITE, PIECE_NAME, PIECE_VALUE, PROMOTES_TO, MOVEMENTS,
    )
    from taikyoku_engine.movegen import generate_legal_moves, choose_random_move
    from taikyoku_engine.move import Move
else:
    BOARD_SIZE = taikyokushogi.BOARD_SIZE
    BLACK = taikyokushogi.BLACK
    WHITE = taikyokushogi.WHITE

# ============================================================
# Game State (global, protected by lock)
# ============================================================
game_lock = threading.Lock()


class GameState:
    def __init__(self):
        if USE_RUST:
            self.board = taikyokushogi.PyBoard()
        else:
            self.board = TaikyokuBoard()
        self.board.setup_initial()
        self.mode = 'human_vs_random'
        self.human_color = BLACK
        self.move_log = []
        self.score_history = [self._score()]
        self.half_move = 0
        self.selected = None
        self.game_over = False

    def reset(self, mode='human_vs_random', human_color=BLACK):
        if USE_RUST:
            self.board = taikyokushogi.PyBoard()
        else:
            self.board = TaikyokuBoard()
        self.board.setup_initial()
        self.mode = mode
        self.human_color = human_color
        self.move_log = []
        self.score_history = [self._score()]
        self.half_move = 0
        self.selected = None
        self.game_over = False

    def _score(self):
        if USE_RUST:
            return self.board.score()
        score = 0
        for (r, c), piece in self.board.piece_positions[BLACK].items():
            score += PIECE_VALUE.get(piece, 1000)
        for (r, c), piece in self.board.piece_positions[WHITE].items():
            score -= PIECE_VALUE.get(piece, 1000)
        return score


game = GameState()


def board_to_json(board):
    """Serialize board state to JSON-compatible dict."""
    if USE_RUST:
        cells = []
        for r in range(BOARD_SIZE):
            row = []
            for c in range(BOARD_SIZE):
                cell = board.at(r, c)
                if cell is None:
                    row.append(None)
                else:
                    piece, color = cell
                    row.append({'piece': piece, 'color': color,
                                'name': taikyokushogi.piece_name_py(piece)})
            cells.append(row)
        result = board.game_result()
        return {
            'board': cells,
            'side_to_move': board.side_to_move,
            'move_number': board.move_number,
            'game_result': result,
            'black_pieces': board.black_piece_count(),
            'white_pieces': board.white_piece_count(),
        }
    else:
        cells = []
        for r in range(BOARD_SIZE):
            row = []
            for c in range(BOARD_SIZE):
                cell = board.at(r, c)
                if cell is None:
                    row.append(None)
                else:
                    piece, color = cell
                    row.append({'piece': piece, 'color': color,
                                'name': PIECE_NAME.get(piece, piece)})
            cells.append(row)
        result = board.get_game_result()
        return {
            'board': cells,
            'side_to_move': board.side_to_move,
            'move_number': board.move_number,
            'game_result': result,
            'black_pieces': len(board.piece_positions[BLACK]),
            'white_pieces': len(board.piece_positions[WHITE]),
        }


def moves_for_square(board, r, c):
    if USE_RUST:
        return board.moves_from_py(r, c)
    cell = board.at(r, c)
    if cell is None: return []
    piece, color = cell
    if color != board.side_to_move: return []
    all_moves = generate_legal_moves(board)
    result = []
    seen = set()
    for m in all_moves:
        if m.from_sq == (r, c):
            key = (m.to_sq, m.promotion, m.is_igui)
            if key not in seen:
                seen.add(key)
                cap_name = PIECE_NAME.get(m.captured, m.captured) if m.captured else None
                result.append({'to': list(m.to_sq), 'promotion': m.promotion,
                               'is_igui': m.is_igui, 'captured': cap_name})
    return result


def find_matching_move(board, fr, fc, tr, tc, promotion=False):
    if USE_RUST:
        return board.apply_move_py(fr, fc, tr, tc, promotion)
    all_moves = generate_legal_moves(board)
    for m in all_moves:
        if m.from_sq == (fr, fc) and m.to_sq == (tr, tc) and m.promotion == promotion:
            return m
    return None


# ============================================================
# HTTP Handler
# ============================================================
class GameHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass  # Suppress request logging

    def _send_json(self, data, status=200):
        body = json.dumps(data).encode()
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', len(body))
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(body)

    def _send_html(self, html):
        body = html.encode()
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.send_header('Content-Length', len(body))
        self.end_headers()
        self.wfile.write(body)

    def _read_body(self):
        length = int(self.headers.get('Content-Length', 0))
        if length:
            return json.loads(self.rfile.read(length))
        return {}

    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        params = parse_qs(parsed.query)

        if path == '/' or path == '/index.html':
            self._send_html(HTML_PAGE)

        elif path == '/api/state':
            with game_lock:
                data = board_to_json(game.board)
                data['mode'] = game.mode
                data['human_color'] = game.human_color
                data['move_count'] = len(game.move_log)
                data['move_log'] = game.move_log[-50:]
                data['move_log_offset'] = max(0, len(game.move_log) - 50)
                data['score_history'] = game.score_history
                data['game_over'] = game.game_over
            self._send_json(data)

        elif path == '/api/moves':
            r = int(params.get('r', ['-1'])[0])
            c = int(params.get('c', ['-1'])[0])
            with game_lock:
                moves = moves_for_square(game.board, r, c)
            self._send_json({'moves': moves, 'from': [r, c]})

        elif path == '/api/piece-info':
            abbrev = params.get('abbrev', [''])[0]
            if USE_RUST:
                self._send_json(taikyokushogi.piece_info_py(abbrev))
            else:
                name = PIECE_NAME.get(abbrev, abbrev)
                value = PIECE_VALUE.get(abbrev, 0)
                promo = PROMOTES_TO.get(abbrev)
                promo_name = PIECE_NAME.get(promo, promo) if promo else None
                mov = MOVEMENTS.get(abbrev, {})
                slide_count = len(mov.get('slides', []))
                jump_count = len(mov.get('jumps', []))
                specials = []
                if mov.get('hook'): specials.append(f"hook ({mov['hook']})")
                if mov.get('area'): specials.append(f"area ({mov['area']})")
                if mov.get('range_capture'): specials.append("range capture")
                if mov.get('igui'): specials.append("igui")
                self._send_json({
                    'abbrev': abbrev, 'name': name, 'value': value,
                    'promotes_to': promo_name,
                    'slide_directions': slide_count,
                    'jump_destinations': jump_count,
                    'specials': specials,
                })

        else:
            self.send_error(404)

    def do_POST(self):
        path = urlparse(self.path).path
        body = self._read_body()

        if path == '/api/new-game':
            mode = body.get('mode', 'human_vs_random')
            human_color = body.get('human_color', BLACK)
            with game_lock:
                game.reset(mode=mode, human_color=human_color)
            self._send_json({'ok': True})

        elif path == '/api/move':
            fr, fc = body['from']
            tr, tc = body['to']
            promotion = body.get('promotion', False)
            with game_lock:
                if game.game_over:
                    self._send_json({'ok': False, 'error': 'Game is over'})
                    return
                game.half_move += 1
                side = 'Black' if game.board.side_to_move == BLACK else 'White'
                piece = game.board.at(fr, fc)
                pname = piece[0] if piece else '?'
                promo_s = "+" if promotion else ""
                if USE_RUST:
                    ok = game.board.apply_move_py(fr, fc, tr, tc, promotion)
                    if not ok:
                        game.half_move -= 1
                        self._send_json({'ok': False, 'error': 'Illegal move'})
                        return
                else:
                    m = find_matching_move(game.board, fr, fc, tr, tc, promotion)
                    if m is None:
                        game.half_move -= 1
                        self._send_json({'ok': False, 'error': 'Illegal move'})
                        return
                    game.board.apply_move(m)
                score = game._score()
                game.score_history.append(score)
                entry = f"{game.half_move}. {side}: {pname} {_sq(fr,fc)}-{_sq(tr,tc)}{promo_s}"
                game.move_log.append(entry)
                result = board_to_json(game.board)['game_result']
                if result:
                    game.game_over = True
                    game.move_log.append(f"** Game over: {result} **")
                data = board_to_json(game.board)
                data['move_log'] = game.move_log[-50:]
                data['move_log_offset'] = max(0, len(game.move_log) - 50)
                data['score_history'] = game.score_history
                data['game_over'] = game.game_over
            self._send_json({'ok': True, **data})

        elif path == '/api/ai-move':
            with game_lock:
                if game.game_over:
                    self._send_json({'ok': False, 'error': 'Game is over'})
                    return
                game.half_move += 1
                side = 'Black' if game.board.side_to_move == BLACK else 'White'
                if USE_RUST:
                    rm = game.board.random_move_py()
                    if rm is None:
                        game.half_move -= 1
                        game.game_over = True
                        game.move_log.append("No legal moves - stalemate")
                        self._send_json({'ok': False, 'error': 'No legal moves'})
                        return
                    fr, fc, tr, tc, promotion = rm
                    piece = game.board.at(fr, fc)
                    pname = piece[0] if piece else '?'
                    game.board.apply_move_py(fr, fc, tr, tc, promotion)
                else:
                    m = choose_random_move(game.board)
                    if m is None:
                        game.half_move -= 1
                        game.game_over = True
                        game.move_log.append("No legal moves - stalemate")
                        self._send_json({'ok': False, 'error': 'No legal moves'})
                        return
                    fr, fc = m.from_sq
                    tr, tc = m.to_sq
                    promotion = m.promotion
                    piece = game.board.at(fr, fc)
                    pname = piece[0] if piece else '?'
                    game.board.apply_move(m)
                promo_s = "+" if promotion else ""
                score = game._score()
                game.score_history.append(score)
                entry = f"{game.half_move}. {side}: {pname} {_sq(fr,fc)}-{_sq(tr,tc)}{promo_s}"
                game.move_log.append(entry)
                result = board_to_json(game.board)['game_result']
                if result:
                    game.game_over = True
                    game.move_log.append(f"** Game over: {result} **")
                data = board_to_json(game.board)
                data['move_log'] = game.move_log[-50:]
                data['move_log_offset'] = max(0, len(game.move_log) - 50)
                data['score_history'] = game.score_history
                data['game_over'] = game.game_over
                data['last_move'] = {'from': [fr, fc], 'to': [tr, tc]}
            self._send_json({'ok': True, **data})

        elif path == '/api/undo':
            with game_lock:
                if USE_RUST:
                    ok = game.board.undo()
                else:
                    ok = bool(game.board.move_history)
                    if ok:
                        game.board.undo_move()
                if ok:
                    if game.move_log:
                        game.move_log.pop()
                    if len(game.score_history) > 1:
                        game.score_history.pop()
                    if game.half_move > 0:
                        game.half_move -= 1
                    game.game_over = False
                    self._send_json({'ok': True})
                else:
                    self._send_json({'ok': False, 'error': 'Nothing to undo'})

        else:
            self.send_error(404)

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()


def _sq(r, c):
    """Format square coordinate."""
    return f"({r},{c})"


# ============================================================
# HTML Frontend (embedded)
# ============================================================
HTML_PAGE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Taikyoku Shogi</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: 'Segoe UI', system-ui, sans-serif;
    background: #1a1a2e;
    color: #e0e0e0;
    min-height: 100vh;
}
.header {
    background: #16213e;
    padding: 8px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border-bottom: 2px solid #0f3460;
    flex-wrap: wrap;
}
.header h1 {
    font-size: 18px;
    color: #e94560;
    white-space: nowrap;
}
.controls {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
}
.controls select, .controls button {
    padding: 4px 10px;
    border-radius: 4px;
    border: 1px solid #0f3460;
    background: #1a1a2e;
    color: #e0e0e0;
    font-size: 12px;
    cursor: pointer;
}
.controls button { background: #0f3460; }
.controls button:hover { background: #e94560; }
.controls button.active { background: #e94560; }
.controls label { font-size: 12px; color: #aaa; }
.status-bar {
    font-size: 12px;
    color: #aaa;
    margin-left: auto;
    text-align: right;
    min-width: 200px;
}
.main {
    display: flex;
    gap: 12px;
    padding: 10px;
    justify-content: center;
    align-items: flex-start;
}
/* Board */
.board-wrap {
    overflow: auto;
    max-height: calc(100vh - 60px);
    border: 2px solid #0f3460;
    background: #0a0a1a;
    flex-shrink: 0;
}
.board {
    display: grid;
    grid-template-columns: 20px repeat(36, var(--cell));
    grid-template-rows: repeat(36, var(--cell)) 20px;
    gap: 0;
    --cell: 28px;
    font-size: 8px;
}
.coord {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 7px;
    color: #666;
    user-select: none;
}
.cell {
    width: var(--cell);
    height: var(--cell);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    user-select: none;
    font-weight: 600;
    position: relative;
    transition: background 0.1s;
    line-height: 1;
    letter-spacing: -0.5px;
}
.cell.light { background: #c8b07a; }
.cell.dark { background: #a68a5b; }
.cell.black-piece { color: #1a0505; }
.cell.white-piece { color: #f5f5ff; }
.cell.white-piece::after {
    content: '';
    position: absolute;
    bottom: 1px;
    left: 50%;
    transform: translateX(-50%);
    width: 60%;
    height: 2px;
    background: #ccccff;
    border-radius: 1px;
}
.cell.selected { background: #ffd700 !important; }
.cell.legal-target { background: #5cb85c !important; cursor: crosshair; }
.cell.legal-target.has-enemy { background: #d9534f !important; }
.cell.last-from { box-shadow: inset 0 0 0 2px #4a90d9; }
.cell.last-to { box-shadow: inset 0 0 0 2px #4a90d9; }
.cell:hover { filter: brightness(1.2); }
.cell .promo-dot {
    position: absolute;
    top: 1px;
    right: 1px;
    width: 3px;
    height: 3px;
    background: #e94560;
    border-radius: 50%;
}
/* Sidebar */
.sidebar {
    width: 260px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    flex-shrink: 0;
    max-height: calc(100vh - 60px);
}
.panel {
    background: #16213e;
    border: 1px solid #0f3460;
    border-radius: 6px;
    padding: 10px;
}
.panel h3 {
    font-size: 12px;
    color: #e94560;
    margin-bottom: 6px;
    border-bottom: 1px solid #0f3460;
    padding-bottom: 4px;
}
.panel .info-row {
    display: flex;
    justify-content: space-between;
    font-size: 11px;
    padding: 2px 0;
}
.panel .info-row .label { color: #888; }
.move-log {
    flex: 1;
    overflow-y: auto;
    max-height: 400px;
}
.move-log .entry {
    font-size: 10px;
    padding: 1px 4px;
    font-family: monospace;
    border-bottom: 1px solid #0a0a1a;
}
.move-log .entry:nth-child(odd) { background: rgba(255,255,255,0.02); }
.move-log .entry .move-num { color: #666; margin-right: 2px; }
/* Score graph */
.score-graph-wrap {
    position: relative;
    background: #0d1b2a;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 6px;
}
.score-graph-wrap canvas {
    display: block;
    width: 100%;
}
.score-label {
    font-size: 9px;
    color: #666;
    display: flex;
    justify-content: space-between;
    padding: 0 2px;
}
.score-current {
    font-size: 12px;
    font-weight: 700;
    text-align: center;
    padding: 4px 0 2px;
}
.score-current.positive { color: #5cb85c; }
.score-current.negative { color: #d9534f; }
.score-current.zero { color: #888; }
.piece-info {
    font-size: 11px;
    min-height: 80px;
}
.piece-info .piece-name { font-size: 14px; font-weight: 700; color: #fff; }
.piece-info .piece-detail { color: #aaa; margin-top: 4px; }
/* Promotion dialog */
.promo-dialog {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #16213e;
    border: 2px solid #e94560;
    border-radius: 8px;
    padding: 20px;
    z-index: 1000;
    text-align: center;
}
.promo-dialog.show { display: block; }
.promo-dialog h3 { margin-bottom: 12px; color: #e94560; }
.promo-dialog button {
    padding: 8px 24px;
    margin: 4px;
    border-radius: 4px;
    border: 1px solid #0f3460;
    background: #0f3460;
    color: #e0e0e0;
    cursor: pointer;
    font-size: 14px;
}
.promo-dialog button:hover { background: #e94560; }
.overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.5);
    z-index: 999;
}
.overlay.show { display: block; }
/* Speed selector */
.speed-control { display: flex; align-items: center; gap: 4px; }
.speed-control input[type=range] { width: 80px; }
</style>
</head>
<body>

<div class="header">
    <h1>Taikyoku Shogi</h1>
    <div class="controls">
        <label>Mode:</label>
        <select id="mode-select">
            <option value="human_vs_random">Human vs Random</option>
            <option value="random_vs_random">Random vs Random</option>
        </select>
        <label>Play as:</label>
        <select id="color-select">
            <option value="0">Black (first)</option>
            <option value="1">White (second)</option>
        </select>
        <button onclick="newGame()">New Game</button>
        <button onclick="undoMove()">Undo</button>
        <button id="auto-btn" onclick="toggleAuto()">Auto Play</button>
        <div class="speed-control">
            <label>Speed:</label>
            <input type="range" id="speed" min="100" max="3000" value="800" step="100">
            <span id="speed-label">800ms</span>
        </div>
    </div>
    <div class="status-bar" id="status">Loading...</div>
</div>

<div class="main">
    <div class="board-wrap">
        <div class="board" id="board"></div>
    </div>
    <div class="sidebar">
        <div class="panel">
            <h3>Game Info</h3>
            <div class="info-row"><span class="label">Turn:</span><span id="info-turn">Black</span></div>
            <div class="info-row"><span class="label">Move #:</span><span id="info-move">1</span></div>
            <div class="info-row"><span class="label">Black pieces:</span><span id="info-black">402</span></div>
            <div class="info-row"><span class="label">White pieces:</span><span id="info-white">402</span></div>
            <div class="info-row"><span class="label">Result:</span><span id="info-result">-</span></div>
        </div>
        <div class="panel piece-info" id="piece-info-panel">
            <h3>Piece Info</h3>
            <div id="piece-info-content">Click a piece to see details</div>
        </div>
        <div class="panel" style="flex:1; display:flex; flex-direction:column; min-height:0;">
            <h3>Move Log</h3>
            <div class="move-log" id="move-log"></div>
        </div>
        <div class="panel">
            <h3>Score (Black's Perspective)</h3>
            <div class="score-current" id="score-current">0</div>
            <div class="score-graph-wrap">
                <canvas id="score-canvas" width="238" height="100"></canvas>
            </div>
            <div class="score-label">
                <span>Move 0</span>
                <span id="score-x-end">-</span>
            </div>
        </div>
    </div>
</div>

<div class="overlay" id="overlay"></div>
<div class="promo-dialog" id="promo-dialog">
    <h3>Promote this piece?</h3>
    <p id="promo-text"></p>
    <button onclick="doPromo(true)">Yes, Promote</button>
    <button onclick="doPromo(false)">No, Keep</button>
</div>

<script>
const SIZE = 36;
let boardState = null;
let selectedSq = null;
let legalMoves = [];
let lastMove = null;
let autoPlay = false;
let autoTimer = null;
let pendingPromo = null; // {from, to}
let gameMode = 'human_vs_random';
let humanColor = 0;

// Build the board grid
function buildBoard() {
    const el = document.getElementById('board');
    el.innerHTML = '';
    // Column headers
    el.appendChild(makeCoord(''));
    for (let c = 0; c < SIZE; c++) {
        const d = makeCoord(SIZE - c);
        el.appendChild(d);
    }
    // Rows
    for (let r = 0; r < SIZE; r++) {
        // Row label
        el.appendChild(makeCoord(SIZE - r));
        for (let c = 0; c < SIZE; c++) {
            const cell = document.createElement('div');
            cell.className = 'cell ' + ((r + c) % 2 === 0 ? 'light' : 'dark');
            cell.dataset.r = r;
            cell.dataset.c = c;
            cell.id = `cell-${r}-${c}`;
            cell.addEventListener('click', () => onCellClick(r, c));
            cell.addEventListener('mouseenter', () => onCellHover(r, c));
            el.appendChild(cell);
        }
    }
    // Bottom row label
    el.appendChild(makeCoord(''));
    for (let c = 0; c < SIZE; c++) {
        el.appendChild(makeCoord(SIZE - c));
    }
}

function makeCoord(text) {
    const d = document.createElement('div');
    d.className = 'coord';
    d.textContent = text;
    return d;
}

function renderBoard(state) {
    boardState = state;
    for (let r = 0; r < SIZE; r++) {
        for (let c = 0; c < SIZE; c++) {
            const cell = document.getElementById(`cell-${r}-${c}`);
            if (!cell) continue;
            // Reset classes
            cell.className = 'cell ' + ((r + c) % 2 === 0 ? 'light' : 'dark');
            cell.innerHTML = '';
            const piece = state.board[r][c];
            if (piece) {
                cell.textContent = piece.piece;
                if (piece.color === 0) {
                    cell.classList.add('black-piece');
                } else {
                    cell.classList.add('white-piece');
                }
            }
            // Highlight selected
            if (selectedSq && selectedSq[0] === r && selectedSq[1] === c) {
                cell.classList.add('selected');
            }
            // Highlight legal targets
            const lm = legalMoves.find(m => m.to[0] === r && m.to[1] === c);
            if (lm) {
                cell.classList.add('legal-target');
                if (lm.captured) cell.classList.add('has-enemy');
            }
            // Highlight last move
            if (lastMove) {
                if (lastMove.from[0] === r && lastMove.from[1] === c) cell.classList.add('last-from');
                if (lastMove.to[0] === r && lastMove.to[1] === c) cell.classList.add('last-to');
            }
        }
    }
    // Update info panel
    document.getElementById('info-turn').textContent = state.side_to_move === 0 ? 'Black' : 'White';
    document.getElementById('info-move').textContent = state.move_number;
    document.getElementById('info-black').textContent = state.black_pieces;
    document.getElementById('info-white').textContent = state.white_pieces;
    document.getElementById('info-result').textContent = state.game_result || '-';
    // Move log
    const logEl = document.getElementById('move-log');
    if (state.move_log) {
        logEl.innerHTML = state.move_log.map(e => `<div class="entry">${e}</div>`).join('');
        logEl.scrollTop = logEl.scrollHeight;
    }
    // Status
    let statusText = `${state.black_pieces} vs ${state.white_pieces} pieces`;
    if (state.game_result) {
        statusText = state.game_result.replace('_', ' ');
        stopAuto();
    }
    document.getElementById('status').textContent = statusText;
    // Score graph
    if (state.score_history) {
        drawScoreGraph(state.score_history);
    }
}

function drawScoreGraph(scores) {
    const canvas = document.getElementById('score-canvas');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const W = canvas.width;
    const H = canvas.height;
    ctx.clearRect(0, 0, W, H);

    if (scores.length < 1) return;

    const current = scores[scores.length - 1];
    const curEl = document.getElementById('score-current');
    const sign = current > 0 ? '+' : '';
    curEl.textContent = `${sign}${current}`;
    curEl.className = 'score-current ' + (current > 0 ? 'positive' : current < 0 ? 'negative' : 'zero');

    document.getElementById('score-x-end').textContent = `Move ${scores.length - 1}`;

    // Compute Y range
    let minS = Math.min(...scores);
    let maxS = Math.max(...scores);
    if (minS === maxS) { minS -= 1000; maxS += 1000; }
    const pad = (maxS - minS) * 0.1;
    minS -= pad;
    maxS += pad;

    const n = scores.length;
    const xStep = n > 1 ? W / (n - 1) : W;

    // Draw zero line
    const zeroY = H - ((0 - minS) / (maxS - minS)) * H;
    ctx.strokeStyle = '#334';
    ctx.lineWidth = 1;
    ctx.setLineDash([4, 4]);
    ctx.beginPath();
    ctx.moveTo(0, zeroY);
    ctx.lineTo(W, zeroY);
    ctx.stroke();
    ctx.setLineDash([]);

    // Fill areas
    if (n > 1) {
        // Positive area (green)
        ctx.beginPath();
        ctx.moveTo(0, zeroY);
        for (let i = 0; i < n; i++) {
            const x = i * xStep;
            const y = H - ((scores[i] - minS) / (maxS - minS)) * H;
            const clampY = Math.min(y, zeroY);
            ctx.lineTo(x, clampY);
        }
        ctx.lineTo((n - 1) * xStep, zeroY);
        ctx.closePath();
        ctx.fillStyle = 'rgba(92, 184, 92, 0.2)';
        ctx.fill();

        // Negative area (red)
        ctx.beginPath();
        ctx.moveTo(0, zeroY);
        for (let i = 0; i < n; i++) {
            const x = i * xStep;
            const y = H - ((scores[i] - minS) / (maxS - minS)) * H;
            const clampY = Math.max(y, zeroY);
            ctx.lineTo(x, clampY);
        }
        ctx.lineTo((n - 1) * xStep, zeroY);
        ctx.closePath();
        ctx.fillStyle = 'rgba(217, 83, 79, 0.2)';
        ctx.fill();
    }

    // Draw score line
    ctx.strokeStyle = '#e0e0e0';
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    for (let i = 0; i < n; i++) {
        const x = i * xStep;
        const y = H - ((scores[i] - minS) / (maxS - minS)) * H;
        if (i === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
    }
    ctx.stroke();

    // Draw current score dot
    if (n > 0) {
        const lastX = (n - 1) * xStep;
        const lastY = H - ((scores[n - 1] - minS) / (maxS - minS)) * H;
        ctx.fillStyle = current >= 0 ? '#5cb85c' : '#d9534f';
        ctx.beginPath();
        ctx.arc(lastX, lastY, 3, 0, Math.PI * 2);
        ctx.fill();
    }
}

async function fetchState() {
    const res = await fetch('/api/state');
    const data = await res.json();
    gameMode = data.mode;
    humanColor = data.human_color;
    renderBoard(data);
}

async function onCellClick(r, c) {
    if (!boardState) return;
    if (boardState.game_result) return;

    // In random_vs_random mode, clicks do nothing
    if (gameMode === 'random_vs_random') return;

    // Only allow clicks when it's human's turn
    if (boardState.side_to_move !== humanColor) return;

    // Check if clicking a legal target
    const target = legalMoves.find(m => m.to[0] === r && m.to[1] === c);
    if (target && selectedSq) {
        // Check if both promote and non-promote options exist
        const promoOption = legalMoves.find(m => m.to[0] === r && m.to[1] === c && m.promotion);
        const noPromoOption = legalMoves.find(m => m.to[0] === r && m.to[1] === c && !m.promotion);
        if (promoOption && noPromoOption) {
            // Ask user
            pendingPromo = {from: selectedSq, to: [r, c]};
            const piece = boardState.board[selectedSq[0]][selectedSq[1]];
            document.getElementById('promo-text').textContent =
                `${piece.name} (${piece.piece}) captures and can promote.`;
            document.getElementById('promo-dialog').classList.add('show');
            document.getElementById('overlay').classList.add('show');
            return;
        }
        await makeMove(selectedSq[0], selectedSq[1], r, c, target.promotion);
        return;
    }

    // Select a piece
    const piece = boardState.board[r][c];
    if (piece && piece.color === humanColor) {
        selectedSq = [r, c];
        // Fetch legal moves for this piece
        const res = await fetch(`/api/moves?r=${r}&c=${c}`);
        const data = await res.json();
        legalMoves = data.moves || [];
        renderBoard(boardState);
        // Show piece info
        showPieceInfo(piece.piece);
    } else {
        selectedSq = null;
        legalMoves = [];
        renderBoard(boardState);
    }
}

async function onCellHover(r, c) {
    if (!boardState) return;
    const piece = boardState.board[r][c];
    if (piece) {
        showPieceInfo(piece.piece);
    }
}

async function showPieceInfo(abbrev) {
    const res = await fetch(`/api/piece-info?abbrev=${encodeURIComponent(abbrev)}`);
    const info = await res.json();
    let html = `<div class="piece-name">${info.name}</div>`;
    html += `<div class="piece-detail">Abbrev: ${info.abbrev}</div>`;
    html += `<div class="piece-detail">Value: ${info.value}</div>`;
    if (info.promotes_to) html += `<div class="piece-detail">Promotes to: ${info.promotes_to}</div>`;
    html += `<div class="piece-detail">Slides: ${info.slide_directions} dirs, Jumps: ${info.jump_destinations}</div>`;
    if (info.specials.length > 0) html += `<div class="piece-detail">Special: ${info.specials.join(', ')}</div>`;
    document.getElementById('piece-info-content').innerHTML = html;
}

async function doPromo(yes) {
    document.getElementById('promo-dialog').classList.remove('show');
    document.getElementById('overlay').classList.remove('show');
    if (pendingPromo) {
        await makeMove(pendingPromo.from[0], pendingPromo.from[1],
                       pendingPromo.to[0], pendingPromo.to[1], yes);
        pendingPromo = null;
    }
}

async function makeMove(fr, fc, tr, tc, promotion) {
    const res = await fetch('/api/move', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({from: [fr, fc], to: [tr, tc], promotion})
    });
    const data = await res.json();
    if (data.ok) {
        lastMove = {from: [fr, fc], to: [tr, tc]};
        selectedSq = null;
        legalMoves = [];
        renderBoard(data);
        // Trigger AI response after short delay
        if (!data.game_result && gameMode === 'human_vs_random') {
            setTimeout(aiMove, 300);
        }
    }
}

async function aiMove() {
    if (boardState && boardState.game_result) return;
    const res = await fetch('/api/ai-move', {method: 'POST'});
    const data = await res.json();
    if (data.ok && data.last_move) {
        lastMove = data.last_move;
        selectedSq = null;
        legalMoves = [];
        renderBoard(data);
    }
}

async function newGame() {
    const mode = document.getElementById('mode-select').value;
    const color = parseInt(document.getElementById('color-select').value);
    stopAuto();
    lastMove = null;
    selectedSq = null;
    legalMoves = [];
    const res = await fetch('/api/new-game', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({mode, human_color: color})
    });
    await fetchState();

    // If human plays White, trigger AI first move
    if (mode === 'human_vs_random' && color === 1) {
        setTimeout(aiMove, 300);
    }
}

async function undoMove() {
    await fetch('/api/undo', {method: 'POST'});
    lastMove = null;
    selectedSq = null;
    legalMoves = [];
    await fetchState();
}

function toggleAuto() {
    if (autoPlay) {
        stopAuto();
    } else {
        startAuto();
    }
}

function startAuto() {
    autoPlay = true;
    document.getElementById('auto-btn').classList.add('active');
    document.getElementById('auto-btn').textContent = 'Stop';
    autoTick();
}

function stopAuto() {
    autoPlay = false;
    if (autoTimer) clearTimeout(autoTimer);
    autoTimer = null;
    document.getElementById('auto-btn').classList.remove('active');
    document.getElementById('auto-btn').textContent = 'Auto Play';
}

async function autoTick() {
    if (!autoPlay) return;
    if (boardState && boardState.game_result) { stopAuto(); return; }

    const mode = document.getElementById('mode-select').value;
    if (mode === 'random_vs_random') {
        await aiMove();
    } else if (mode === 'human_vs_random') {
        // Only auto-move if it's AI's turn
        if (boardState && boardState.side_to_move !== humanColor) {
            await aiMove();
        }
    }

    const speed = parseInt(document.getElementById('speed').value);
    document.getElementById('speed-label').textContent = speed + 'ms';
    autoTimer = setTimeout(autoTick, speed);
}

// Speed slider update
document.getElementById('speed').addEventListener('input', () => {
    document.getElementById('speed-label').textContent =
        document.getElementById('speed').value + 'ms';
});

// Initialize
buildBoard();
fetchState();
</script>

</body>
</html>
"""


# ============================================================
# Main
# ============================================================
def main():
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
    server = HTTPServer(('0.0.0.0', port), GameHandler)
    server.daemon_threads = True
    print(f"Taikyoku Shogi Web GUI")
    print(f"Open http://localhost:{port} in your browser")
    print(f"Press Ctrl+C to stop")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nShutting down...")
        server.shutdown()


if __name__ == '__main__':
    main()