1

Ive been trying to make a chess game in Pygame and ive managed to draw the board, and all the pieces. Now im moving onto detecting if a piece has been clicked, but it says the piece has been selected in all the column (BISHOP)

def detectClick():
     pos = pygame.mouse.get_pos()
        
     if (0,0) <= pos <= (50,50):
          print('bb')
        

Ive tried math, but to no success. I have no clue as to why this bit isnt working

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
FritzPappo
  • 33
  • 3
  • how is trying to compare if the coordinates of the mouse are in the rectangle with diagonal (0,0) to (50,50) going to detect a click? – Sembei Norimaki Mar 26 '23 at 03:29

1 Answers1

1

if (0,0) <= pos <= (50,50): does not do what you expect. When comparing tuples, the first pair of elements that are not equal always determines the result of the comparison. Therefore, if the first elements are unequal, the others are not considered at all. You are trying to use the tuple for a 2D box test where both coordinates must satisfy a condition. You need to compare the items component by component

if 0 < pos[0] < 50 and 0 < pos[1] < 50:

In pygame you can use pygame.Rect.colliderect to test if a point is in a rectangle:

rect = pygame.Rect(0, 0, 50, 50)
if rect.collidepoint(pos):

However to get the column and row of a point in a grid you just need the // (floor division) operator e.g. for a grid with a cell size of 50:

pos = pygame.mouse.get_pos()
column = pos[0] // 50
row = pos[1] // 50

Also see

Rabbid76
  • 202,892
  • 27
  • 131
  • 174