-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.py
More file actions
944 lines (931 loc) · 53.1 KB
/
search.py
File metadata and controls
944 lines (931 loc) · 53.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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
import sys
import os
import re
import time
import math
import random
import json
import threading
import concurrent.futures
from http.server import HTTPServer, BaseHTTPRequestHandler
from shell_lite.runtime import *
# Initialize Runtime Helpers
builtins_map = get_builtins()
globals().update(builtins_map)
class DotDict(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
self[key] = value
STD_MODULES = get_std_modules()
# Wrap modules
for k, v in STD_MODULES.items():
if isinstance(v, dict): STD_MODULES[k] = DotDict(v)
# Async Executor
_executor = concurrent.futures.ThreadPoolExecutor()
# HTTP Server Support
GLOBAL_ROUTES = {}
GLOBAL_STATIC_ROUTES = {}
class ShellLiteHTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.handle_req()
def do_POST(self):
self.handle_req()
def handle_req(self):
path = self.path
# Static Routes
for prefix, folder in GLOBAL_STATIC_ROUTES.items():
if path.startswith(prefix):
clean_path = path[len(prefix):]
if clean_path.startswith('/'):
clean_path = clean_path[1:]
if clean_path == '': clean_path = 'index.html'
file_path = os.path.join(folder, clean_path)
if os.path.exists(file_path) and \
os.path.isfile(file_path):
self.send_response(200)
# Simple mime type guessing
if file_path.endswith('.css'):
settings = 'text/css'
elif file_path.endswith('.js'):
settings = 'application/javascript'
elif file_path.endswith('.html'):
settings = 'text/html'
else:
settings = 'application/octet-stream'
self.send_header('Content-type', settings)
self.end_headers()
with open(file_path, 'rb') as f:
self.wfile.write(f.read())
return
handler = GLOBAL_ROUTES.get(path)
if handler:
try:
res = handler()
self.send_response(200)
self.end_headers()
if res: self.wfile.write(str(res).encode())
else: self.wfile.write(b'OK')
except Exception as e:
self.send_response(500)
self.wfile.write(str(e).encode())
else:
self.send_response(404)
self.wfile.write(b'Not Found')
# --- Web DSL Support ---
class Tag:
def __init__(self, name, attrs=None):
self.name = name
self.attrs = attrs or {}
self.children = []
def add(self, child):
self.children.append(child)
def __str__(self):
attr_str = ''.join([f' {k}="{v}"' for k,v in self.attrs.items()])
inner = ''.join([str(c) for c in self.children])
if self.name in ('img', 'br', 'hr', 'input', 'meta', 'link'):
return f'<{self.name}{attr_str} />'
return f'<{self.name}{attr_str}>{inner}</{self.name}>'
class WebBuilder:
def __init__(self): self.stack = []
def push(self, tag):
if self.stack: self.stack[-1].add(tag)
self.stack.append(tag)
def pop(self): return self.stack.pop() if self.stack else None
def add_text(self, text):
if self.stack: self.stack[-1].add(text)
else: pass # Top level text?
_web_builder = WebBuilder()
class BuilderContext:
def __init__(self, tag): self.tag = tag
def __enter__(self):
_web_builder.push(self.tag)
return self.tag
def __exit__(self, *args): _web_builder.pop()
def _make_tag_fn(name):
def fn(*args):
attrs = {}
content = []
for arg in args:
if isinstance(arg, dict):
attrs.update(arg)
elif isinstance(arg, str) and '=' in arg and ' ' not in arg:
k, v = arg.split('=', 1)
attrs[k] = v
else:
content.append(arg)
t = Tag(name, attrs)
for c in content:
t.add(c)
return t
return fn
for t in ['div', 'p', 'h1', 'h2', 'h3', 'h4', 'span', 'a',
'img', 'button', 'input', 'form', 'ul', 'li',
'html', 'head', 'body', 'title', 'meta', 'link',
'script', 'style', 'br', 'hr']:
globals()[t] = _make_tag_fn(t)
# --- User Script ---
from constants import *
from moves import *
time = STD_MODULES['time']
from book import *
PAWN_PST = [0, 0, 0, 0, 0, 0, 0, 0, 50, 50, 50, 50, 50, 50, 50, 50, 10, 10, 20, 30, 30, 20, 10, 10, 5, 5, 10, 25, 25, 10, 5, 5, 0, 0, 0, 20, 20, 0, 0, 0, 5, (0 - 5), (0 - 10), 0, 0, (0 - 10), (0 - 5), 5, 5, 10, 10, (0 - 20), (0 - 20), 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0]
KNIGHT_PST = [(0 - 50), (0 - 40), (0 - 30), (0 - 30), (0 - 30), (0 - 30), (0 - 40), (0 - 50), (0 - 40), (0 - 20), 0, 0, 0, 0, (0 - 20), (0 - 40), (0 - 30), 0, 10, 15, 15, 10, 0, (0 - 30), (0 - 30), 5, 15, 20, 20, 15, 5, (0 - 30), (0 - 30), 0, 15, 20, 20, 15, 0, (0 - 30), (0 - 30), 5, 10, 15, 15, 10, 5, (0 - 30), (0 - 40), (0 - 20), 0, 5, 5, 0, (0 - 20), (0 - 40), (0 - 50), (0 - 40), (0 - 30), (0 - 30), (0 - 30), (0 - 30), (0 - 40), (0 - 50)]
BISHOP_PST = [(0 - 20), (0 - 10), (0 - 10), (0 - 10), (0 - 10), (0 - 10), (0 - 10), (0 - 20), (0 - 10), 0, 0, 0, 0, 0, 0, (0 - 10), (0 - 10), 0, 5, 10, 10, 5, 0, (0 - 10), (0 - 10), 5, 5, 10, 10, 5, 5, (0 - 10), (0 - 10), 0, 10, 10, 10, 10, 0, (0 - 10), (0 - 10), 10, 10, 10, 10, 10, 10, (0 - 10), (0 - 10), 5, 0, 0, 0, 0, 5, (0 - 10), (0 - 20), (0 - 10), (0 - 10), (0 - 10), (0 - 10), (0 - 10), (0 - 10), (0 - 20)]
ROOK_PST = [0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 10, 10, 10, 10, 5, (0 - 5), 0, 0, 0, 0, 0, 0, (0 - 5), (0 - 5), 0, 0, 0, 0, 0, 0, (0 - 5), (0 - 5), 0, 0, 0, 0, 0, 0, (0 - 5), (0 - 5), 0, 0, 0, 0, 0, 0, (0 - 5), (0 - 5), 0, 0, 0, 0, 0, 0, (0 - 5), 0, 0, 0, 5, 5, 0, 0, 0]
KING_PST = [(0 - 30), (0 - 40), (0 - 40), (0 - 50), (0 - 50), (0 - 40), (0 - 40), (0 - 30), (0 - 30), (0 - 40), (0 - 40), (0 - 50), (0 - 50), (0 - 40), (0 - 40), (0 - 30), (0 - 30), (0 - 40), (0 - 40), (0 - 50), (0 - 50), (0 - 40), (0 - 40), (0 - 30), (0 - 30), (0 - 40), (0 - 40), (0 - 50), (0 - 50), (0 - 40), (0 - 40), (0 - 30), (0 - 20), (0 - 30), (0 - 30), (0 - 40), (0 - 40), (0 - 30), (0 - 30), (0 - 20), (0 - 10), (0 - 20), (0 - 20), (0 - 20), (0 - 20), (0 - 20), (0 - 20), (0 - 10), 20, 20, 0, 0, 0, 0, 20, 20, 20, 30, 10, 0, 0, 10, 30, 20]
QUEEN_PST = [(0 - 20), (0 - 10), (0 - 10), (0 - 5), (0 - 5), (0 - 10), (0 - 10), (0 - 20), (0 - 10), 0, 0, 0, 0, 0, 0, (0 - 10), (0 - 10), 0, 5, 5, 5, 5, 0, (0 - 10), (0 - 5), 0, 5, 5, 5, 5, 0, (0 - 5), 0, 0, 5, 5, 5, 5, 0, (0 - 5), (0 - 10), 5, 5, 5, 5, 5, 0, (0 - 10), (0 - 10), 0, 5, 0, 0, 0, 0, (0 - 10), (0 - 20), (0 - 10), (0 - 10), (0 - 5), (0 - 5), (0 - 10), (0 - 10), (0 - 20)]
KING_ENDGAME_PST = [(0 - 50), (0 - 40), (0 - 30), (0 - 20), (0 - 20), (0 - 30), (0 - 40), (0 - 50), (0 - 30), (0 - 20), (0 - 10), 0, 0, (0 - 10), (0 - 20), (0 - 30), (0 - 30), (0 - 10), 20, 30, 30, 20, (0 - 10), (0 - 30), (0 - 30), (0 - 10), 30, 40, 40, 30, (0 - 10), (0 - 30), (0 - 30), (0 - 10), 30, 40, 40, 30, (0 - 10), (0 - 30), (0 - 30), (0 - 10), 20, 30, 30, 20, (0 - 10), (0 - 30), (0 - 30), (0 - 30), 0, 0, 0, 0, (0 - 30), (0 - 30), (0 - 50), (0 - 30), (0 - 30), (0 - 30), (0 - 30), (0 - 30), (0 - 30), (0 - 50)]
tt_table = {}
learning_table = {}
def load_learning_cache():
_slang_ret = None
if exists('learning_cache.json'):
content = slang_file_read('learning_cache.json')
learning_table = json_parse(content)
else:
learning_table = {}
return _slang_ret
def save_learning_cache():
_slang_ret = None
content = json_stringify(learning_table)
slang_file_write('learning_cache.json', content, 'w')
return _slang_ret
def tt_lookup(key, depth, alpha, beta):
_slang_ret = None
if contains(tt_table, key):
entry = tt_table[key]
if (entry['depth'] >= depth):
val = entry['val']
flag = entry['flag']
if (flag == 0):
return val
if (flag == 1):
if (val >= beta):
return val
if (flag == 2):
if (val <= alpha):
return val
else:
if contains(learning_table, key):
entry = learning_table[key]
if (entry['depth'] >= depth):
val = entry['val']
flag = entry['flag']
if (flag == 0):
return val
if (flag == 1):
if (val >= beta):
return val
if (flag == 2):
if (val <= alpha):
return val
return null
return _slang_ret
def tt_store(key, depth, val, flag, move):
_slang_ret = None
entry = {'depth': depth, 'val': val, 'flag': flag, 'move': move}
tt_table[key] = entry
if (depth >= 4):
m_data = null
if (move != null):
m_data = {'from_sq': (move . from_sq), 'to_sq': (move . to_sq), 'piece': (move . piece), 'captured': (move . captured), 'flags': (move . flags)}
learning_entry = {'depth': depth, 'val': val, 'flag': flag, 'move': m_data}
should_store = True
if contains(learning_table, key):
existing = learning_table[key]
if (existing['depth'] > depth):
should_store = False
if (should_store == True):
learning_table[key] = learning_entry
return _slang_ret
killer_table = {}
history_table = {}
def add_killer(ply, move):
_slang_ret = None
if (not contains(killer_table, ply)):
killer_table[ply] = []
killers = killer_table[ply]
already_exists = False
for km in killers:
if (((km . from_sq) == (move . from_sq)) and ((km . to_sq) == (move . to_sq))):
already_exists = True
if (not already_exists):
_slang_ret = add(killers, move)
_web_builder.add_text(_slang_ret)
if (len(killers) > 2):
_slang_ret = pop(killers, 0)
_web_builder.add_text(_slang_ret)
return _slang_ret
def evaluate(board):
_slang_ret = None
score = 0
sqs = (board . squares)
turn = (board . turn)
white_pawns_in_file = [0, 0, 0, 0, 0, 0, 0, 0]
black_pawns_in_file = [0, 0, 0, 0, 0, 0, 0, 0]
white_pieces = 0
black_pieces = 0
white_queens = 0
black_queens = 0
white_bishops = 0
black_bishops = 0
white_knights = 0
black_knights = 0
white_pawn_eg_bonus = 0
black_pawn_eg_bonus = 0
white_rooks = []
black_rooks = []
for i in range(0, 64):
p = sqs[i]
if (p == 0):
continue
ptype = (p % 8)
color = (p - ptype)
val = 0
if (ptype == 1):
val = 100
col = (i % 8)
if (color == 8):
white_pawns_in_file[col] = (white_pawns_in_file[col] + 1)
rank_num = (7 - int((i / 8)))
if (rank_num >= 4):
white_pawn_eg_bonus = (white_pawn_eg_bonus + (rank_num * 10))
else:
black_pawns_in_file[col] = (black_pawns_in_file[col] + 1)
rank_num = int((i / 8))
if (rank_num >= 4):
black_pawn_eg_bonus = (black_pawn_eg_bonus + (rank_num * 10))
else:
if (ptype == 2):
val = 300
if (color == 8):
white_pieces = (white_pieces + 1)
white_knights = (white_knights + 1)
else:
black_pieces = (black_pieces + 1)
black_knights = (black_knights + 1)
else:
if (ptype == 3):
val = 320
if (color == 8):
white_pieces = (white_pieces + 1)
white_bishops = (white_bishops + 1)
else:
black_pieces = (black_pieces + 1)
black_bishops = (black_bishops + 1)
else:
if (ptype == 4):
val = 500
if (color == 8):
white_pieces = (white_pieces + 1)
_slang_ret = add(white_rooks, i)
_web_builder.add_text(_slang_ret)
else:
black_pieces = (black_pieces + 1)
_slang_ret = add(black_rooks, i)
_web_builder.add_text(_slang_ret)
else:
if (ptype == 5):
val = 900
if (color == 8):
white_pieces = (white_pieces + 1)
white_queens = (white_queens + 1)
else:
black_pieces = (black_pieces + 1)
black_queens = (black_queens + 1)
else:
if (ptype == 6):
val = 20000
idx = i
if (color == 16):
r = int((i / 8))
c = (i % 8)
idx = (((7 - r) * 8) + c)
pst_val = 0
if (ptype == 1):
pst_val = PAWN_PST[idx]
else:
if (ptype == 2):
pst_val = KNIGHT_PST[idx]
else:
if (ptype == 3):
pst_val = BISHOP_PST[idx]
else:
if (ptype == 4):
pst_val = ROOK_PST[idx]
else:
if (ptype == 5):
pst_val = QUEEN_PST[idx]
else:
if (ptype == 6):
pst_val = KING_PST[idx]
val = (val + pst_val)
if (color == turn):
score = (score + val)
else:
score = (score - val)
if (ptype == 2):
offsets = [[(0 - 2), (0 - 1)], [(0 - 2), 1], [(0 - 1), (0 - 2)], [(0 - 1), 2], [1, (0 - 2)], [1, 2], [2, (0 - 1)], [2, 1]]
mob = 0
kr = int((i / 8))
kc = (i % 8)
for off in offsets:
nr = (kr + off[0])
nc = (kc + off[1])
if ((((nr >= 0) and (nr < 8)) and (nc >= 0)) and (nc < 8)):
target = ((nr * 8) + nc)
tp = sqs[target]
if ((tp == EMPTY) or ((tp - (tp % 8)) != color)):
mob = (mob + 1)
mob_val = (mob * 2)
if (color == turn):
score = (score + mob_val)
else:
score = (score - mob_val)
else:
if (((ptype == 3) or (ptype == 4)) or (ptype == 5)):
dirs = []
if (ptype == 3):
dirs = [7, (0 - 7), 9, (0 - 9)]
else:
if (ptype == 4):
dirs = [1, (0 - 1), 8, (0 - 8)]
else:
dirs = [1, (0 - 1), 8, (0 - 8), 7, (0 - 7), 9, (0 - 9)]
mob = 0
sr = int((i / 8))
sc = (i % 8)
for d in dirs:
dr = 0
dc = 0
if (d == 1):
dc = 1
else:
if (d == (0 - 1)):
dc = (0 - 1)
else:
if (d == 8):
dr = 1
else:
if (d == (0 - 8)):
dr = (0 - 1)
else:
if (d == 7):
dr = 1
dc = (0 - 1)
else:
if (d == (0 - 7)):
dr = (0 - 1)
dc = 1
else:
if (d == 9):
dr = 1
dc = 1
else:
if (d == (0 - 9)):
dr = (0 - 1)
dc = (0 - 1)
nr = (sr + dr)
nc = (sc + dc)
while ((((nr >= 0) and (nr < 8)) and (nc >= 0)) and (nc < 8)):
target = ((nr * 8) + nc)
tp = sqs[target]
if (tp == EMPTY):
mob = (mob + 1)
else:
if ((tp - (tp % 8)) != color):
mob = (mob + 1)
break
nr = (nr + dr)
nc = (nc + dc)
mob_val = (mob * 2)
if (color == turn):
score = (score + mob_val)
else:
score = (score - mob_val)
is_eg = False
if ((white_queens == 0) and (black_queens == 0)):
is_eg = True
else:
if ((white_pieces <= 2) and (black_pieces <= 2)):
is_eg = True
if (white_bishops >= 2):
if (turn == WHITE):
score = (score + 40)
else:
score = (score - 40)
if (black_bishops >= 2):
if (turn == BLACK):
score = (score + 40)
else:
score = (score - 40)
for r_sq in white_rooks:
col = (r_sq % 8)
wp = white_pawns_in_file[col]
bp = black_pawns_in_file[col]
bonus = 0
if (wp == 0):
if (bp == 0):
bonus = 30
else:
bonus = 15
if (turn == WHITE):
score = (score + bonus)
else:
score = (score - bonus)
for r_sq in black_rooks:
col = (r_sq % 8)
wp = white_pawns_in_file[col]
bp = black_pawns_in_file[col]
bonus = 0
if (bp == 0):
if (wp == 0):
bonus = 30
else:
bonus = 15
if (turn == BLACK):
score = (score + bonus)
else:
score = (score - bonus)
wk_sq = (board . white_king_sq)
bk_sq = (board . black_king_sq)
if is_eg:
if (wk_sq != (0 - 1)):
pst_diff = (KING_ENDGAME_PST[wk_sq] - KING_PST[wk_sq])
if (turn == WHITE):
score = (score + pst_diff)
else:
score = (score - pst_diff)
if (bk_sq != (0 - 1)):
bk_r = int((bk_sq / 8))
bk_c = (bk_sq % 8)
bk_idx = (((7 - bk_r) * 8) + bk_c)
pst_diff = (KING_ENDGAME_PST[bk_idx] - KING_PST[bk_idx])
if (turn == BLACK):
score = (score + pst_diff)
else:
score = (score - pst_diff)
if (turn == WHITE):
score = ((score + white_pawn_eg_bonus) - black_pawn_eg_bonus)
else:
score = ((score + black_pawn_eg_bonus) - white_pawn_eg_bonus)
else:
if (wk_sq != (0 - 1)):
wk_safety = 0
if ((wk_sq == 62) or (wk_sq == 63)):
if (sqs[53] != (PAWN + WHITE)):
wk_safety = (wk_safety - 20)
if (sqs[54] != (PAWN + WHITE)):
wk_safety = (wk_safety - 20)
if (sqs[55] != (PAWN + WHITE)):
wk_safety = (wk_safety - 20)
else:
if ((wk_sq == 58) or (wk_sq == 57)):
if (sqs[48] != (PAWN + WHITE)):
wk_safety = (wk_safety - 20)
if (sqs[49] != (PAWN + WHITE)):
wk_safety = (wk_safety - 20)
if (sqs[50] != (PAWN + WHITE)):
wk_safety = (wk_safety - 20)
if (turn == WHITE):
score = (score + wk_safety)
else:
score = (score - wk_safety)
if (bk_sq != (0 - 1)):
bk_safety = 0
if ((bk_sq == 6) or (bk_sq == 7)):
if (sqs[13] != (PAWN + BLACK)):
bk_safety = (bk_safety - 20)
if (sqs[14] != (PAWN + BLACK)):
bk_safety = (bk_safety - 20)
if (sqs[15] != (PAWN + BLACK)):
bk_safety = (bk_safety - 20)
else:
if ((bk_sq == 2) or (bk_sq == 1)):
if (sqs[8] != (PAWN + BLACK)):
bk_safety = (bk_safety - 20)
if (sqs[9] != (PAWN + BLACK)):
bk_safety = (bk_safety - 20)
if (sqs[10] != (PAWN + BLACK)):
bk_safety = (bk_safety - 20)
if (turn == BLACK):
score = (score + bk_safety)
else:
score = (score - bk_safety)
if is_eg:
if (white_pieces == 0):
if ((wk_sq != (0 - 1)) and (bk_sq != (0 - 1))):
wk_r = int((wk_sq / 8))
wk_c = (wk_sq % 8)
dist_to_center = (abs((wk_r - 3.5)) + abs((wk_c - 3.5)))
bk_r = int((bk_sq / 8))
bk_c = (bk_sq % 8)
dist_between_kings = (abs((wk_r - bk_r)) + abs((wk_c - bk_c)))
mop_up = (int((dist_to_center * 10)) + int(((14 - dist_between_kings) * 5)))
if (turn == 16):
score = (score + mop_up)
else:
score = (score - mop_up)
else:
if (black_pieces == 0):
if ((wk_sq != (0 - 1)) and (bk_sq != (0 - 1))):
bk_r = int((bk_sq / 8))
bk_c = (bk_sq % 8)
dist_to_center = (abs((bk_r - 3.5)) + abs((bk_c - 3.5)))
wk_r = int((wk_sq / 8))
wk_c = (wk_sq % 8)
dist_between_kings = (abs((wk_r - bk_r)) + abs((wk_c - bk_c)))
mop_up = (int((dist_to_center * 10)) + int(((14 - dist_between_kings) * 5)))
if (turn == 8):
score = (score + mop_up)
else:
score = (score - mop_up)
for f in range(0, 8):
wp = white_pawns_in_file[f]
bp = black_pawns_in_file[f]
if (wp > 1):
penalty = ((wp - 1) * 15)
if (turn == WHITE):
score = (score - penalty)
else:
score = (score + penalty)
if (bp > 1):
penalty = ((bp - 1) * 15)
if (turn == BLACK):
score = (score - penalty)
else:
score = (score + penalty)
if (wp > 0):
has_adj_w = False
if (f > 0):
if (white_pawns_in_file[(f - 1)] > 0):
has_adj_w = True
if (f < 7):
if (white_pawns_in_file[(f + 1)] > 0):
has_adj_w = True
if (not has_adj_w):
if (turn == WHITE):
score = (score - 12)
else:
score = (score + 12)
if (bp > 0):
has_adj_b = False
if (f > 0):
if (black_pawns_in_file[(f - 1)] > 0):
has_adj_b = True
if (f < 7):
if (black_pawns_in_file[(f + 1)] > 0):
has_adj_b = True
if (not has_adj_b):
if (turn == BLACK):
score = (score - 12)
else:
score = (score + 12)
if ((wp > 0) and (bp == 0)):
blocked = False
if (f > 0):
if (black_pawns_in_file[(f - 1)] > 0):
blocked = True
if (f < 7):
if (black_pawns_in_file[(f + 1)] > 0):
blocked = True
if (not blocked):
if (turn == WHITE):
score = (score + 20)
else:
score = (score - 20)
if ((bp > 0) and (wp == 0)):
blocked = False
if (f > 0):
if (white_pawns_in_file[(f - 1)] > 0):
blocked = True
if (f < 7):
if (white_pawns_in_file[(f + 1)] > 0):
blocked = True
if (not blocked):
if (turn == BLACK):
score = (score + 20)
else:
score = (score - 20)
return score
return _slang_ret
def generate_legal_captures(board):
_slang_ret = None
original_turn = (board . turn)
pseudo = generate_pseudo_legal_moves(board)
legal_captures = []
for m in pseudo:
if (((m . captured) == EMPTY) or ((m . captured) == 0)):
continue
_slang_ret = (board . make_move(m))
_web_builder.add_text(_slang_ret)
if (not is_square_attacked(board, (board . get_king_square(original_turn)), (board . turn))):
_slang_ret = add(legal_captures, m)
_web_builder.add_text(_slang_ret)
_slang_ret = (board . undo_move())
_web_builder.add_text(_slang_ret)
return legal_captures
return _slang_ret
search_state = {'start_time': 0.0, 'time_limit': 100000000.0, 'aborted': False, 'node_count': 0}
def check_time():
_slang_ret = None
search_state['node_count'] = (search_state['node_count'] + 1)
if ((search_state['node_count'] % 1024) == 0):
elapsed = (((time . time()) * 1000.0) - search_state['start_time'])
if (elapsed > search_state['time_limit']):
search_state['aborted'] = True
return _slang_ret
def quiescence(board, alpha, beta):
_slang_ret = None
_slang_ret = check_time()
_web_builder.add_text(_slang_ret)
if (search_state['aborted'] == True):
return 0
stand_pat = evaluate(board)
if (stand_pat >= beta):
return beta
if ((stand_pat + 975) < alpha):
return alpha
if (stand_pat > alpha):
alpha = stand_pat
moves = generate_legal_captures(board)
ordered = order_moves(moves, null, 0)
for m in ordered:
_slang_ret = (board . make_move(m))
_web_builder.add_text(_slang_ret)
score = (0 - quiescence(board, (0 - beta), (0 - alpha)))
_slang_ret = (board . undo_move())
_web_builder.add_text(_slang_ret)
if (score >= beta):
return beta
if (score > alpha):
alpha = score
return alpha
return _slang_ret
def make_null_move(board):
_slang_ret = None
old_turn = (board . turn)
old_ep = (board . ep_square)
if ((board . turn) == WHITE):
_slang_ret = (board . set_turn(BLACK))
_web_builder.add_text(_slang_ret)
else:
_slang_ret = (board . set_turn(WHITE))
_web_builder.add_text(_slang_ret)
_slang_ret = (board . set_ep_square((0 - 1)))
_web_builder.add_text(_slang_ret)
return [old_turn, old_ep]
return _slang_ret
def undo_null_move(board, state):
_slang_ret = None
_slang_ret = (board . set_turn(state[0]))
_web_builder.add_text(_slang_ret)
_slang_ret = (board . set_ep_square(state[1]))
_web_builder.add_text(_slang_ret)
return _slang_ret
def find_best_move(board, depth, allocated_time):
_slang_ret = None
_slang_ret = load_learning_cache()
_web_builder.add_text(_slang_ret)
book_move = get_book_move(board)
if (book_move != null):
return book_move
moves = generate_legal_moves(board)
if empty(moves):
return null
best_move = null
_slang_ret = clear_dict(tt_table)
_web_builder.add_text(_slang_ret)
_slang_ret = clear_dict(killer_table)
_web_builder.add_text(_slang_ret)
_slang_ret = clear_dict(history_table)
_web_builder.add_text(_slang_ret)
search_state['start_time'] = ((time . time()) * 1000.0)
search_state['time_limit'] = float(allocated_time)
search_state['aborted'] = False
search_state['node_count'] = 0
last_completed_best_move = moves[0]
last_val = (0 - 1000000)
end_depth = (depth + 1)
for d in range(1, end_depth):
key = (board . zobrist_key)
hash_move = null
if contains(tt_table, key):
hash_move = tt_table[key]['move']
else:
if contains(learning_table, key):
l_entry = learning_table[key]
l_move = l_entry['move']
if (l_move != null):
hash_move = Move(l_move['from_sq'], l_move['to_sq'], l_move['piece'], l_move['captured'], l_move['flags'])
ordered = order_moves(moves, hash_move, 0)
best_val = (0 - 1000000)
depth_best_move = null
use_aspiration = False
asp_alpha = (0 - 1000000)
asp_beta = 1000000
if ((d >= 3) and (last_val != (0 - 1000000))):
use_aspiration = True
asp_alpha = (last_val - 30)
asp_beta = (last_val + 30)
for m in ordered:
_slang_ret = (board . make_move(m))
_web_builder.add_text(_slang_ret)
alpha = (0 - 1000000)
beta = (0 - best_val)
if (use_aspiration == True):
alpha = asp_alpha
beta = asp_beta
if ((0 - best_val) < beta):
beta = (0 - best_val)
if (alpha < (0 - 1000000)):
alpha = (0 - 1000000)
val = (0 - negamax(board, (d - 1), (0 - beta), (0 - alpha), 1))
_slang_ret = (board . undo_move())
_web_builder.add_text(_slang_ret)
if (search_state['aborted'] == True):
break
if (val > best_val):
best_val = val
depth_best_move = m
if ((use_aspiration == True) and ((best_val <= asp_alpha) or (best_val >= asp_beta))):
best_val = (0 - 1000000)
depth_best_move = null
for m in ordered:
_slang_ret = (board . make_move(m))
_web_builder.add_text(_slang_ret)
val = (0 - negamax(board, (d - 1), (0 - 1000000), (0 - best_val), 1))
_slang_ret = (board . undo_move())
_web_builder.add_text(_slang_ret)
if (search_state['aborted'] == True):
break
if (val > best_val):
best_val = val
depth_best_move = m
if (search_state['aborted'] == True):
break
last_completed_best_move = depth_best_move
last_val = best_val
_slang_ret = tt_store(key, d, best_val, 0, depth_best_move)
_web_builder.add_text(_slang_ret)
elapsed = (((time . time()) * 1000.0) - search_state['start_time'])
if ((elapsed * 2.0) > search_state['time_limit']):
break
_slang_ret = save_learning_cache()
_web_builder.add_text(_slang_ret)
return last_completed_best_move
return _slang_ret
def is_repetition(board):
_slang_ret = None
key = (board . zobrist_key)
h_len = len((board . history))
if (h_len == 0):
return False
limit = (h_len + 1)
for i in range(1, limit):
idx = (h_len - i)
h_state = (board . history[idx])
if (h_state['zobrist_key'] == key):
return True
m = h_state['move']
if (m != null):
if ((get_piece_type((m . piece)) == PAWN) or (((m . captured) != EMPTY) and ((m . captured) != 0))):
return False
return False
return _slang_ret
def has_non_pawn_pieces(board, color):
_slang_ret = None
sqs = (board . squares)
for i in range(0, 64):
p = sqs[i]
if (p != EMPTY):
pt = (p % 8)
pc = (p - pt)
if (pc == color):
if ((((pt == KNIGHT) or (pt == BISHOP)) or (pt == ROOK)) or (pt == QUEEN)):
return True
return False
return _slang_ret
def negamax(board, depth, alpha, beta, ply):
_slang_ret = None
_slang_ret = check_time()
_web_builder.add_text(_slang_ret)
if (search_state['aborted'] == True):
return 0
if ((ply > 0) and is_repetition(board)):
return 0
in_check = is_in_check(board, (board . turn))
if in_check:
depth = (depth + 1)
key = (board . zobrist_key)
tt_val = tt_lookup(key, depth, alpha, beta)
if (tt_val != null):
return tt_val
if (depth == 0):
return quiescence(board, alpha, beta)
if (not in_check):
static_val = evaluate(board)
if (depth <= 4):
if ((static_val - (depth * 100)) >= beta):
return static_val
if (depth <= 2):
if ((static_val + 300) < alpha):
return quiescence(board, alpha, beta)
if (((depth >= 3) and (not in_check)) and has_non_pawn_pieces(board, (board . turn))):
r = 2
if (depth >= 6):
r = 3
margin = (static_val - beta)
if (margin > 0):
extra = int((margin / 200))
if (extra > 2):
extra = 2
r = (r + extra)
null_state = make_null_move(board)
score = (0 - negamax(board, ((depth - 1) - r), (0 - beta), ((0 - beta) + 1), (ply + 1)))
_slang_ret = undo_null_move(board, null_state)
_web_builder.add_text(_slang_ret)
if (score >= beta):
return beta
moves = generate_legal_moves(board)
if empty(moves):
if in_check:
return ((0 - 100000) + ply)
else:
return 0
hash_move = null
if contains(tt_table, key):
hash_move = tt_table[key]['move']
ordered = order_moves(moves, hash_move, ply)
best_val = (0 - 1000000)
best_move = null
moves_searched = 0
futility_ok = False
if ((depth <= 4) and (not in_check)):
fut_margin = (depth * 150)
if ((static_val + fut_margin) < alpha):
futility_ok = True
for m in ordered:
if (futility_ok and (moves_searched >= 1)):
if (((m . captured) == 0) and ((m . flags) == 0)):
moves_searched = (moves_searched + 1)
continue
_slang_ret = (board . make_move(m))
_web_builder.add_text(_slang_ret)
is_lmr = False
if ((((depth >= 3) and (moves_searched >= 3)) and ((m . captured) == 0)) and ((m . flags) == 0)):
if (not is_in_check(board, (board . turn))):
is_lmr = True
val = (0 - 1000000)
if (is_lmr == True):
reduction = 1
if ((depth >= 5) and (moves_searched >= 6)):
reduction = 2
val = (0 - negamax(board, ((depth - 1) - reduction), ((0 - alpha) - 1), (0 - alpha), (ply + 1)))
if (val > alpha):
val = (0 - negamax(board, (depth - 1), ((0 - alpha) - 1), (0 - alpha), (ply + 1)))
if ((val > alpha) and (val < beta)):
val = (0 - negamax(board, (depth - 1), (0 - beta), (0 - alpha), (ply + 1)))
else:
if (moves_searched == 0):
val = (0 - negamax(board, (depth - 1), (0 - beta), (0 - alpha), (ply + 1)))
else:
val = (0 - negamax(board, (depth - 1), ((0 - alpha) - 1), (0 - alpha), (ply + 1)))
if ((val > alpha) and (val < beta)):
val = (0 - negamax(board, (depth - 1), (0 - beta), (0 - alpha), (ply + 1)))
_slang_ret = (board . undo_move())
_web_builder.add_text(_slang_ret)
moves_searched = (moves_searched + 1)
if (search_state['aborted'] == True):
break
if (val > best_val):
best_val = val
best_move = m
if (val > alpha):
alpha = val
if (beta <= alpha):
if ((m . captured) == 0):
_slang_ret = add_killer(ply, m)
_web_builder.add_text(_slang_ret)
h_key = (((m . from_sq) * 64) + (m . to_sq))
h_score = 0
if contains(history_table, h_key):
h_score = history_table[h_key]
history_table[h_key] = (h_score + (depth * depth))
break
if (search_state['aborted'] == True):
return 0
flag = 0
if (best_val <= alpha):
flag = 2
else:
if (best_val >= beta):
flag = 1
_slang_ret = tt_store(key, depth, best_val, flag, best_move)
_web_builder.add_text(_slang_ret)
return best_val
return _slang_ret