-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_search.py
2048 lines (1924 loc) · 90 KB
/
game_search.py
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
import string, random, sys, math, copy, time
import config
from const import *
from utils import *
from types import *
from chain import Chain
from board import Board
from pos_cache import *
class SearchAborted(Exception): pass
class SearchNode:
def __init__(self):
self.parent = None
self.children = []
self.move = None
self.counts = []
class PNSearchNode(SearchNode):
def __init__(self, type):
SearchNode.__init__(self)
self.type = type
self.move = PASS_MOVE
self.expanded = False
self.value = None
self.proof = None
self.disproof = None
self.lambda_generator = None
class GameSearch:
def __init__(self):
self.node_count = 0
#reading shadow for caching local reads
#reading shadow for each read, key is type of reading and origin of block
self.reading_shadow = {}
self.lambda_sorted_moves_history = {}
#if PASS_MOVE: destroy shadows, other: create shadow for that block origin
self.current_shadow_origin = PASS_MOVE
self.shadow_only_neighbour = False
#what points on goban have shadow
#value is dictionary of origins of blocks that can be used to retrieve actual shadow from self.reading_shadow
self.reading_shadow_goban = {}
self.use_tactics = config.use_tactics
self.use_lambda = config.use_lambda
self.use_ld_search = config.use_ld_search
if self.use_lambda:
self.shadow_only_neighbour = True
self.target_blocks = []
def last_captures(self):
captures = []
if self.undo_history:
for name, color, pos in self.undo_history[-1]:
if name=="change_block_color":
captures = captures + self.current_board.blocks[pos].stones.keys()
captures.sort()
return captures
def search_key(self):
captures = self.last_captures()
return self.current_board.side, self.current_board.key(), tuple(captures)
def check_shadow_consistency(self):
for type_and_origin in self.reading_shadow:
for pos in self.reading_shadow[type_and_origin]:
if not self.reading_shadow_goban[pos][type_and_origin]:
raise KeyError, (pos, type_and_origin)
for pos in self.reading_shadow_goban:
for type_and_origin in self.reading_shadow_goban[pos]:
if not self.reading_shadow[type_and_origin][pos]:
raise KeyError, (pos, type_and_origin)
def create_shadow(self, shadow_dict):
reading_type = self.current_reading_type
if not reading_type:
return
origin = self.current_shadow_origin
shadow_key = reading_type, origin
if shadow_key not in self.reading_shadow:
self.reading_shadow[shadow_key] = {}
shadow = self.reading_shadow[shadow_key]
for pos in shadow_dict:
shadow[pos] = True
## if not self.use_lambda:
## if pos not in self.reading_shadow_goban:
## self.reading_shadow_goban[pos] = {}
## self.reading_shadow_goban[pos][origin] = origin
def create_shadow_goban(self, shadow_dict):
reading_type = self.current_reading_type
origin = self.current_shadow_origin
for pos in shadow_dict:
if pos not in self.reading_shadow_goban:
self.reading_shadow_goban[pos] = {}
self.reading_shadow_goban[pos][reading_type, origin] = True
def destroy_this_shadow_only(self, key):
shadow = self.reading_shadow[key]
del self.reading_shadow[key]
for pos2 in shadow:
if pos2 not in self.reading_shadow_goban:
continue
del self.reading_shadow_goban[pos2][key]
if not self.reading_shadow_goban[pos2]:
del self.reading_shadow_goban[pos2]
def destroy_shadow(self, shadow_dict):
for pos in shadow_dict:
if pos in self.reading_shadow_goban:
key_list = self.reading_shadow_goban[pos].keys()
for key in key_list:
self.destroy_this_shadow_only(key)
def update_shadow(self, move):
if self.current_shadow_origin==NO_MOVE or move==PASS_MOVE:
return
#collect shadow intersections
cboard = self.current_board
shadow_dict = {}
shadow_dict[move] = True
for pos in cboard.iterate_neighbour(move):
block = cboard.blocks[pos]
if block.color in (WHITE, BLACK) and not self.shadow_only_neighbour:
shadow_dict.update(block.stones)
shadow_dict.update(block.neighbour)
else:
shadow_dict[pos] = True
if self.current_shadow_origin==PASS_MOVE:
self.destroy_shadow(shadow_dict)
else:
self.create_shadow(shadow_dict)
def all_block_tactic_status(self, pos):
"""normal tactical and heuristical tactical analysis"""
cboard = self.current_board
block = cboard.blocks[pos]
origin = block.get_origin()
if config.debug_flag and origin!=pos:
dprintnl(move_as_string(pos), "--origin->", move_as_string(origin))
result = self.block_tactic_status(origin)
if self.use_ld_search and result[0] in (TACTICALLY_UNKNOWN, TACTICALLY_CRITICAL):
result_dict = self.heuristical_dead_analysis(origin)
if origin in result_dict:
result = result_dict[origin]
return result
def block_tactic_status(self, pos):
"""capture, life and death tactical status"""
cboard = self.current_board
block = cboard.blocks[pos]
origin = block.get_origin()
## if origin in self.reading_shadow:
## try:
## result0 = self.reading_shadow[origin][origin]
## try:
## a, b, c = result0
## if config.use_shadow_cache:
## return result0
## except TypeError:
## result0 = None
## except KeyError:
## result0 = None
## else:
## result0 = None
status, attack_move, defend_move = self.block_capture_tactic_status(pos)
## all_reading_shadow = self.reading_shadow.get(origin, {})
if self.use_ld_search and status==TACTICALLY_UNKNOWN:
status, attack_move, defend_move = self.block_life_and_death_status(pos)
## (status, attack_move, defend_move), ld_shadow = self.block_life_and_death_status(pos)
## all_reading_shadow.update(ld_shadow)
#if origin in self.reading_shadow:
# del self.reading_shadow[origin]
result = status, attack_move, defend_move
## self.reading_shadow[origin] = all_reading_shadow
## self.reading_shadow[origin][origin] = result
if config.debug_flag:
dprintnl("all", move_as_string(pos), result[0], move_list_as_string(result[1:3]))
self.current_shadow_origin = PASS_MOVE
return result
def block_life_and_death_status(self, pos):
cboard = self.current_board
block = cboard.blocks[pos]
block_color = cboard.blocks[pos].color
origin = block.get_origin()
## combined_shadow = {}
life_result = self.block_life_or_death_status(pos, "life")
## combined_shadow.update(shadow = self.reading_shadow.get(origin, {}))
death_result = self.block_life_or_death_status(pos, "death")
death_shadow_moves = self.last_shadow.keys()
## combined_shadow.update(shadow = self.reading_shadow.get(origin, {}))
attack_move = death_result[1]
defense_move = life_result[1]
if life_result[0] >= 1.0:
if death_result[0] >= 1.0:
status = TACTICALLY_CRITICAL
else:
status = TACTICALLY_LIVE
else:
if death_result[0] >= 1.0:
status = TACTICALLY_DEAD
result = self.block_death_defense(origin, attack_move, death_shadow_moves)
if result[0] < 1.0:
defend_move = result[1]
status = TACTICALLY_CRITICAL
else:
status = TACTICALLY_UNKNOWN
result = status, attack_move, defense_move
if config.debug_flag:
dprintnl("l&d", move_as_string(pos), result[0], move_list_as_string(result[1:3]))
return result #, combined_shadow
def block_life_or_death_status(self, pos, reading_type="death", defense_move=PASS_MOVE):
"""analyse life and death status for block
reading_type: "death" or "life"
"""
cboard = self.current_board
self.life_death_reading_type = reading_type
self.current_reading_type = reading_type
if defense_move!=PASS_MOVE:
self.current_reading_type = self.current_reading_type + " " + move_as_string(defense_move)
if cboard.assumed_unconditional_alive_list:
self.current_reading_type = self.current_reading_type + " " + move_list_as_string(cboard.assumed_unconditional_alive_list)
saved_block_status_dict = cboard.save_block_status()
block = cboard.blocks[pos]
block_color = cboard.blocks[pos].color
origin = block.get_origin()
if reading_type=="death":
self.defender_color = block_color
else:
self.defender_color = other_side[block_color]
self.current_shadow_origin_color = block_color
if config.debug_tactics:
dprintnl(self.move_as_string(origin), reading_type)
dprintnl(self.current_board.as_string_with_unconditional_status())
#setup search for life&death search
time0 = time.time()
node_count0 = self.node_count
self.lambda0 = self.life_death_connection_cut_lambda0
self.goal_achieved = self.unconditional_status
self.find_relevant_moves = self.find_relevant_eye_moves
original_default_nodes = config.lambda_node_limit
if block.size() < 3:
config.lambda_node_limit = config.lambda_slow_node_limit
elif block.size() < 6:
config.lambda_node_limit = config.lambda_slow_node_limit * 3
else:
config.lambda_node_limit = config.lambda_slow_node_limit * 10
original_slow_limit = config.lambda_node_limit
self.lambda_search_cache = {}
self.lambda_shadow = None
self.next_lambda_recursion = 0
result = self.lambda_search(origin)
if config.debug_tactics:
self.print_pn_statistics()
config.lambda_node_limit = original_default_nodes
cboard.restore_block_status(saved_block_status_dict)
#if origin in self.reading_shadow:
# del self.reading_shadow[origin]
if config.debug_flag:
if result[0] >= 1.0 and reading_type=="death":
dprintnl("!"*60)
if defense_move!=PASS_MOVE:
defense_string = "defense " + move_as_string(defense_move)
else:
defense_string = ""
if self.node_count-node_count0==0:
dprintsp("(")
dprintnl(reading_type, move_as_string(pos), result[0], move_list_as_string(result[1:3]), self.node_count-node_count0, original_slow_limit, defense_string, "%.3fs" % (time.time() - time0,))
return result
def block_death_defense(self, pos, attack_move, death_shadow_moves):
cboard = self.current_board
block = cboard.blocks[pos]
block_color = cboard.blocks[pos].color
origin = block.get_origin()
result = [1.0, attack_move]
move_list = self.lambda_sort_move_candidates(death_shadow_moves, [], attack_move)
if block_color==other_side[cboard.side]:
pass_made = True
self.make_move(PASS_MOVE)
else:
pass_made = False
defense_move = PASS_MOVE
for move in move_list:
if self.make_move(move):
if config.debug_tactics:
dprintnl("try defence:", self.move_as_string(move))
## backup_shadow = self.reading_shadow[origin]
result = self.block_life_or_death_status(pos, "death", defense_move=move)
## self.reading_shadow[origin] = backup_shadow
self.undo_move()
if result[0]<1.0:
if config.debug_tactics:
dprintnl("found defence:", self.move_as_string(move))
defense_move = move
break
if pass_made:
self.undo_move()
return result[0], defense_move
def block_connection_status(self, pos1, pos2):
"""analyse connection status for block1 and block2
"""
cboard = self.current_board
reading_type = "connection"
self.current_reading_type = reading_type + move_list_as_string((pos1, pos2))
saved_block_status_dict = cboard.save_block_status()
block = cboard.blocks[pos1]
block_color = cboard.blocks[pos1].color
self.defender_color = other_side[block_color]
self.current_shadow_origin_color = block_color
if config.debug_tactics:
dprintnl(move_list_as_string((pos1, pos2)), reading_type)
dprintnl(self.current_board)
#setup search for life&death search
time0 = time.time()
node_count0 = self.node_count
self.lambda0 = self.life_death_connection_cut_lambda0
self.goal_achieved = self.connection_status
self.find_relevant_moves = self.find_connection_moves
original_default_nodes = config.lambda_node_limit
config.lambda_node_limit = config.lambda_connection_node_limit
original_connection_limit = config.lambda_node_limit
self.lambda_search_cache = {}
self.lambda_shadow = None
self.next_lambda_recursion = 0
self.connection_pos2 = pos2
result = self.lambda_search(pos1)
if config.debug_tactics:
self.print_pn_statistics()
if result[0]>=1.0:
connect_move = result[1]
moves = self.lambda_sort_move_candidates(self.last_shadow.keys(), [], connect_move)
if block_color==cboard.side:
pass_made = True
self.make_move(PASS_MOVE)
else:
pass_made = False
for cut_move in moves:
if self.make_move(cut_move):
if config.debug_tactics:
dprintnl("try cut:", self.move_as_string(cut_move))
self.current_reading_type = "cut " + move_list_as_string((pos1, pos2, cut_move))
result = self.lambda_search(pos1)
self.undo_move()
if result[0]<1.0:
break
if pass_made:
self.undo_move()
if result[0]>=1.0:
result = TACTICALLY_LIVE, connect_move, PASS_MOVE
else:
result = TACTICALLY_CRITICAL, connect_move, cut_move
else:
result = TACTICALLY_UNKNOWN, result[1], PASS_MOVE
config.lambda_node_limit = original_default_nodes
cboard.restore_block_status(saved_block_status_dict)
#if origin in self.reading_shadow:
# del self.reading_shadow[origin]
if config.debug_flag:
if self.node_count-node_count0==0:
dprintsp("(")
dprintnl(reading_type, move_list_as_string((pos1, pos2)), result[0], move_list_as_string(result[1:3]), self.node_count-node_count0, original_connection_limit, "%.3fs" % (time.time() - time0,))
return result
def block_cut_status(self, origin_blocks, cutting_points):
"""analyse cutting status for origin_blocks using cutting_points
seems to be too inefficient to be useful :-(
will just use more limited static miai analysis for now
"""
cboard = self.current_board
reading_type = "cut"
str_args = move_list_as_string(origin_blocks) + " : " + move_list_as_string(cutting_points)
base_current_reading_type = reading_type + str_args
saved_block_status_dict = cboard.save_block_status()
pos1 = origin_blocks[0]
block = cboard.blocks[pos1]
block_color = cboard.blocks[pos1].color
self.defender_color = other_side[block_color]
self.current_shadow_origin_color = block_color
if config.debug_tactics:
dprintnl(str_args, reading_type)
dprintnl(self.current_board)
#setup search for life&death search
time0 = time.time()
node_count0 = self.node_count
self.lambda0 = self.life_death_connection_cut_lambda0
self.origin_blocks = origin_blocks
self.goal_achieved = self.cut_status
self.cutting_points = cutting_points
self.find_relevant_moves = self.find_cut_moves
original_default_nodes = config.lambda_node_limit
config.lambda_node_limit = config.lambda_connection_node_limit
original_connection_limit = config.lambda_node_limit
self.lambda_search_cache = {}
self.lambda_shadow = None
self.next_lambda_recursion = 0
result = [0.0, PASS_MOVE]
for connect_move in cutting_points:
if block_color==cboard.side:
pass_made = True
self.make_move(PASS_MOVE)
else:
pass_made = False
if self.make_move(connect_move):
if config.debug_tactics:
dprintnl("try connect:", self.move_as_string(connect_move))
self.current_reading_type = base_current_reading_type + " : " + move_as_string(connect_move)
result = self.lambda_search(pos1)
self.undo_move()
if config.debug_tactics:
self.print_pn_statistics()
if result[0]<1.0:
break
if pass_made:
self.undo_move()
if result[0]>=1.0:
result = TACTICALLY_LIVE, result[1], PASS_MOVE
else:
result = TACTICALLY_UNKNOWN, result[1], PASS_MOVE
config.lambda_node_limit = original_default_nodes
cboard.restore_block_status(saved_block_status_dict)
#if origin in self.reading_shadow:
# del self.reading_shadow[origin]
if config.debug_flag:
if self.node_count-node_count0==0:
dprintsp("(")
dprintnl(reading_type, str_args, result[0], move_list_as_string(result[1:3]), self.node_count-node_count0, original_connection_limit, "%.3fs" % (time.time() - time0,))
return result
def count_chain_liberties(self, chain):
cboard = self.current_board
liberties_dict = {}
for block in chain.blocks.values():
for liberty in cboard.list_block_liberties(block):
liberties_dict[liberty] = True
chain.liberty_count = len(liberties_dict)
def common_dead_neighbour(self, block1, block2):
cboard = self.current_board
for block3 in cboard.iterate_neighbour_blocks(block1):
if block3.color==other_side[block1.color] and block3.status==TACTICALLY_DEAD:
for block4 in cboard.iterate_neighbour_blocks(block2):
if block4==block3:
return True
return False
def form_chains_tactical(self):
"""blocks are connected if:
1) 2 or more common liberties
2) shared dead block
3) 1 common liberty and tactical search says they are connected
"""
self.chains = []
cboard = self.current_board
for block in cboard.iterate_blocks(BLACK+WHITE):
if not hasattr(block, "status"):
block.status = TACTICALLY_UNKNOWN
block.chain = None
for color in (BLACK, WHITE):
block_origin_list = []
for block in cboard.iterate_blocks(color):
block_origin_list.append(block.get_origin())
for origin1 in block_origin_list:
block1 = cboard.blocks[origin1]
if block1.chain: continue
chain = Chain()
self.chains.append(chain)
chain.add_block(block1)
block_added = True
while block_added:
block_added = False
for origin2 in block_origin_list:
block2 = cboard.blocks[origin2]
if block2.chain or block2.color!=block1.color:
continue
for origin3 in chain.blocks.keys():
block3 = cboard.blocks[origin3]
common_liberty_count = len(cboard.block_connection_status(origin2, origin3))
if common_liberty_count>=2 or self.common_dead_neighbour(block2, block3):
chain.add_block(block2)
block_added = True
break
elif common_liberty_count==1:
result = self.block_connection_status(origin2, origin3)
self.refresh_all_chain_pointers()
block1 = cboard.blocks[origin1]
block2 = cboard.blocks[origin2]
#self.check_chains(require_complete = False)
if result[0]==TACTICALLY_LIVE:
chain.add_block(block2)
block_added = True
break
def chain_propagate_live_status(self, chain):
"""propagate UNCONDITIONALLY_LIVE, TACTICALLY_LIVE status to connected TACTICALLY_UNKNOWN blocks"""
has_live_block = False
chain.has_unknown_block = False
for block in chain.blocks.values():
if block.status==UNCONDITIONAL_UNKNOWN:
block.status = TACTICALLY_UNKNOWN
if block.status in (UNCONDITIONAL_LIVE, TACTICALLY_LIVE):
has_live_block = True
elif block.status in (TACTICALLY_UNKNOWN, TACTICALLY_CRITICAL):
chain.has_unknown_block = True
if has_live_block:
for block in chain.blocks.values():
if block.status == TACTICALLY_UNKNOWN:
block.status = TACTICALLY_LIVE
chain.has_unknown_block = False
def add_cutting_moves(self, target_origin, surrounding_origins):
cboard = self.current_board
cut_color = cboard.goban[surrounding_origins[0]]
surround_lib_dict = {}
for pos in surrounding_origins:
block = cboard.blocks[pos]
for lib in cboard.list_block_liberties(block):
surround_lib_dict[lib] = True
for pos in surround_lib_dict:
if cboard.goban[pos]!=EMPTY:
continue
for pos2 in cboard.iterate_neighbour(pos):
if pos not in surround_lib_dict:
continue
if cboard.goban[pos2]!=EMPTY:
continue
x1, y1 = pos
x2, y2 = pos2
ok = False
if x1==x2:
if x1==1:
ok = cboard.goban[x1+1, y1]==cboard.goban[x2+1, y2]==cut_color
elif x1==cboard.size:
ok = cboard.goban[x1-1, y1]==cboard.goban[x2-1, y2]==cut_color
else:
ok = cboard.goban[x1+1, y1]==cboard.goban[x2+1, y2]==cut_color and \
cboard.goban[x1-1, y1]==cboard.goban[x2-1, y2]==cut_color
else:
if y1==1:
ok = cboard.goban[x1, y1+1]==cboard.goban[x2, y2+1]==cut_color
elif y1==cboard.size:
ok = cboard.goban[x1, y1-1]==cboard.goban[x2, y2-1]==cut_color
else:
ok = cboard.goban[x1, y1+1]==cboard.goban[x2, y2+1]==cut_color and \
cboard.goban[x1, y1-1]==cboard.goban[x2, y2-1]==cut_color
if not ok:
continue
if cboard.side!=cut_color:
self.make_move(PASS_MOVE)
if taxi_distance(pos, target_origin) < taxi_distance(pos2, target_origin):
move = pos2
else:
move = pos
## print cboard
## print move_as_string(move)
self.make_move(move)
## print cboard
## stop()
def refresh_all_chain_pointers(self):
cboard = self.current_board
for block in cboard.iterate_blocks(BLACK+WHITE):
block.chain = None
for chain in self.chains:
for origin in chain.blocks:
block = cboard.blocks[origin]
chain.blocks[origin] = block
block.chain = chain
def chains_as_sgf(self):
current_letter = "a"
label_dict = {}
for chain in self.chains:
for block in chain.blocks.values():
for stone in block.stones:
label_dict[stone] = current_letter
current_letter = chr(ord(current_letter) + 1)
if current_letter > "z":
current_letter = "A"
return self.current_board.as_sgf_with_labels(label_dict)
def check_chains(self, require_complete=True):
cboard = self.current_board
for chain in self.chains:
for origin in chain.blocks:
if cboard.blocks[origin]!=chain.blocks[origin]:
raise ValueError, "not pointing to right block"
for block in cboard.iterate_blocks(BLACK+WHITE):
if not block.chain:
if require_complete:
raise ValueError, "no chain for block"
else:
continue
for chain in self.chains:
if block.get_origin() in chain.blocks:
break
else:
raise ValueError, "block not found in any chains"
def heuristical_dead_analysis(self, one_block_pos = PASS_MOVE):
"""
1) normal analysis
2) store block status
3) connection analysis
4) propagate UNCONDITIONALLY_LIVE, TACTICALLY_LIVE status to connected TACTICALLY_UNKNOWN blocks
5) count total liberties for all chains (combine liberties to dict and count size)
6) go trough all chains that are TACTICALLY_UNKNOWN
7) reset assumed_unconditional_alive_list
8) search for neighbour opponent chains
9) add all TACTICALLY_LIVE blocks to assumed_unconditional_alive_list
10) if opponent chain has 2 more liberties, add all TACTICALLY_UNKNOWN to assumed_unconditional_alive_list
11) do death analysis for biggest inside block
12) add result to result_list
13) restore block status
14) set block status from result_list
"""
if config.debug_flag:
dprintnl("")
dprintnl("START HEURISTICAL ANALYSIS")
cboard = self.current_board
if one_block_pos==PASS_MOVE:
one_block_pos = None
else:
one_block_pos = cboard.blocks[one_block_pos].get_origin()
saved_block_status_dict = cboard.save_block_status()
self.form_chains_tactical()
if (config.debug_flag and not one_block_pos) or config.debug_tactics:
dprintnl(self.chains_as_sgf())
#self.check_chains()
for chain in self.chains:
self.chain_propagate_live_status(chain)
self.count_chain_liberties(chain)
result_dict = {}
for chain in self.chains:
if one_block_pos:
if one_block_pos not in chain.blocks:
continue
elif not chain.has_unknown_block:
continue
cboard.assumed_unconditional_alive_list = []
#search for neighbour opponent chains
neighbour_chains = {}
for block in chain.blocks.values():
for block2 in cboard.iterate_neighbour_blocks(block):
if block2.color==EMPTY:
continue
chain2 = block2.chain
chain2_origin = chain2.get_origin()
neighbour_chains[chain2_origin] = chain2
# add all TACTICALLY_LIVE blocks to assumed_unconditional_alive_list
# if opponent chain has 2 more liberties, add all TACTICALLY_UNKNOWN to assumed_unconditional_alive_list
for chain2 in neighbour_chains.values():
liberty_count_ok = chain2.liberty_count >= chain.liberty_count + 2
for block2 in chain2.blocks.values():
if block2.status==TACTICALLY_LIVE or \
(block2.status==TACTICALLY_UNKNOWN and liberty_count_ok):
cboard.assumed_unconditional_alive_list.append(block2.get_origin())
cboard.assumed_unconditional_alive_color = block2.color
blocks_todo = {}
if one_block_pos:
blocks_todo[one_block_pos] = True
else:
for origin, block in chain.blocks.items():
if block.status in (TACTICALLY_UNKNOWN, TACTICALLY_CRITICAL):
blocks_todo[origin] = True
while blocks_todo:
biggest_block = None
for origin in blocks_todo:
block = cboard.blocks[origin]
if biggest_block==None or block.size() > biggest_block.size():
biggest_block = block
origin = biggest_block.get_origin()
del blocks_todo[origin]
if cboard.assumed_unconditional_alive_list:
saved_block_status_dict2 = cboard.save_block_status()
#do death analysis for biggest inside block
node_count0 = self.node_count
current_history_len = len(self.move_history)
self.current_shadow_origin = NO_MOVE
self.add_cutting_moves(origin, cboard.assumed_unconditional_alive_list)
## if move_as_string(origin)=="B12":
## print "?!?!?!"
## print cboard
death_result = self.block_life_or_death_status(origin, "death")
death_shadow_moves = self.last_shadow.keys()
if death_result[0] >= 1.0:
if death_result[0] >= 1.0:
dprintnl("?"*60)
attack_move = death_result[1]
result = self.block_death_defense(origin, attack_move, death_shadow_moves)
if result[0] < 1.0:
defend_move = result[1]
status = TACTICALLY_CRITICAL
else:
defend_move = PASS_MOVE
status = TACTICALLY_DEAD
result_dict[origin] = status, attack_move, defend_move
if self.node_count-node_count0==0:
dprintsp("(")
if config.debug_flag:
dprintnl("heuristical death", move_as_string(origin), status, move_as_string(attack_move), move_as_string(defend_move), self.node_count-node_count0)
else:
if self.node_count-node_count0==0:
dprintsp("(")
if config.debug_flag:
dprintnl("heuristical death", move_as_string(origin), TACTICALLY_UNKNOWN, self.node_count-node_count0)
self.current_shadow_origin = NO_MOVE
while len(self.move_history) > current_history_len:
self.undo_move()
cboard.restore_block_status(saved_block_status_dict2)
self.refresh_all_chain_pointers()
else:
blocks_todo = {}
cboard.assumed_unconditional_alive_list = []
cboard.restore_block_status(saved_block_status_dict)
self.current_shadow_origin = PASS_MOVE
return result_dict
def search_log2tree(self, search_log):
root_node = node = SearchNode()
color = self.current_board.side
for entry, node_count in search_log:
node.counts.append(node_count)
if entry==UNDO_MOVE:
node = node.parent
else:
parent = node
node = SearchNode()
node.move = entry
node.color = color
node.parent = parent
parent.children.append(node)
color = other_side[color]
return root_node
def sgf_trace(self, move):
if config.sgf_trace_tactics: # and not self.next_lambda_recursion:
self.search_log.append((move, self.node_count))
def tree2sgf(self, tree):
if tree.move==None:
s = ["(;GM[1]SZ[%i]RU[Chinese]" % self.size]
for i in range(len(self.move_history)):
if i%2:
color = ";W"
else:
color = ";B"
move = self.move_history[i]
sgf = move_as_sgf(move, self.size)
if move==PASS_MOVE:
s.append("%s[%s]" % (color, sgf))
else:
s.append("%s[%s]CR[%s]" % (color, sgf, sgf))
else:
if tree.color==WHITE:
color = ";W"
else:
color = ";B"
sgf = move_as_sgf(tree.move, self.size)
if tree.move==PASS_MOVE:
cr = ""
else:
cr = "CR[%s]" % sgf
s = ["%s[%s]%s" % (color, sgf, cr)]
#number following moves
i = 1
slabel = ["LB"]
slabel_dict = {}
scomment = ["C["]
for node in tree.children:
if node.move!=PASS_MOVE:
sgf_move = move_as_sgf(node.move, self.size)
if sgf_move in slabel_dict:
sgf = slabel_dict[sgf_move][:-1] + ","+str(i) + "]"
else:
sgf = "[%s:%s]" % (sgf_move, i)
slabel_dict[sgf_move] = sgf
else:
scomment.append("PASS:%s\n" % i)
i = i + 1
scomment.append("Counts: %s\n" % (tuple(tree.counts),))
if slabel_dict:
slabel = slabel + slabel_dict.values()
s.append(string.join(slabel, ""))
if len(scomment)>1:
scomment.append("]")
s.append(string.join(scomment, ""))
#add child nodes
if tree.children:
if len(tree.children)==1:
s.append(self.tree2sgf(tree.children[0]))
else:
for node in tree.children:
s.append("(" + self.tree2sgf(node) + ")")
if tree.move==None:
s.append(")")
return string.join(s, "\n")
def block_capture_tactic_status_sgf(self, pos):
old_sgf_trace_tactics = config.sgf_trace_tactics
config.sgf_trace_tactics = True
self.search_log = []
result = self.block_capture_tactic_status(pos)
tree = self.search_log2tree(self.search_log)
sgf_trace_fp = open("lambda_search.sgf", "w")
sgf_trace_fp.write(self.tree2sgf(tree))
sgf_trace_fp.close()
config.sgf_trace_tactics = old_sgf_trace_tactics
return result
def block_capture_tactic_status(self, pos):
cboard = self.current_board
block = cboard.blocks[pos]
block_color = cboard.blocks[pos].color
origin = block.get_origin()
liberties = cboard.list_block_liberties(block)
if 0 and origin in self.reading_shadow:
if self.use_lambda:
result0, self.block_extra_result = self.reading_shadow[origin][origin]
else:
result0 = self.reading_shadow[origin][origin]
if config.use_shadow_cache:
return result0
else:
result0 = None
time0 = time.time()
self.current_reading_type = "capture"
node_count0 = self.node_count
#backup_reading_shadow = copy.deepcopy(self.reading_shadow)
#backup_reading_shadow_goban = copy.deepcopy(self.reading_shadow_goban)
self.defender_color = self.current_shadow_origin_color = block_color
if config.debug_tactics:
dprintnl(self.move_as_string(origin), "capture")
dprintnl(self.current_board)
if self.use_lambda:
self.lambda0 = self.capture_lambda0
self.goal_achieved = self.captured
self.find_relevant_moves = self.find_relevant_liberties
self.block_extra_result = None
#result = self.lambda_n(origin, 1, 10001)
self.lambda_shadow = None
self.next_lambda_recursion = 0
self.alpha_beta_search_cache = {}
self.lambda_search_cache = {}
original_default_nodes = config.lambda_node_limit
#config.lambda_node_limit = default_nodes
result = self.lambda_search(origin)
default_nodes = self.danger_limit
#default_nodes = self.danger_limit
current_danger = self.pn_danger_ratio()
if config.debug_tactics:
self.print_pn_statistics()
if result[0]>=1.0:
attack_move = result[1]
moves = self.lambda_sort_move_candidates(self.last_shadow.keys(), liberties, attack_move)
if config.sgf_trace_tactics:
moves = []
if block_color==other_side[cboard.side]:
pass_made = True
self.make_move(PASS_MOVE)
else:
pass_made = False
for defend_move in moves:
if self.make_move(defend_move):
is_atari_move = ""
block2 = cboard.blocks[defend_move]
if cboard.block_liberties(block2)==1:
is_atari_move = "atari"
else:
for block3 in cboard.iterate_neighbour_blocks(block2):
if block3.color==cboard.side and cboard.block_liberties(block3)==1:
is_atari_move = "atari"
if is_atari_move:
config.lambda_node_limit = default_nodes * 2
else:
config.lambda_node_limit = default_nodes / 2
if config.debug_tactics:
dprintnl("try defence:", is_atari_move, self.move_as_string(defend_move))
## backup_shadow = self.reading_shadow[origin]
self.current_reading_type = "capture defense " + move_list_as_string((origin, defend_move))
result = self.lambda_search(origin)
## self.reading_shadow[origin] = backup_shadow
self.undo_move()
if result[0]<1.0:
break
if pass_made:
self.undo_move()
if result[0]>=1.0:
result = TACTICALLY_DEAD, attack_move, PASS_MOVE
else:
result = TACTICALLY_CRITICAL, attack_move, defend_move
else:
config.lambda_node_limit = default_nodes / 5
#check double threats...
if block_color==cboard.side:
pass_made = True
self.make_move(PASS_MOVE)
else:
pass_made = False
for pos2 in liberties:
search_this = False
for pos3 in cboard.iterate_neighbour(pos2):
block2 = cboard.blocks[pos3]
origin2 = block2.get_origin()
if origin2!=origin and block2.color==block_color:
search_this = True
break
if search_this and not config.sgf_trace_tactics:
if self.make_move(pos2):
#in case of ko initial reading from cache might have missed this
if cboard.goban[origin]==EMPTY:
self.undo_move()
result = TACTICALLY_CRITICAL, pos2, pos2
break
## backup_shadow0 = self.reading_shadow.get(pos2)
backup_current_shadow_origin_color = self.current_shadow_origin_color
self.defender_color = self.current_shadow_origin_color = cboard.goban[pos2]
self.current_reading_type = "capture double check " + self.move_as_string(pos2)
result0 = self.lambda_search(pos2)
self.defender_color = self.current_shadow_origin_color = backup_current_shadow_origin_color
## if backup_shadow0:
## self.reading_shadow[pos2] = backup_shadow0
## elif pos2 in self.reading_shadow:
## del self.reading_shadow[self.current_reading_type, pos2]
if result0[0]>=1.0:
if config.debug_tactics:
dprintnl("can't do double attack at:", self.move_as_string(pos2))
self.undo_move()
else:
if config.debug_tactics:
dprintnl("try double attack:", self.move_as_string(pos2))
## backup_shadow = self.reading_shadow[origin]
self.current_reading_type = "capture double attack1 " + self.move_as_string(origin)
result1 = self.lambda_search(origin)
if result1[0]>=1.0:
if config.debug_tactics:
dprintnl(self.move_as_string(origin), "was now critical, try:", self.move_as_string(origin2))
## backup_shadow2 = self.reading_shadow.get(origin2)
self.current_reading_type = "capture double attack2 " + self.move_as_string(origin2)
result2 = self.lambda_search(origin2)
if result1[0]>=1.0:
if config.debug_tactics:
dprintnl(self.move_as_string(origin2), "was also critical, try find common saving move")
block2 = cboard.blocks[origin]
attack_as_defense_moves_to_analyse = []
for block3 in cboard.iterate_neighbour_blocks(block):
if block3.color == other_side[block2.color]:
liberties3 = cboard.list_block_liberties(block3)
if len(liberties3)==1 and liberties3[0] not in attack_as_defense_moves_to_analyse:
attack_as_defense_moves_to_analyse.append(liberties3[0])
for move2 in attack_as_defense_moves_to_analyse:
if self.make_move(move2):
if config.debug_tactics:
dprintnl("group1:", self.move_as_string(origin), "try capture defense:", self.move_as_string(move2))
self.current_reading_type = "capture double defend1 " + self.move_as_string(origin)
result1_2 = self.lambda_search(origin)
if config.debug_tactics:
dprintnl("group2:", self.move_as_string(origin2), "try capture defense", self.move_as_string(move2))
self.current_reading_type = "capture double defend2 " + self.move_as_string(origin2)
result2_2 = self.lambda_search(origin2)
self.undo_move()
if result1_2[0] < 1.0 and result2_2[0] < 1.0:
if config.debug_tactics:
dprintnl(self.move_as_string(move2), "saves both")
result1 = result1_2
result2 = result2_2
else:
if config.debug_tactics:
dprintnl(self.move_as_string(move2), "doesn't work")
## if backup_shadow2:
## self.reading_shadow[origin2] = backup_shadow2
## elif origin2 in self.reading_shadow:
## del self.reading_shadow[self.current_reading_type, origin2]
## self.reading_shadow[origin] = backup_shadow
self.undo_move()
if result1[0]>=1.0 and result2[0]>=1.0:
result = TACTICALLY_CRITICAL, pos2, pos2
break
else: #no adjacent double attacks found
if 0 and current_danger>=0.3:
config.lambda_node_limit = default_nodes
moves = self.lambda_sort_move_candidates(self.last_shadow.keys(), liberties, result[1])
increase_move = PASS_MOVE
best_increase = 0
for attack_move in moves[:config.danger_move_limit]:
if self.make_move(attack_move):
if config.debug_tactics:
dprintnl("try danger increase:", move_as_string(attack_move))