Chess Engine in Python – Part 2 – Moving the pieces

In this video you will learn how to use user input to move the pieces on the chess board. We will handle invalid moves in a later video.

67 Comments

  1. It's great! I'm loving this course so much!!
    Eddie what's your username in chess.com? Then we can play

  2. Thanks for the videos! I have a question….

    When defining "col" and "row" variable, why do you divide the location[index] by square size?

    Thanks again!

  3. Thanks for the tutorial. But it seems like I have a little "Unwanted features". the pieces do move but there is the same moved image in the location that it previously was but under the board. How do I fix this? I tried to make sure the Board was drawn first than pieces.
    edit: fixed it.
    My screen was set as white but the board was transparent. So the image of the previous set was shown straight through the back.
    Had to set the screen.fill at drawBoard to avoid it.

  4. Can you please please show us how to do the same thing you've done with the row and col, for detecting the clicks, but when it's not actually the whole entire screen

  5. I get the following error:

    return self.getRankFile(self.startRow, self.startCol) + self.getRankfile(self.endRow, self.endCol)
    AttributeError: 'Move' object has no attribute 'getRankfile'

    any help would be greatly appreciated

  6. dear sir nice video explanation but sorry to say you have to increase a font size of your ide terminal

  7. Bro I have a channel all you need to remember is subscribe my channel😁,your content are very useful and easy 😉 keep doing it

  8. great video but my peices does only move in rows

  9. Best bug ever in this version of the script is to click on an empty square and then on a piece to remove the piece.

  10. File "D:downloadchesspythonChessMain.py", line 72, in <module>

    main()

    File "D:downloadchesspythonChessMain.py", line 42, in main

    move = ChessEngine.Move(playerClicks[0],playerClicks[1],gs.board)

    File "D:downloadchesspythonPCSChessEngine.py", line 35, in _init_

    self.startRow = startSq[0]

    IndexError: tuple index out of range

    it says this and I can't fix it.

  11. finally got the fen support done…
    oof

  12. i can use Visual studio for this project ?

  13. As someone mentioned in comments, if you click on an empty square then on the piece, the piece disappears.
    I patched this with adding IF check in makeMove:

    def makeMove(self, move):
    if self.board[move.startRow][move.startCol] != '–':
    self.board[move.startRow][move.startCol] = '–'
    self.board[move.endRow][move.endCol] = move.pieceMoved
    self.moveLog.append(move)
    self.whiteToMove = not self.whiteToMove

  14. Any one can help me , the pieces are not moving but the notations are displaying on the terminal as its moving .plzzz help me I don't know what to do

  15. Will there be a Github for the whole thing? just wondering

  16. Wait, is it just me or is the whole screen flickering?

  17. There is not link to view the code or copy ? on the screen extremely difficult to see. 🙂
    Full of ads on top of that. Super ! 😛

  18. Great way to learn Python. I mean thank you!

  19. Can anyone please tell what are the libraries to be installed?

  20. line 46, in getChessNotation

    return self.getRankFile(self.startRow, self.startCol) + self.getRankFile(self.endRow, self.endCol)

    line 49, in getRankFile

    return self.colsToFiles[c] + self.rowsToRanks[r]

    AttributeError: 'Move' object has no attribute 'rowsToRanks'

    Help please

  21. I've triple checked my code but can't figure out why the pieces won't move

  22. Did anyone figure out how to highlight the first selected square?

  23. Это лучшее из всего, что мне доводилось видеть! OMG! Как же ты крут!

  24. the pieces do move but there is the same moved image in the location that it previously was but under the board. How do I fix this?

  25. To get the modern chess notation used on most sites (like lichess) something like this should work
    (I haven't tried it, just casually watching the video and thought i'd make an input)
    def getChessNotation(self):

    notation = ''

    if self.pieceCaptured is '–' and self.pieceMoved is not 'P':

    notation = self.pieceMoved + getRankFile(self.endRow, self.endCol)

    elif self.pieceCaptured is '–' and self.pieceMoved is 'P':

    notation = getRankFile(self.endRow, self.endCol)

    elif self.pieceCaptured is not '–':

    notation = self.pieceMoved + 'X' + + getRankFile(self.endRow, self.endCol)

    return notation

    More logic would have to be added for special moves like castling and en passant. and also the case where two pieces can move to the same square

  26. Can some really help me here. My pieces are moving but I can't print the chess notation. Instead it gives me this
    <bound method Move.getChessNotation of <CEtest.Move object at 0x0000015D92D7DA20>>

    def __init__(self, startSq, endSq, board): # borad = current board state

    # maping keys to values "using dictionary to key value where vlaue will cause imagary to move"

    #key : value

    ranksToRows = {"1":7,"2":6,"3":5,"4":4,"5":3,"6":2,"7":1,"8":0}

    rowsToRanks = {v:k for k, v in ranksToRows.items()} # for loop reversing the dictionary

    filesToCols = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7}

    colsToFiles = {v:k for k, v in filesToCols.items()}
    # here i says that Pylance cannot recognize "rowsToRanks" and "colsToFiles"
    # These are the 2 methods
    def getChessNotation(self):

    # to make chess notation

    return self.getRankFile(self.startRow, self.startCol) + self.getRankFile(self.endRow, self.endCol)

    def getRankFile(self,r,c):

    return self.colsToFiles[c] + self.rowsToRanks[r]

    I am really stuck at this point for the past 4 days
    Please help me out here
    @Eddie Sharick

  27. i am getting a type error list not callable when i try to initialise the move object however after searching the error it says to use square brackets to index, i have done this and the error is still coming up. Also when i save the code to run the instantiation line for move starts a new line after move( for the parameters so i have no clue how to fix this can anyone help?
    heres the main code and the constructor
    def main():

    p.init()

    screen = p.display.set_mode((WIDTH, HEIGHT))

    clock = p.time.Clock()

    screen.fill(p.Color("black"))

    gs = chessEngine.GameState()

    loadImages()

    running = True

    global playerClick

    global sqSelected

    sqSelected = () # tracks last click of user (tuple)

    playerClick = [] # keeps track of player clicks (two tuples)

    while running:

    for e in p.event.get():

    if e.type == p.QUIT:

    running = False

    elif e.type == p.MOUSEBUTTONDOWN:

    location = p.mouse.get_pos() # (x,y) location of mouse

    col = location[0]//SQ_SIZE

    row = location[1]//SQ_SIZE

    if sqSelected == (row, col):

    sqSelected = ()

    playerClick = []

    else:

    # append for both first and second clicks

    sqSelected = (row, col)

    playerClick.append(sqSelected)

    if len(playerClick) == 2:

    move = chessEngine.Move(

    playerClick[0], playerClick[1], gs.board())

    gs.makeMove(move)

    playerClick = []

    sqSelected = ()

    drawGameState(screen, gs)

    clock.tick(MAX_FPS)

    p.display.flip()

    def __init__(self, startSq, endSq, board):

    self.startRow = startSq[0]

    self.startCol = startSq[1]

    self.endRow = endSq[0]

    self.endCol = endSq[1]

    self.pieceMoved = board[self.startRow][self.startCol]

    self.pieceCaptured = board[self.endRow][self.endCol]

  28. I m getting this error, when I follow this code. Can you help me figure out why am I getting this error and hwo to fix this. Thank you. Here is the error I m getting –
    45 self.piece_moved = board[self.startRow][self.startCol]
    46 self.piece_captured = board[self.endRow][self.endCol]

    TypeError: list indices must be integers or slices, not float

  29. i love u so much bro like u dont understand

  30. def makeMove(self, move):

    self.board[move.startrow][move.startcol] = '–'

    self.board[move.endrow][move.endcol] = move.pieceMoved

    self.MoveLog.append(move) #log move so we can undo later

    self.WhiteToMove = not self.WhiteToMove #switch turns

    which 'move' does move.startrow, etc, access? is it the move in main() that's: move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) ?

    or the class: Move()

    if it's the class, why isn't it the "m" capital? like so: self.board[Move.endrow]?

  31. Very useful tutorial
    Helped me to get started with pygame
    i want to use my own logic for engine development
    but i was kinda lost on GUI
    Thank you very much bro

  32. Is there a way to play human first and then via a file, inputting a PGN, moving alternatively? Human/File, Human/File… etc.? I am trying to modify your code but cannot see where could I do that. Could you offer some guidance?

  33. Heyy im new with this.
    Is it okay if i just copied what you just write.
    I feel what im doing is illegal:(

  34. can anyone please provide code for this project

  35. Can you post the code, muy english is avery bad and i get lost. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *