I'm trying to make tic tac toe with pygame. If you click in any one of the squares, an x will be displayed. The problem is that it takes a lot of clicks to display the x. here's the code:
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.quit()
sys.exit()
mouse_pos = pygame.mouse.get_pos()
event = pygame.event.wait()
screen.fill(bg_color)
if event.type == pygame.MOUSEBUTTONDOWN and 250 < mouse_pos[0] < 300 and 250 > mouse_pos[1] > 199:
mouse_clicked1 = True
if event.type == pygame.MOUSEBUTTONDOWN and 301 < mouse_pos[0] < 351 and 249 > mouse_pos[1] > 201:
mouse_clicked2 = True
if mouse_clicked1:
screen.blit(x, object_top_left)
if mouse_clicked2:
screen.blit(x, object_top)
pygame.event.wait()
waits for a single event from the queue. Remove the function a use the events which you get from pygame.event.get()
.
If the event type is MOUSEBUTTONDOWN
(or MOUSEBUTTONUP
), then the mouse position is stored in the pos
attribute of the pygame.event.Event()
object:
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN and 250 < event.pos[0] < 300 and 250 > event.pos[1] > 199:
mouse_clicked1 = True
if event.type == pygame.MOUSEBUTTONDOWN and 301 < event.pos[0] < 351 and 249 > event.pos[1] > 201:
mouse_clicked2 = True
screen.fill(bg_color)
if mouse_clicked1:
screen.blit(x, object_top_left)
if mouse_clicked2:
screen.blit(x, object_top)
Note, pygame.event.get()
get and removes all the events from the queue. Hence the call to pygame.event.wait()
in the loop, will rarely return any event.
Furthermore, I recommend to use pygame.Rect
objects and collidepoint()
:
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
rect1 = pygameRect(250, 200, 50, 50)
if rect1.collidepoint(event.pos):
mouse_clicked1 = True
rect2 = pygameRect(300, 200, 50, 50)
if rect2.collidepoint(event.pos):
mouse_clicked2 = True
screen.fill(bg_color)
if mouse_clicked1:
screen.blit(x, object_top_left)
if mouse_clicked2:
screen.blit(x, object_top)