如何解决我在pygame中的游戏无法正常运行
我正在尝试用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
),则鼠标位置存储在pygame.event.Event()
对象的pos
属性中:
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,50)
if rect2.collidepoint(event.pos):
mouse_clicked2 = True
screen.fill(bg_color)
if mouse_clicked1:
screen.blit(x,object_top)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。