如何在pygame中伪造鼠标事件?

时间:2018-12-08 16:46:03

标签: python pygame

我正在尝试创建一个玩俄罗斯方块游戏的机器人,但是在源代码(它具有GUI界面)中,我必须按一下播放按钮才能开始新游戏。但是由于我希望该机器人玩这个游戏,超越/跳过“播放按钮”。我在Python中使用pygame库。如何创建此类事件或规避按下“播放”按钮的事实?

1 个答案:

答案 0 :(得分:2)

可以通过以下方式创建鼠标(或任何其他事件):创建一个pygame.event.Event实例,并将事件类型(链接页面顶部有一个列表)和相关属性作为字典传递或关键字参数(在这种情况下为posbutton)。

mouse_event = pg.event.Event(pg.MOUSEBUTTONDOWN, {'pos': (245, 221), 'button': 1})

此事件需要使用pygame.event.post函数添加到事件队列中,以便可以在事件循环中对其进行处理。一个最小的完整示例:

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
button = pg.Rect(200, 200, 90, 40)
# Create an Event instance and pass the event type
# and a dict with the necessary event attributes.
mouse_event = pg.event.Event(pg.MOUSEBUTTONDOWN, {'pos': (245, 221), 'button': 1})

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEBUTTONDOWN:
            if button.collidepoint(event.pos):
                print('collision')

    # I just add the event to the queue once per frame.
    pg.event.post(mouse_event)

    screen.fill(BG_COLOR)
    pg.draw.rect(screen, BLUE, button)
    pg.display.flip()
    clock.tick(60)

pg.quit()