我正在尝试用pygame井字游戏。如果单击任何一个正方形,将显示一个x。问题在于,要显示x,需要点击很多。这是代码:
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()
等待队列中的单个事件。使用从中获取的事件删除该函数pygame.event.get()
。
如果事件类型为MOUSEBUTTONDOWN
(或MOUSEBUTTONUP
),则鼠标位置存储在对象的pos
属性中pygame.event.Event()
:
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)
注意,pygame.event.get()
获取并从队列中删除所有事件。因此,pygame.event.wait()
循环中对的调用将很少返回任何事件。
此外,我建议使用pygame.Rect
对象和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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句