How would I keep track of the users clicks on the chessboard?

Viewed 170

I'm using Python 3.7.4. I'm using Pycharm 2020 Community as my IDE. I'm using Pygame 1.9.6 as my game interpreter.

I was wondering on how I could keep track of the players click on the chess board. I was thinking it should should in my main() running operation, but where in it? So on a chessboard it's an 8x8 board, so 64 squares. Like say they click on the square once to select the square with a piece on it, then click on another square to move said piece to other square if the square is empty. An empty square on my chess board is: "01". Like do I need someway to get to the dimensions of the board say, like a row or a column? I have the dimensions of the board.

WIDTH = HEIGHT = 512  # 400 is another option
DIMENSION = 8  # dimensions of a chess board are 8x8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 15  # for animations later on
IMAGES = {}

def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    loadImages()  # only do this once, before the while loop
    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()

I've never done mouse clicks before so I was wondering on how I could do that?

2 Answers

You can get the mouse coordinates and divide it by SQ_SIZE, but use floor-division (mousex//SQ_Size), using the two division signs terminates the decimal point and you will be left with the index of the board. For example if you click at (230, 213), you could have...

if pygame.mouse.get_pressed()[0]: # Is the left mouse button down
    mousex, mousey = pygame.mouse.get_pos() # (230, 213)
    col = mousex // SQ_SIZE # 230 // 64 = 3
    row = mousey // SQ_SIZE # 213 // 64 = 3
    pieceSelected = chessBoard[row][col]

This would allow you to get the piece that the user clicked on.

The index of the clicked field can be computed by the // (floor division) operator. Get the MOUSEBUTTONDOWN event (see pygame.event) and divide the mouse position coordinates by SQ_SIZE:

def main():
    # [...]

    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

            if e.type == p.MOUSEBUTTONDOWN:
                mousePos = e.pos
                column, row = mousePos[0] // SQ_SIZE, mousePos[1] // SQ_SIZE
                columnName, rowName  = chr(ord('a') + column), str(row+1)
                print("clicked at " + columnName + rowName)
Related