Reputation: 131
Hi I am writing a chess game in pygame. The issue that I have is that when I want to highlight (with a red rectangle) a figure when it is clicked, it only happens for a brief moment, i.e. when the mouse is clicked. Then the refresh happens and the red rectangle vanishes. The code responsible for that is:
def window_redrawing():
# Drawing the background and chess board
win.fill(bg_col)
win.blit(chess_board, (53, 50))
initial_positions()
mouse_x, mouse_y = pygame.mouse.get_pos()
for objPawn in pawn_list:
if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
b = pygame.draw.rect(win, (255, 0, 0), objPawn.clickbox, 2)
pygame.display.update(b)
pygame.display.update()
My question: how can I draw the rectangle when the mouse is clicked so that it stays there, for a longer time? (let's say till the mouse is clicked again)
I have also tried out some other methods like the win.blit()
, as follows:
def window_redrawing():
# Drawing the background and chess board
win.fill(bg_col)
win.blit(chess_board, (53, 50))
initial_positions()
mouse_x, mouse_y = pygame.mouse.get_pos()
for objPawn in pawn_list:
if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
win.blit(objPawn.clickbox, (objPawn.start_x, objPawn.start_y))
But then I get a following error: TypeError: argument 1 must be pygame.Surface, not tuple
All help is appreciated, thanks!!!
Upvotes: 1
Views: 194
Reputation: 210968
Add an attribute clicked
to the class of the instances in pawn_list
(I don't know the actual name of the calss)
class Pawn: # I don't kow the actual name
def __init__(self)_
# [...]
self.clicked = False
Set the state when the object is clicked (objPawn.clicked = True
). Iterate through the objects in the list and draw the rectangle if the state clicked
is set:
def window_redrawing():
mouse_x, mouse_y = pygame.mouse.get_pos()
for objPawn in pawn_list:
if objPawn.start_x <= mouse_x <= objPawn.start_x + 86 and objPawn.start_y + 84 >= mouse_y >= objPawn.start_y:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
objPawn.clicked = True
# Drawing the background and chess board
win.fill(bg_col)
win.blit(chess_board, (53, 50))
for objPawn in pawn_list:
if objPawn.clicked:
pygame.draw.rect(win, (255, 0, 0), objPawn.clickbox, 2)
pygame.display.update()
Upvotes: 1