├── .github ├── FUNDING.yml └── workflows │ └── codeql-analysis.yml ├── README.md ├── main.py ├── piece.py ├── engine.py ├── LICENSE └── board.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: ['Tazeg'] 2 | custom: ['https://keybase.io/jeffprod'] 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | JePyChess 2 | ========= 3 | 4 | Introducing "JeffProd Simple Python Chess Program" running in command line. 5 | You can play a full game versus it. 6 | Run it with the command : ./main.py 7 | 8 | It supports actually : 9 | - promote 10 | - under-promote 11 | - capture "en passant" 12 | 13 | Commands are : 14 | - **new** to start a new game 15 | - **e2e4** or **e7e8q** for example to move a piece. Promotes are q,r,n,b for queen, rook, knight, bishop 16 | - **undomove** to cancel the last move 17 | - **legalmoves** to show legal moves for side to move 18 | - **go** requests the engine to play now 19 | - **setboard fen** to set the board as the FEN position given 20 | - **getboard** to export the current FEN position 21 | - **sd x** to set the depth search 22 | - **perft x** to test the move generator (x = search depth) 23 | - **quit**... to quit 24 | 25 | Things to do : 26 | - move ordering 27 | - quiescent search 28 | - 50 moves rule 29 | - 3 repetitions rule 30 | - time settings 31 | - opening book 32 | 33 | Requirements : 34 | - Python 3 35 | 36 | More information on : 37 | https://fr.jeffprod.com/blog/2014/comment-programmer-un-jeu-dechecs/ 38 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ######################################################################## 3 | # JeffProd Simple Python Chess Program 4 | ######################################################################## 5 | # AUTHOR : Jean-Francois GAZET 6 | # WEB : http://www.jeffprod.com 7 | # TWITTER : @JeffProd 8 | # MAIL : jeffgazet@gmail.com 9 | # LICENCE : GNU GENERAL PUBLIC LICENSE Version 2, June 1991 10 | ######################################################################## 11 | 12 | # Import object classes 13 | from board import * 14 | from engine import * 15 | 16 | b=Board() 17 | e=Engine() 18 | 19 | while(True): 20 | 21 | b.render() 22 | 23 | c=input('>>> ') 24 | 25 | if(c=='quit' or c=='exit'): 26 | exit(0) 27 | 28 | elif(c=='undomove'): 29 | e.undomove(b) 30 | 31 | elif('setboard' in c): 32 | e.setboard(b,c) 33 | 34 | elif(c=='getboard'): 35 | e.getboard(b) 36 | 37 | elif(c=='go'): 38 | e.search(b) 39 | 40 | elif(c=='new'): 41 | e.newgame(b) 42 | 43 | elif(c=='bench'): 44 | e.bench(b) 45 | 46 | elif('sd ' in c): 47 | e.setDepth(c) 48 | 49 | elif('perft ' in c): 50 | e.perft(c,b) 51 | 52 | elif(c=='legalmoves'): 53 | e.legalmoves(b) 54 | 55 | else: 56 | # coup à jouer ? ex : e2e4 57 | e.usermove(b,c) 58 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 2 * * 2' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['python'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | with: 35 | # We must fetch at least the immediate parents so that if this is 36 | # a pull request then we can checkout the head. 37 | fetch-depth: 2 38 | 39 | # If this run was triggered by a pull request event, then checkout 40 | # the head of the pull request instead of the merge commit. 41 | - run: git checkout HEAD^2 42 | if: ${{ github.event_name == 'pull_request' }} 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /piece.py: -------------------------------------------------------------------------------- 1 | ######################################################################## 2 | # JeffProd Simple Python Chess Program 3 | ######################################################################## 4 | # AUTHOR : Jean-Francois GAZET 5 | # WEB : http://www.jeffprod.com 6 | # TWITTER : @JeffProd 7 | # MAIL : jeffgazet@gmail.com 8 | # LICENCE : GNU GENERAL PUBLIC LICENSE Version 2, June 1991 9 | ######################################################################## 10 | 11 | class Piece: 12 | 13 | "Chess set class" 14 | 15 | VIDE='.' # empty piece name (=empty square '.' in console) 16 | 17 | # Name of the pieces 18 | nomPiece=(VIDE,'ROI','DAME','TOUR','CAVALIER','FOU','PION') 19 | 20 | # Give a score value for each piece : KING=0, QUEEN=9, ROOK=5... 21 | valeurPiece=(0,0,9,5,3,3,1) 22 | 23 | # For the pieces moves, using method "mail box" from Robert Hyatt 24 | # It helps to know if a piece is not moved outside the board ! 25 | tab120 = ( 26 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 27 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 28 | -1, 0, 1, 2, 3, 4, 5, 6, 7, -1, 29 | -1, 8, 9, 10, 11, 12, 13, 14, 15, -1, 30 | -1, 16, 17, 18, 19, 20, 21, 22, 23, -1, 31 | -1, 24, 25, 26, 27, 28, 29, 30, 31, -1, 32 | -1, 32, 33, 34, 35, 36, 37, 38, 39, -1, 33 | -1, 40, 41, 42, 43, 44, 45, 46, 47, -1, 34 | -1, 48, 49, 50, 51, 52, 53, 54, 55, -1, 35 | -1, 56, 57, 58, 59, 60, 61, 62, 63, -1, 36 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 37 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 38 | ) 39 | tab64 = ( 40 | 21, 22, 23, 24, 25, 26, 27, 28, 41 | 31, 32, 33, 34, 35, 36, 37, 38, 42 | 41, 42, 43, 44, 45, 46, 47, 48, 43 | 51, 52, 53, 54, 55, 56, 57, 58, 44 | 61, 62, 63, 64, 65, 66, 67, 68, 45 | 71, 72, 73, 74, 75, 76, 77, 78, 46 | 81, 82, 83, 84, 85, 86, 87, 88, 47 | 91, 92, 93, 94, 95, 96, 97, 98 48 | ) 49 | 50 | # Moving vectors according to the 'tab64', 51 | deplacements_tour=(-10,10,-1,1) 52 | deplacements_fou=(-11,-9,11,9) 53 | deplacements_cavalier=(-12,-21,-19,-8,12,21,19,8) 54 | # KING and QUEEN = BISHOP + ROOK ! 55 | 56 | #################################################################### 57 | 58 | def __init__(self,nom=VIDE,couleur=''): 59 | 60 | """Creating a piece object, with its attributes : 61 | - 'nom' as name (ROI, DAME...); 62 | - 'couleur' as color (blanc,noir); 63 | - 'valeur' as its value""" 64 | 65 | self.nom=nom 66 | self.couleur=couleur 67 | self.valeur=self.valeurPiece[self.nomPiece.index(nom)] 68 | 69 | #################################################################### 70 | 71 | def isEmpty(self): 72 | 73 | """Returns TRUE or FALSE if this piece object is defined, 74 | As any square on board can have a piece on it, or not, 75 | we can set a null piece on a square.""" 76 | 77 | return (self.nom==self.VIDE) 78 | 79 | #################################################################### 80 | 81 | def pos2_roi(self,pos1,cAd,echiquier,dontCallIsAttacked=False): 82 | 83 | """Returns the list of moves for the king : 84 | - which is at square 'pos1' 85 | - which opponent color is 'cAd' (blanc,noir) 86 | - dontCallIsAttacked is set to avoid recursives calls 87 | between is_attacked() and gen_moves_list(). 88 | """ 89 | 90 | liste=[] 91 | 92 | for i in (self.deplacements_tour+self.deplacements_fou): 93 | n=self.tab120[self.tab64[pos1]+i] 94 | if(n!=-1): 95 | if(echiquier.cases[n].isEmpty() or echiquier.cases[n].couleur==cAd): 96 | liste.append((pos1,n,'')) 97 | 98 | if(dontCallIsAttacked): 99 | return liste # we just wanted moves that can attack 100 | 101 | # The current side to move is the opposite of cAd 102 | c=echiquier.oppColor(cAd) 103 | 104 | # Castle moves 105 | if(c=='blanc'): 106 | if(echiquier.white_can_castle_63): 107 | # If a rook is at square 63 108 | # And if squares between KING and ROOK are empty 109 | # And if squares on which KING walks are not attacked 110 | # And if KING is not in check 111 | # Then we can add this castle move 112 | if(echiquier.cases[63].nom=='TOUR' and \ 113 | echiquier.cases[63].couleur=='blanc' and \ 114 | echiquier.cases[61].isEmpty() and \ 115 | echiquier.cases[62].isEmpty() and \ 116 | echiquier.is_attacked(61,'noir')==False and \ 117 | echiquier.is_attacked(62,'noir')==False and \ 118 | echiquier.is_attacked(pos1,'noir')==False): 119 | liste.append((pos1,62,'')) 120 | if(echiquier.white_can_castle_56): 121 | # S'il y a une tour en 56, etc... 122 | if(echiquier.cases[56].nom=='TOUR' and \ 123 | echiquier.cases[56].couleur=='blanc' and \ 124 | echiquier.cases[57].isEmpty() and \ 125 | echiquier.cases[58].isEmpty() and \ 126 | echiquier.cases[59].isEmpty() and \ 127 | echiquier.is_attacked(58,cAd)==False and \ 128 | echiquier.is_attacked(59,cAd)==False and \ 129 | echiquier.is_attacked(pos1,cAd)==False): 130 | liste.append((pos1,58,'')) 131 | elif(c=='noir'): 132 | if(echiquier.black_can_castle_7): 133 | if(echiquier.cases[7].nom=='TOUR' and \ 134 | echiquier.cases[7].couleur=='noir' and \ 135 | echiquier.cases[5].isEmpty() and \ 136 | echiquier.cases[6].isEmpty() and \ 137 | echiquier.is_attacked(5,cAd)==False and \ 138 | echiquier.is_attacked(6,cAd)==False and \ 139 | echiquier.is_attacked(pos1,cAd)==False): 140 | liste.append((pos1,6,'')) 141 | if(echiquier.black_can_castle_0): 142 | if(echiquier.cases[0].nom=='TOUR' and \ 143 | echiquier.cases[0].couleur=='noir' and \ 144 | echiquier.cases[1].isEmpty() and \ 145 | echiquier.cases[2].isEmpty() and \ 146 | echiquier.cases[3].isEmpty() and \ 147 | echiquier.is_attacked(2,cAd)==False and \ 148 | echiquier.is_attacked(3,cAd)==False and \ 149 | echiquier.is_attacked(pos1,cAd)==False): 150 | liste.append((pos1,2,'')) 151 | 152 | return liste 153 | 154 | #################################################################### 155 | 156 | def pos2_tour(self,pos1,cAd,echiquier): 157 | 158 | """Returns the list of moves for a ROOK : 159 | - at square number 'pos1' (0 to 63) 160 | - opponent color is cAd (blanc,noir)""" 161 | 162 | liste=[] 163 | 164 | for k in self.deplacements_tour: 165 | j=1 166 | while(True): 167 | n=self.tab120[self.tab64[pos1] + (k * j)] 168 | if(n!=-1): # as we are not out of the board 169 | if(echiquier.cases[n].isEmpty() or echiquier.cases[n].couleur==cAd): 170 | liste.append((pos1,n,'')) # append the move if square is empty of opponent color 171 | else: 172 | break # stop if outside of the board 173 | if(not echiquier.cases[n].isEmpty()): 174 | break # destination square is not empty (opponent or not) then the rook won't pass through 175 | j=j+1 176 | 177 | return liste 178 | 179 | #################################################################### 180 | 181 | def pos2_cavalier(self,pos1,cAd,echiquier): 182 | 183 | """Returns the list of moves for a KNIGHT : 184 | - at square number 'pos1' (0 to 63) 185 | - opponent color is cAd (blanc,noir)""" 186 | 187 | liste=[] 188 | 189 | for i in self.deplacements_cavalier: 190 | n=self.tab120[self.tab64[pos1]+i] 191 | if(n!=-1): 192 | if(echiquier.cases[n].isEmpty() or echiquier.cases[n].couleur==cAd): 193 | liste.append((pos1,n,'')) 194 | 195 | return liste 196 | 197 | #################################################################### 198 | 199 | def pos2_fou(self,pos1,cAd,echiquier): 200 | 201 | """Returns the list of moves for a BISHOP : 202 | - at square number 'pos1' (0 to 63) 203 | - opponent color is cAd (blanc,noir)""" 204 | 205 | liste=[] 206 | 207 | for k in self.deplacements_fou: 208 | j=1 209 | while(True): 210 | n=self.tab120[self.tab64[pos1] + (k * j)] 211 | if(n!=-1): # as we are not out of the board 212 | if(echiquier.cases[n].isEmpty() or echiquier.cases[n].couleur==cAd): 213 | liste.append((pos1,n,'')) # append the move if square is empty of opponent color 214 | else: 215 | break # stop if outside of the board 216 | if(not echiquier.cases[n].isEmpty()): 217 | break # destination square is not empty (opponent or not) then the bishop won't pass through 218 | j=j+1 219 | 220 | return liste 221 | 222 | #################################################################### 223 | 224 | def pos2_pion(self,pos1,couleur,echiquier): 225 | 226 | """Returns the list of moves for a PAWN : 227 | - at square number 'pos1' (0 to 63) 228 | - opponent color is cAd (blanc,noir)""" 229 | 230 | liste=[] 231 | 232 | # White PAWN --------------------------------------------------- 233 | if(couleur=='blanc'): 234 | 235 | # Upper square 236 | n=self.tab120[self.tab64[pos1]-10] 237 | if(n!=-1): 238 | if(echiquier.cases[n].isEmpty()): 239 | # If the PAWN has arrived to rank 8 (square 0 to 7), 240 | if(n<8): 241 | # it will be promoted 242 | liste.append((pos1,n,'q')) 243 | liste.append((pos1,n,'r')) 244 | liste.append((pos1,n,'n')) 245 | liste.append((pos1,n,'b')) 246 | else: 247 | liste.append((pos1,n,'')) 248 | 249 | # 2nd square if PAWN is at starting square 250 | if(echiquier.ROW(pos1)==6): 251 | # If the 2 upper squares are empty 252 | if(echiquier.cases[pos1-8].isEmpty() and echiquier.cases[pos1-16].isEmpty()): 253 | liste.append((pos1,pos1-16,'')) 254 | 255 | # Capture upper left 256 | n=self.tab120[self.tab64[pos1]-11] 257 | if(n!=-1): 258 | if(echiquier.cases[n].couleur=='noir' or echiquier.ep==n): 259 | if(n<8): # Capture + promote 260 | liste.append((pos1,n,'q')) 261 | liste.append((pos1,n,'r')) 262 | liste.append((pos1,n,'n')) 263 | liste.append((pos1,n,'b')) 264 | else: 265 | liste.append((pos1,n,'')) 266 | 267 | # Capture upper right 268 | n=self.tab120[self.tab64[pos1]-9] 269 | if(n!=-1): 270 | if(echiquier.cases[n].couleur=='noir' or echiquier.ep==n): 271 | if(n<8): 272 | liste.append((pos1,n,'q')) 273 | liste.append((pos1,n,'r')) 274 | liste.append((pos1,n,'n')) 275 | liste.append((pos1,n,'b')) 276 | else: 277 | liste.append((pos1,n,'')) 278 | 279 | # Black PAWN --------------------------------------------------- 280 | else: 281 | 282 | # Upper square 283 | n=self.tab120[self.tab64[pos1]+10] 284 | if(n!=-1): 285 | if(echiquier.cases[n].isEmpty()): 286 | # PAWN has arrived to 8th rank (square 56 to 63), 287 | # it will be promoted 288 | if(n>55): 289 | liste.append((pos1,n,'q')) 290 | liste.append((pos1,n,'r')) 291 | liste.append((pos1,n,'n')) 292 | liste.append((pos1,n,'b')) 293 | else: 294 | liste.append((pos1,n,'')) 295 | 296 | # 2nd square if PAWN is at starting square 297 | if(echiquier.ROW(pos1)==1): 298 | # If the 2 upper squares are empty 299 | if(echiquier.cases[pos1+8].isEmpty() and echiquier.cases[pos1+16].isEmpty()): 300 | liste.append((pos1,pos1+16,'')) 301 | 302 | # Capture bottom left 303 | n=self.tab120[self.tab64[pos1]+9] 304 | if(n!=-1): 305 | if(echiquier.cases[n].couleur=='blanc' or echiquier.ep==n): 306 | if(n>55): 307 | liste.append((pos1,n,'q')) 308 | liste.append((pos1,n,'r')) 309 | liste.append((pos1,n,'n')) 310 | liste.append((pos1,n,'b')) 311 | else: 312 | liste.append((pos1,n,'')) 313 | 314 | # Capture bottom right 315 | n=self.tab120[self.tab64[pos1]+11] 316 | if(n!=-1): 317 | if(echiquier.cases[n].couleur=='blanc' or echiquier.ep==n): 318 | if(n>55): 319 | liste.append((pos1,n,'q')) 320 | liste.append((pos1,n,'r')) 321 | liste.append((pos1,n,'n')) 322 | liste.append((pos1,n,'b')) 323 | else: 324 | liste.append((pos1,n,'')) 325 | 326 | return liste 327 | 328 | #################################################################### 329 | -------------------------------------------------------------------------------- /engine.py: -------------------------------------------------------------------------------- 1 | ######################################################################## 2 | # JeffProd Simple Python Chess Program 3 | ######################################################################## 4 | # AUTHOR : Jean-Francois GAZET 5 | # WEB : http://www.jeffprod.com 6 | # TWITTER : @JeffProd 7 | # MAIL : jeffgazet@gmail.com 8 | # LICENCE : GNU GENERAL PUBLIC LICENSE Version 2, June 1991 9 | ######################################################################## 10 | 11 | from piece import * 12 | import time 13 | 14 | class Engine: 15 | 16 | "The chess engine" 17 | 18 | #################################################################### 19 | 20 | def __init__(self): 21 | 22 | self.MAX_PLY=32 23 | self.pv_length=[0 for x in range(self.MAX_PLY)] 24 | self.INFINITY=32000 25 | self.init() 26 | 27 | #################################################################### 28 | 29 | def usermove(self,b,c): 30 | 31 | """Move a piece for the side to move, asked in command line. 32 | The command 'c' in argument is like 'e2e4' or 'b7b8q'. 33 | Argument 'b' is the chessboard. 34 | """ 35 | 36 | if(self.endgame): 37 | self.print_result(b) 38 | return 39 | 40 | # Testing the command 'c'. Exit if incorrect. 41 | chk=self.chkCmd(c) 42 | if(chk!=''): 43 | print(chk) 44 | return 45 | 46 | # Convert cases names to int, ex : e3 -> 44 47 | pos1=b.caseStr2Int(c[0]+c[1]) 48 | pos2=b.caseStr2Int(c[2]+c[3]) 49 | 50 | # Promotion asked ? 51 | promote='' 52 | if(len(c)>4): 53 | promote=c[4] 54 | if(promote=='q'): 55 | promote='q' 56 | elif(promote=='r'): 57 | promote='r' 58 | elif(promote=='n'): 59 | promote='n' 60 | elif(promote=='b'): 61 | promote='b' 62 | 63 | # Generate moves list to check 64 | # if the given move (pos1,pos2,promote) is correct 65 | mList=b.gen_moves_list() 66 | 67 | # The move is not in list ? or let the king in check ? 68 | if(((pos1,pos2,promote) not in mList) or \ 69 | (b.domove(pos1,pos2,promote)==False)): 70 | print("\n"+c+' : incorrect move or let king in check'+"\n") 71 | return 72 | 73 | # Display the chess board 74 | b.render() 75 | 76 | # Check if game is over 77 | self.print_result(b) 78 | 79 | # Let the engine play 80 | #self.search(b) 81 | 82 | #################################################################### 83 | 84 | def chkCmd(self,c): 85 | 86 | """Check if the command 'c' typed by user is like a move, 87 | i.e. 'e2e4','b7b8n'... 88 | Returns '' if correct. 89 | Returns a string error if not. 90 | """ 91 | 92 | err=( 93 | 'The move must be 4 or 5 letters : e2e4, b1c3, e7e8q...', 94 | 'Incorrect move.' 95 | ) 96 | letters=('a','b','c','d','e','f','g','h') 97 | numbers=('1','2','3','4','5','6','7','8') 98 | 99 | if(len(c)<4 or len(c)>5): 100 | return err[0] 101 | 102 | if(c[0] not in letters): 103 | return err[1] 104 | 105 | if(c[1] not in numbers): 106 | return err[1] 107 | 108 | if(c[2] not in letters): 109 | return err[1] 110 | 111 | if(c[3] not in numbers): 112 | return err[1] 113 | 114 | return '' 115 | 116 | #################################################################### 117 | 118 | def search(self,b): 119 | 120 | """Search the best move for the side to move, 121 | according to the given chessboard 'b' 122 | """ 123 | 124 | if(self.endgame): 125 | self.print_result(b) 126 | return 127 | 128 | # TODO 129 | # search in opening book 130 | 131 | self.clear_pv() 132 | self.nodes=0 133 | b.ply=0 134 | 135 | print("ply\tnodes\tscore\tpv") 136 | 137 | for i in range(1,self.init_depth+1): 138 | 139 | score=self.alphabeta(i,-self.INFINITY,self.INFINITY,b) 140 | 141 | print("{}\t{}\t{}\t".format(i,self.nodes,score/10),end='') 142 | 143 | # print PV informations : ply, nodes... 144 | j=0 145 | while(self.pv[j][j]!=0): 146 | c=self.pv[j][j] 147 | pos1=b.caseInt2Str(c[0]) 148 | pos2=b.caseInt2Str(c[1]) 149 | print("{}{}{}".format(pos1,pos2,c[2]),end=' ') 150 | j+=1 151 | print() 152 | 153 | # Break if MAT is found 154 | if(score>self.INFINITY-100 or score<-self.INFINITY+100): 155 | break 156 | 157 | # root best move found, do it, and print result 158 | best=self.pv[0][0] 159 | b.domove(best[0],best[1],best[2]) 160 | self.print_result(b) 161 | 162 | #################################################################### 163 | 164 | def alphabeta(self,depth,alpha,beta,b): 165 | 166 | # We arrived at the end of the search : return the board score 167 | if(depth==0): 168 | return b.evaluer() 169 | # TODO : return quiesce(alpha,beta) 170 | 171 | self.nodes+=1 172 | self.pv_length[b.ply] = b.ply 173 | 174 | # Do not go too deep 175 | if(b.ply >= self.MAX_PLY-1): 176 | return b.evaluer() 177 | 178 | # Extensions 179 | # If king is in check, let's go deeper 180 | chk=b.in_check(b.side2move) # 'chk' used at the end of func too 181 | if(chk): 182 | depth+=1 183 | 184 | # TODO 185 | # sort moves : captures first 186 | 187 | # Generate all moves for the side to move. Those who 188 | # let king in check will be processed in domove() 189 | mList=b.gen_moves_list() 190 | 191 | f=False # flag to know if at least one move will be done 192 | for i,m in enumerate(mList): 193 | 194 | # Do the move 'm'. 195 | # If it lets king in check, undo it and ignore it 196 | # remind : a move is defined with (pos1,pos2,promote) 197 | # i.e. : 'e7e8q' is (12,4,'q') 198 | if(not b.domove(m[0],m[1],m[2])): 199 | continue 200 | 201 | f=True # a move has passed 202 | 203 | score=-self.alphabeta(depth-1,-beta,-alpha,b) 204 | 205 | # Unmake move 206 | b.undomove() 207 | 208 | if(score>alpha): 209 | 210 | # TODO 211 | # this move caused a cutoff, 212 | # should be ordered higher for the next search 213 | 214 | if(score>=beta): 215 | return beta 216 | alpha = score 217 | 218 | # Updating the triangular PV-Table 219 | self.pv[b.ply][b.ply] = m 220 | j = b.ply + 1 221 | while(jself.MAX_PLY): 312 | print('Depth must be between 2 and',self.MAX_PLY) 313 | return 314 | 315 | # Things seems to be all right 316 | self.init_depth=d 317 | print('Depth set to',d) 318 | 319 | #################################################################### 320 | 321 | def perft(self,c,b): 322 | 323 | """PERFformance Test : 324 | This is a debugging function through the move generation tree 325 | for the current board until depth [x]. 326 | 'c' is the command line written by user : perft [x] 327 | """ 328 | 329 | # Checking the requested depth 330 | cmd=c.split() 331 | #cmd[0]='perft' 332 | 333 | try: 334 | d=int(cmd[1]) 335 | except ValueError: 336 | print('Please type an integer as depth i.e. : perft 5') 337 | return 338 | 339 | if(d<1 or d>self.MAX_PLY): 340 | print('Depth must be between 1 and',self.MAX_PLY) 341 | return 342 | 343 | print("Depth\tNodes\tCaptures\tE.p.\tCastles\tPromotions\tChecks\tCheckmates") 344 | 345 | time1 = self.get_ms() 346 | for i in range(1,d+1): 347 | total=self.perftoption(0,i-1,b) 348 | print("{}\t{}".format(i,total)) 349 | time2 = self.get_ms() 350 | timeDiff = round((time2-time1)/1000,2) 351 | print('Done in',timeDiff,'s') 352 | 353 | def perftoption(self,prof,limit,b): 354 | cpt=0 355 | 356 | if(prof>limit): 357 | return 0 358 | 359 | l=b.gen_moves_list() 360 | 361 | for i,m in enumerate(l): 362 | 363 | if(not b.domove(m[0],m[1],m[2])): 364 | continue 365 | 366 | cpt+=self.perftoption(prof+1,limit,b) 367 | 368 | if(limit==prof): 369 | cpt+=1 370 | 371 | b.undomove() 372 | 373 | return cpt 374 | 375 | #################################################################### 376 | 377 | def legalmoves(self,b): 378 | 379 | "Show legal moves for side to move" 380 | 381 | mList=b.gen_moves_list() 382 | 383 | cpt=1 384 | for m in mList: 385 | if(not b.domove(m[0],m[1],m[2])): 386 | continue 387 | print('move #',cpt,':',b.caseInt2Str(m[0])+b.caseInt2Str(m[1])+m[2]) 388 | b.undomove() 389 | cpt+=1 390 | 391 | #################################################################### 392 | 393 | def getboard(self,b): 394 | 395 | """The user requests the current FEN position 396 | with the command 'getboard'""" 397 | 398 | print(b.getboard()) 399 | 400 | #################################################################### 401 | 402 | def newgame(self,b): 403 | 404 | self.init() 405 | b.init() 406 | 407 | #################################################################### 408 | 409 | def bench(self,b): 410 | 411 | """Test to calculate the number of nodes a second. 412 | The position used is the 17th move of the game : 413 | Bobby Fischer vs. J. Sherwin, New Jersey State 414 | Open Championship, 9/2/1957 : 415 | 1rb2rk1/p4ppp/1p1qp1n1/3n2N1/2pP4/2P3P1/PPQ2PBP/R1B1R1K1 w - - 0 1 416 | The engine searches to a given depth, 3 following times. 417 | The kilonodes/s is calculated with the best time. 418 | """ 419 | 420 | oldDepth=self.init_depth 421 | self.init_depth=4 422 | timeDiff=[] 423 | 424 | # testing 3 times 425 | for i in range(3): 426 | 427 | print('Searching to depth',self.init_depth,'...') 428 | 429 | if(not b.setboard('1rb2rk1/p4ppp/1p1qp1n1/3n2N1/2pP4/2P3P1/PPQ2PBP/R1B1R1K1 w - - 0 1')): 430 | print('Could not set board ???!#!') 431 | return 432 | 433 | start_time=self.get_ms() 434 | self.search(b) 435 | stop_time=self.get_ms() 436 | timeDiff.append(stop_time-start_time) 437 | print('Time:',timeDiff[i],'ms\n') 438 | 439 | if(timeDiff[1] < timeDiff[0]): 440 | timeDiff[0] = timeDiff[1] 441 | if(timeDiff[2] < timeDiff[0]): 442 | timeDiff[0] = timeDiff[2] 443 | 444 | print('Best time:',timeDiff[0],'ms') 445 | print('Nodes:',self.nodes) 446 | print('Nodes per second:',round(self.nodes/timeDiff[0],2),'kn/s') 447 | 448 | # Restoring changed values 449 | self.init_depth=oldDepth 450 | 451 | #################################################################### 452 | 453 | def undomove(self,b): 454 | 455 | "The user requested a 'undomove' in command line" 456 | 457 | b.undomove() 458 | self.endgame=False 459 | 460 | #################################################################### 461 | 462 | def get_ms(self): 463 | return int(round(time.time() * 1000)) 464 | 465 | #################################################################### 466 | 467 | def init(self): 468 | self.endgame=False 469 | self.init_depth=4 # search in fixed depth 470 | self.nodes=0 # number of nodes 471 | self.clear_pv() 472 | 473 | #################################################################### 474 | 475 | 476 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /board.py: -------------------------------------------------------------------------------- 1 | ######################################################################## 2 | # JeffProd Simple Python Chess Program 3 | ######################################################################## 4 | # AUTHOR : Jean-Francois GAZET 5 | # WEB : http://www.jeffprod.com 6 | # TWITTER : @JeffProd 7 | # MAIL : jeffgazet@gmail.com 8 | # LICENCE : GNU GENERAL PUBLIC LICENSE Version 2, June 1991 9 | ######################################################################## 10 | 11 | from piece import * 12 | import os # for clear ou cls 13 | 14 | class Board: 15 | 16 | "The chess board" 17 | 18 | # Names of the 64 sqares 19 | coord=[ 20 | 'a8','b8','c8','d8','e8','f8','g8','h8', 21 | 'a7','b7','c7','d7','e7','f7','g7','h7', 22 | 'a6','b6','c6','d6','e6','f6','g6','h6', 23 | 'a5','b5','c5','d5','e5','f5','g5','h5', 24 | 'a4','b4','c4','d4','e4','f4','g4','h4', 25 | 'a3','b3','c3','d3','e3','f3','g3','h3', 26 | 'a2','b2','c2','d2','e2','f2','g2','h2', 27 | 'a1','b1','c1','d1','e1','f1','g1','h1', 28 | ] 29 | 30 | #################################################################### 31 | 32 | def __init__(self): 33 | self.init() 34 | 35 | #################################################################### 36 | 37 | def init(self): 38 | 39 | "Init the chess board at starting position" 40 | 41 | # Chessboard has 64 squares, numbered from 0 to 63 (a8 to h1) 42 | # Placing pieces ('cases' is 'square' in french :) 43 | self.cases = [ 44 | Piece('TOUR','noir'),Piece('CAVALIER','noir'),Piece('FOU','noir'),Piece('DAME','noir'),Piece('ROI','noir'),Piece('FOU','noir'),Piece('CAVALIER','noir'),Piece('TOUR','noir'), 45 | Piece('PION','noir'),Piece('PION','noir'),Piece('PION','noir'),Piece('PION','noir'),Piece('PION','noir'),Piece('PION','noir'),Piece('PION','noir'),Piece('PION','noir'), 46 | Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(), 47 | Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(), 48 | Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(), 49 | Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(),Piece(), 50 | Piece('PION','blanc'),Piece('PION','blanc'),Piece('PION','blanc'),Piece('PION','blanc'),Piece('PION','blanc'),Piece('PION','blanc'),Piece('PION','blanc'),Piece('PION','blanc'), 51 | Piece('TOUR','blanc'),Piece('CAVALIER','blanc'),Piece('FOU','blanc'),Piece('DAME','blanc'),Piece('ROI','blanc'),Piece('FOU','blanc'),Piece('CAVALIER','blanc'),Piece('TOUR','blanc') 52 | ] 53 | 54 | self.side2move='blanc' 55 | self.ep=-1 # the number of the square where to take 'en pasant' 56 | self.history=[] # the moves history 57 | self.ply=0 # half-move number since the start 58 | 59 | # Castle rights 60 | self.white_can_castle_56=True 61 | self.white_can_castle_63=True 62 | self.black_can_castle_0=True 63 | self.black_can_castle_7=True 64 | 65 | #################################################################### 66 | 67 | def gen_moves_list(self,color='',dontCallIsAttacked=False): 68 | 69 | """Returns all possible moves for the requested color. 70 | If color is not given, it is considered as the side to move. 71 | dontCallIsAttacked is a boolean flag to avoid recursive calls, 72 | due to the actually wrotten is_attacked() function calling 73 | this gen_moves_list() function. 74 | A move is defined as it : 75 | - the number of the starting square (pos1) 76 | - the number of the destination square (pos2) 77 | - the name of the piece to promote '','q','r','b','n' 78 | (queen, rook, bishop, knight) 79 | """ 80 | 81 | if(color==''): 82 | color=self.side2move 83 | mList=[] 84 | 85 | # For each 'piece' on the board (pos1 = 0 to 63) 86 | for pos1,piece in enumerate(self.cases): 87 | 88 | # Piece (or empty square) color is not the wanted ? pass 89 | if piece.couleur!=color: 90 | continue 91 | 92 | if(piece.nom=='ROI'): # KING 93 | mList+=piece.pos2_roi(pos1,self.oppColor(color),self,dontCallIsAttacked) 94 | continue 95 | 96 | elif(piece.nom=='DAME'): # QUEEN = ROOK + BISHOP moves ! 97 | mList+=piece.pos2_tour(pos1,self.oppColor(color),self) 98 | mList+=piece.pos2_fou(pos1,self.oppColor(color),self) 99 | continue 100 | 101 | elif(piece.nom=='TOUR'): # ROOK 102 | mList+=piece.pos2_tour(pos1,self.oppColor(color),self) 103 | continue 104 | 105 | elif(piece.nom=='CAVALIER'): # KNIGHT 106 | mList+=piece.pos2_cavalier(pos1,self.oppColor(color),self) 107 | continue 108 | 109 | elif(piece.nom=='FOU'): # BISHOP 110 | mList+=piece.pos2_fou(pos1,self.oppColor(color),self) 111 | continue 112 | 113 | if(piece.nom=='PION'): # PAWN 114 | mList+=piece.pos2_pion(pos1,piece.couleur,self) 115 | continue 116 | 117 | return mList 118 | 119 | #################################################################### 120 | 121 | def setboard(self,fen): 122 | 123 | """Set the board to the FEN position given. i.e. : 124 | rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - - 0 125 | Returns TRUE or FALSE if done or not. 126 | If not : print errors. 127 | """ 128 | 129 | f=fen.split() 130 | err="" 131 | 132 | if(len(f)!=6): 133 | err+="Wrong FEN notation. It should be :\n" 134 | err+="[pieces] [side to move] [castle rights] [ep] [plys] [move number]\n" 135 | err+="i.e. : rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1\n" 136 | print(err) 137 | return False 138 | 139 | self.init() 140 | self.white_can_castle_56=False 141 | self.white_can_castle_63=False 142 | self.black_can_castle_0=False 143 | self.black_can_castle_7=False 144 | 145 | fen = f[0] # rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR 146 | trait = f[1] # b ou w (black,white) 147 | roque = f[2] # KQkq 148 | ep = f[3] # e3 149 | rule50= f[4] # 0 (half-moves since start of game for 50 moves rule) 150 | num = f[5] # move number 151 | 152 | # Setting pieces 153 | i=0 154 | for c in fen: 155 | if(c=='k'): 156 | self.cases[i]=Piece('ROI','noir') 157 | i=i+1 158 | elif(c=='q'): 159 | self.cases[i]=Piece('DAME','noir') 160 | i=i+1 161 | elif(c=='r'): 162 | self.cases[i]=Piece('TOUR','noir') 163 | i=i+1 164 | elif(c=='n'): 165 | self.cases[i]=Piece('CAVALIER','noir') 166 | i=i+1 167 | elif(c=='b'): 168 | self.cases[i]=Piece('FOU','noir') 169 | i=i+1 170 | elif(c=='p'): 171 | self.cases[i]=Piece('PION','noir') 172 | i=i+1 173 | elif(c=='K'): 174 | self.cases[i]=Piece('ROI','blanc') 175 | i=i+1 176 | elif(c=='Q'): 177 | self.cases[i]=Piece('DAME','blanc') 178 | i=i+1 179 | elif(c=='R'): 180 | self.cases[i]=Piece('TOUR','blanc') 181 | i=i+1 182 | elif(c=='N'): 183 | self.cases[i]=Piece('CAVALIER','blanc') 184 | i=i+1 185 | elif(c=='B'): 186 | self.cases[i]=Piece('FOU','blanc') 187 | i=i+1 188 | elif(c=='P'): 189 | self.cases[i]=Piece('PION','blanc') 190 | i=i+1 191 | elif(c=='/'): 192 | pass 193 | else: # a number of empty squares is given 194 | try: 195 | nb=int(c) 196 | except ValueError: 197 | print('Error : wrong FEN. Integer expected.') 198 | return 199 | cpt=0 200 | while(cpt0): 265 | s+=str(emptySq) 266 | emptySq=0 267 | s+='/' 268 | 269 | if(piece.isEmpty()): 270 | emptySq+=1 271 | 272 | elif(p=='ROI'): 273 | if(emptySq>0): 274 | s+=str(emptySq) 275 | emptySq=0 276 | if(c=='noir'): 277 | s+='k' 278 | else: 279 | s+='K' 280 | 281 | elif(p=='DAME'): 282 | if(emptySq>0): 283 | s+=str(emptySq) 284 | emptySq=0 285 | if(c=='noir'): 286 | s+='q' 287 | else: 288 | s+='Q' 289 | 290 | elif(p=='TOUR'): 291 | if(emptySq>0): 292 | s+=str(emptySq) 293 | emptySq=0 294 | if(c=='noir'): 295 | s+='r' 296 | else: 297 | s+='R' 298 | 299 | elif(p=='CAVALIER'): 300 | if(emptySq>0): 301 | s+=str(emptySq) 302 | emptySq=0 303 | if(c=='noir'): 304 | s+='n' 305 | else: 306 | s+='N' 307 | 308 | elif(p=='FOU'): 309 | if(emptySq>0): 310 | s+=str(emptySq) 311 | emptySq=0 312 | if(c=='noir'): 313 | s+='b' 314 | else: 315 | s+='B' 316 | 317 | elif(p=='PION'): 318 | if(emptySq>0): 319 | s+=str(emptySq) 320 | emptySq=0 321 | if(c=='noir'): 322 | s+='p' 323 | else: 324 | s+='P' 325 | 326 | if(emptySq>0): 327 | s+=str(emptySq) 328 | 329 | # b or w (black,white) 330 | if(self.side2move=='blanc'): 331 | s+=' w ' 332 | else: 333 | s+=' b ' 334 | 335 | # Castle rights (KQkq) 336 | no_castle_right=True 337 | if(self.white_can_castle_63): 338 | s+='K' 339 | no_castle_right=False 340 | if(self.white_can_castle_56): 341 | s+='Q' 342 | no_castle_right=False 343 | if(self.black_can_castle_7): 344 | s+='k' 345 | no_castle_right=False 346 | if(self.black_can_castle_0): 347 | s+='q' 348 | no_castle_right=False 349 | if(no_castle_right): 350 | s+='-' 351 | 352 | # prise en passant e3 353 | if(self.ep!=-1): 354 | s+=' '+self.coord[self.ep] 355 | else: 356 | s+=' -' 357 | 358 | # TODO 359 | # number of half-moves for 50 moves rule 360 | s+=' -' 361 | 362 | # numéro du coup 363 | s+=' '+str(int(len(self.history)/2)) 364 | 365 | return s 366 | 367 | #################################################################### 368 | 369 | def domove(self,depart,arrivee,promote): 370 | 371 | """Move a piece on the board from the square numbers 372 | 'depart' to 'arrivee' (0..63) respecting rules : 373 | - prise en passant 374 | - promote and under-promote 375 | - castle rights 376 | Returns : 377 | - TRUE if the move do not let king in check 378 | - FALSE otherwise and undomove is done. 379 | """ 380 | 381 | # Debugging tests 382 | #if(self.cases[depart].isEmpty()): 383 | # print('domove() ERROR : asked for an empty square move : ',depart,arrivee,promote) 384 | # return 385 | #if(int(depart)<0 or int(depart)>63): 386 | # print('domove() ERROR : incorrect FROM square number : ',depart) 387 | # return 388 | #if(int(arrivee)<0 or int(arrivee)>63): 389 | # print('domove() ERROR : incorrect TO square number : ',arrivee) 390 | # return 391 | #if(not(promote=='' or promote=='q' or promote=='r' or promote=='n' or promote=='b')): 392 | # print('domove() ERROR : incorrect promote : ',promote) 393 | # return 394 | 395 | # Informations to save in the history moves 396 | pieceDeplacee=self.cases[depart] # moved piece 397 | piecePrise=self.cases[arrivee] # taken piece, can be null : Piece() 398 | isEp=False # will be used to undo a ep move 399 | histEp=self.ep # saving the actual ep square (-1 or square number TO) 400 | hist_roque_56=self.white_can_castle_56 401 | hist_roque_63=self.white_can_castle_63 402 | hist_roque_0=self.black_can_castle_0 403 | hist_roque_7=self.black_can_castle_7 404 | flagViderEp=True # flag to erase ep or not : if the pawn moved is not taken directly, it can't be taken later 405 | 406 | # Moving piece 407 | self.cases[arrivee]=self.cases[depart] 408 | self.cases[depart]=Piece() 409 | 410 | self.ply+=1 411 | 412 | # a PAWN has been moved ------------------------------------- 413 | if(pieceDeplacee.nom=='PION'): 414 | 415 | # White PAWN 416 | if(pieceDeplacee.couleur=='blanc'): 417 | 418 | # If the move is "en passant" 419 | if(self.ep==arrivee): 420 | piecePrise=self.cases[arrivee+8] # take black pawn 421 | self.cases[arrivee+8]=Piece() 422 | isEp=True 423 | 424 | # The white pawn moves 2 squares from starting square 425 | # then blacks can take "en passant" next move 426 | elif(self.ROW(depart)==6 and self.ROW(arrivee)==4): 427 | self.ep=arrivee+8 428 | flagViderEp=False 429 | 430 | # Black PAWN 431 | else: 432 | 433 | if(self.ep==arrivee): 434 | piecePrise=self.cases[arrivee-8] 435 | self.cases[arrivee-8]=Piece() 436 | isEp=True 437 | 438 | elif(self.ROW(depart)==1 and self.ROW(arrivee)==3): 439 | self.ep=arrivee-8 440 | flagViderEp=False 441 | 442 | # a ROOK has been moved-------------------------------------- 443 | # update castle rights 444 | 445 | elif(pieceDeplacee.nom=='TOUR'): 446 | 447 | # White ROOK 448 | if(pieceDeplacee.couleur=='blanc'): 449 | if(depart==56): 450 | self.white_can_castle_56=False 451 | elif(depart==63): 452 | self.white_can_castle_63=False 453 | 454 | # Black ROOK 455 | else: 456 | if(depart==0): 457 | self.black_can_castle_0=False 458 | elif(depart==7): 459 | self.black_can_castle_7=False 460 | 461 | # a KING has been moved----------------------------------------- 462 | 463 | elif(pieceDeplacee.nom=='ROI'): 464 | 465 | # White KING 466 | if(pieceDeplacee.couleur=='blanc'): 467 | 468 | # moving from starting square 469 | if(depart==60): 470 | # update castle rights 471 | self.white_can_castle_56=False 472 | self.white_can_castle_63=False 473 | 474 | # If castling, move the rook 475 | if(arrivee==58): 476 | self.cases[56]=Piece() 477 | self.cases[59]=Piece('TOUR','blanc') 478 | 479 | elif(arrivee==62): 480 | self.cases[63]=Piece() 481 | self.cases[61]=Piece('TOUR','blanc') 482 | 483 | # Black KING 484 | else: 485 | 486 | if(depart==4): 487 | self.black_can_castle_0=False 488 | self.black_can_castle_7=False 489 | 490 | if(arrivee==6): 491 | self.cases[7]=Piece() 492 | self.cases[5]=Piece('TOUR','noir') 493 | 494 | elif(arrivee==2): 495 | self.cases[0]=Piece() 496 | self.cases[3]=Piece('TOUR','noir') 497 | 498 | # End pieces cases----------------------------------------------- 499 | 500 | # Any move cancels the ep move 501 | if(flagViderEp==True): 502 | self.ep=-1 503 | 504 | # Promote : the pawn is changed to requested piece 505 | if(promote!=''): 506 | if(promote=='q'): 507 | self.cases[arrivee]=Piece('DAME',self.side2move) 508 | elif(promote=='r'): 509 | self.cases[arrivee]=Piece('TOUR',self.side2move) 510 | elif(promote=='n'): 511 | self.cases[arrivee]=Piece('CAVALIER',self.side2move) 512 | elif(promote=='b'): 513 | self.cases[arrivee]=Piece('FOU',self.side2move) 514 | 515 | # Change side to move 516 | self.changeTrait() 517 | 518 | # Save move to the history list 519 | self.history.append((depart,\ 520 | arrivee,\ 521 | pieceDeplacee,\ 522 | piecePrise,\ 523 | isEp,\ 524 | histEp,\ 525 | promote,\ 526 | hist_roque_56,\ 527 | hist_roque_63,\ 528 | hist_roque_0,\ 529 | hist_roque_7)) 530 | 531 | # If the move lets king in check, undo it and return false 532 | if(self.in_check(self.oppColor(self.side2move))): 533 | self.undomove() 534 | return False 535 | 536 | return True 537 | 538 | #################################################################### 539 | 540 | def undomove(self): 541 | 542 | "Undo the last move in history" 543 | 544 | if(len(self.history)==0): 545 | print('No move played') 546 | return 547 | 548 | # The last move in history is : self.historique[-1] 549 | lastmove=self.history[-1] 550 | 551 | pos1=lastmove[0] 552 | pos2=lastmove[1] 553 | piece_deplacee=lastmove[2] 554 | piece_prise=lastmove[3] 555 | isEp=lastmove[4] 556 | ep=lastmove[5] 557 | promote=lastmove[6] 558 | self.white_can_castle_56=lastmove[7] 559 | self.white_can_castle_63=lastmove[8] 560 | self.black_can_castle_0=lastmove[9] 561 | self.black_can_castle_7 =lastmove[10] 562 | 563 | self.ply-=1 564 | 565 | # Change side to move 566 | self.changeTrait() 567 | 568 | # Replacing piece on square number 'pos1' 569 | self.cases[pos1]=self.cases[pos2] 570 | 571 | # Square where we can take "en pasant" 572 | self.ep=ep 573 | 574 | # If undoing a promote, the piece was a pawn 575 | if(promote!=''): 576 | self.cases[pos1]=Piece('PION',self.side2move) 577 | 578 | # Replacing capture piece on square 'pos2' 579 | self.cases[pos2]=piece_prise 580 | 581 | # Switch the piece we have replaced to 'pos1'------------------- 582 | if(self.cases[pos1].nom=='PION'): 583 | # If a pawn has been taken "en passant", replace it 584 | if(isEp): 585 | self.cases[pos2]=Piece() 586 | if(self.cases[pos1].couleur=='noir'): 587 | self.cases[pos2-8]=Piece('PION','blanc') 588 | else: 589 | self.cases[pos2+8]=Piece('PION','noir') 590 | 591 | # Replacing KING ----------------------------------------------- 592 | elif(self.cases[pos1].nom=='ROI'): 593 | 594 | # White KING 595 | if(self.cases[pos1].couleur=='blanc'): 596 | # Replacing on initial square 597 | if(pos1==60): 598 | # If the move was castle, replace ROOK 599 | if(pos2==58): 600 | self.cases[56]=Piece('TOUR','blanc') 601 | self.cases[59]=Piece() 602 | elif(pos2==62): 603 | self.cases[63]=Piece('TOUR','blanc') 604 | self.cases[61]=Piece() 605 | # Black KING 606 | else: 607 | if(pos1==4): 608 | if(pos2==2): 609 | self.cases[0]=Piece('TOUR','noir') 610 | self.cases[3]=Piece() 611 | elif(pos2==6): 612 | self.cases[7]=Piece('TOUR','noir') 613 | self.cases[5]=Piece() 614 | # End switch piece---------------------------------------------- 615 | 616 | # Delete the last move from history 617 | self.history.pop() 618 | 619 | #################################################################### 620 | 621 | def changeTrait(self): 622 | 623 | "Change the side to move" 624 | 625 | if(self.side2move=='blanc'): 626 | self.side2move='noir' 627 | else: 628 | self.side2move='blanc' 629 | 630 | #################################################################### 631 | 632 | def oppColor(self,c): 633 | 634 | "Returns the opposite color of the 'c' color given" 635 | 636 | if(c=='blanc'): 637 | return 'noir' 638 | else: 639 | return 'blanc' 640 | 641 | #################################################################### 642 | 643 | def in_check(self,couleur): 644 | 645 | """Returns TRUE or FALSE 646 | if the KING of the given 'color' is in check""" 647 | 648 | # Looking for the id square where is the king 649 | # sure, we can code better to avoid this and win kn/s... 650 | for i in range(0,64): 651 | if(self.cases[i].nom=='ROI' and self.cases[i].couleur==couleur): 652 | pos=i 653 | break 654 | 655 | return self.is_attacked(pos,self.oppColor(couleur)) 656 | 657 | #################################################################### 658 | 659 | def is_attacked(self,pos,couleur): 660 | 661 | """Returns TRUE or FALSE if the square number 'pos' is a 662 | destination square for the color 'couleur'. 663 | If so we can say that 'pos' is attacked by this side. 664 | This function is used for 'in check' and for castle moves.""" 665 | 666 | mList=self.gen_moves_list(couleur,True) 667 | 668 | for pos1,pos2,promote in mList: 669 | if(pos2==pos): 670 | return True 671 | 672 | return False 673 | 674 | #################################################################### 675 | 676 | def render(self): 677 | 678 | "Display the chessboard in console mode" 679 | 680 | input("\nType a key to continue...") 681 | os.system('cls' if os.name == 'nt' else 'clear') 682 | 683 | print('') 684 | print('=> Commands are :') 685 | print('- "new" for a new game') 686 | print('- "e2e4" for example, to move a piece') 687 | print('- "e7e8q" for a promote move to queen ("r" for rook, "n" for knight, "b" for bishop)') 688 | print('- "legalmoves" show legal moves for side to move') 689 | print('- "undomove" to cancel the last move') 690 | print('- "go" asks the engine to play now') 691 | print('- "setboard [fen]" to set the board as the FEN notation given') 692 | print('- "getboard" to export the current FEN board position') 693 | print('- "sd [x]" to set the depth search') 694 | print('- "perft [x]" : test the move generator (x = search depth)') 695 | print('- "quit"... to quit') 696 | print('') 697 | 698 | print('8',end=' ') 699 | i,y=1,7 700 | for piece in self.cases: 701 | if(piece.couleur=='noir'): 702 | print(piece.nom[0].lower(),end=' ') 703 | else: 704 | print(piece.nom[0],end=' ') 705 | 706 | if(i%8==0): 707 | print() 708 | print() 709 | if(y>0): 710 | print(str(y),end=' ') 711 | y=y-1 712 | 713 | i+=1 714 | print(' a b c d e f g h') 715 | 716 | print('Side to move : '+self.side2move) 717 | 718 | if(self.ep!=-1): 719 | print('"en passant" possible in',self.coord[self.ep]) 720 | 721 | # Displaying castle rights 722 | no_castle_right=True 723 | print('Castle rights : ',end='') 724 | if(self.white_can_castle_63): 725 | print('K',end='') 726 | no_castle_right=False 727 | if(self.white_can_castle_56): 728 | print('Q',end='') 729 | no_castle_right=False 730 | if(self.black_can_castle_7): 731 | print('k',end='') 732 | no_castle_right=False 733 | if(self.black_can_castle_0): 734 | print('q',end='') 735 | no_castle_right=False 736 | if(no_castle_right): 737 | print('-',end='') 738 | print() 739 | 740 | # Displaying moves done from the history 741 | self.showHistory() 742 | 743 | #################################################################### 744 | 745 | def caseStr2Int(self,c): 746 | 747 | """'c' given in argument is a square name like 'e2' 748 | "This functino returns a square number like 52""" 749 | 750 | err=( 751 | 'The square name must be 2 caracters i.e. e2,e4,b1...', 752 | 'Incorrect square name. Please enter i.e. e2,e4,b1...' 753 | ) 754 | letters=('a','b','c','d','e','f','g','h') 755 | numbers=('1','2','3','4','5','6','7','8') 756 | 757 | if(len(c)!=2): 758 | print(err[0]) 759 | return -1 760 | 761 | if(c[0] not in letters): 762 | print(err[1]) 763 | return -1 764 | 765 | if(c[1] not in numbers): 766 | print(err[1]) 767 | return -1 768 | 769 | return self.coord.index(c) 770 | 771 | #################################################################### 772 | 773 | def caseInt2Str(self,i): 774 | 775 | """Given in argument : an integer between 0 and 63 776 | Returns a string like 'e2'""" 777 | 778 | err=( 779 | 'Square number must be in 0 to 63', 780 | ) 781 | letters=('a','b','c','d','e','f','g','h') 782 | numbers=('1','2','3','4','5','6','7','8') 783 | 784 | if(i<0 or i>63): 785 | print(err[0]) 786 | return 787 | 788 | return self.coord[i] 789 | 790 | #################################################################### 791 | 792 | @staticmethod 793 | def ROW(x): 794 | """ROW returns the number of the row from 0(a8-h8) to 7(a1-h1) 795 | in which is the square 'x'""" 796 | return (x >> 3) 797 | 798 | #################################################################### 799 | 800 | @staticmethod 801 | def COL(x): 802 | """COL returns the number of the colon (from 0 to 7) 803 | in which is the square 'x'""" 804 | return (x & 7) 805 | 806 | #################################################################### 807 | 808 | def showHistory(self): 809 | 810 | "Displays the history of the moves played" 811 | 812 | if(len(self.history)==0): 813 | return 814 | 815 | print() 816 | cpt,aff=1.0,True 817 | for (depart,\ 818 | arrivee,\ 819 | pieceDeplacee,\ 820 | piecePrise,\ 821 | isEp,\ 822 | histEp,\ 823 | promote,\ 824 | roque56,\ 825 | roque63,\ 826 | roque0,\ 827 | roque7) in self.history: 828 | a=self.caseInt2Str(depart) 829 | b=self.caseInt2Str(arrivee) 830 | if(piecePrise.isEmpty()==False): 831 | a=a+'x' 832 | if(promote!=''): 833 | b=b+promote 834 | if(aff==True): 835 | print("{}.{}{} ".format(int(cpt),a,b),end=' ') 836 | aff=False 837 | else: 838 | print("{}{} ".format(a,b),end=' ') 839 | aff=True 840 | cpt+=0.5 841 | print() 842 | print() 843 | 844 | #################################################################### 845 | 846 | def evaluer(self): 847 | 848 | """A wonderful evaluate() function 849 | returning actually only the material score""" 850 | 851 | WhiteScore=0 852 | BlackScore=0 853 | 854 | # Parsing the board squares from 0 to 63 855 | for pos1,piece in enumerate(self.cases): 856 | 857 | # Material score 858 | if(piece.couleur=='blanc'): 859 | WhiteScore+=piece.valeur 860 | else: 861 | # NB : here is for black piece or empty square 862 | BlackScore+=piece.valeur 863 | 864 | if(self.side2move=='blanc'): 865 | return WhiteScore-BlackScore 866 | else: 867 | return BlackScore-WhiteScore 868 | 869 | #################################################################### 870 | --------------------------------------------------------------------------------