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

2024-04-20 11:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个玩俄罗斯方块的机器人游戏。但是在源代码(它有GUI界面)我要按播放按钮和新游戏开始。但是因为我想让机器人玩它,我必须超越/跳过“播放按钮”。我正在使用中的pygame库Python。怎么了我可以创建这样一个事件或绕过按下播放按钮的事实吗?你知道吗


Tags: 游戏界面源代码事件机器人guipygame事实
1条回答
网友
1楼 · 发布于 2024-04-20 11:07:17

鼠标(或任何其他事件)可以这样创建:创建一个^{}实例,并将事件类型(链接页顶部有一个列表)和相关属性作为字典或关键字参数传递(在本例中为posbutton)。你知道吗

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

需要使用^{}函数将此事件添加到事件队列中,以便在事件循环中处理它。一个简单完整的例子:

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()

相关问题 更多 >