和屏幕尺寸有什么关系

问题描述 投票:0回答:1
`from turtle import right
import pyautogui, time, random, pygame
from pygame.locals import *
time.sleep(3)
class Square(pygame.sprite.Sprite):
    def __init__(self):
        super(Square,self).__init__()
        self.surf = pygame.Surface((20,20))
    self.surf.fill((255,0,0))
    self.rect = self.surf.get_rect()
width,height = 960,540
screen = pygame.display.set_mode((width,height))
cont = True
square1 = Square()
while cont:
time.sleep(0.4)
x,y=random.randrange(int(1920/2- 
width/2),int(1920/2+width/2)),random.randrange(int(1080/2-height/2),int(1080/2+height/2))
screen.blit(square1.surf,(x,y))
pyautogui.click(x,y)
for event in pygame.event.get():
    if event.type == QUIT:
        cont=False
    elif event.type == KEYDOWN:
        if event.key == K_BACKSPACE:
            cont=False
pygame.display.flip()`

嗨,所以基本上我是Python新手,现在正在学习基本的pyautogui用法,并尝试制作这个无用的“游戏”,它应该将光标移动到某个点并在此时绘制一个正方形,并且当屏幕显示时一切都工作得很好大小设置为(1920,1080),但是当我将大小更改为其他任何值时,它就会失败,例如光标坐标和绘制的正方形坐标不兼容。有人对此有解释吗?

python pyautogui
1个回答
0
投票

发生这种情况是因为您在 pygame 窗口中绘制了一个坐标为 (0,0) 的正方形,但光标的坐标为整个屏幕的 (0,0)。我解决了这个问题,我用 pygame 窗口坐标绘制第一个正方形,然后计算移位。

这是我的代码示例:

while True:
    time.sleep(0.4)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        elif event.type == KEYDOWN:
            if event.key == K_BACKSPACE:
                pygame.quit()
                exit()

    square1.rect.x = random.randint(0, width - square1.rect.w)
    square1.rect.y = random.randint(0, height - square1.rect.h)

    pyautogui.click((1920/2 - width/2) + square1.rect.centerx,
                (1080/2-height/2) + square1.rect.centery)

    screen.blit(square1.surf, square1.rect)
    pygame.display.flip()

如果您的 pygame 窗口大小与整个大小相同,则它可以工作,因为坐标 (0,0) 位于同一位置。

我希望它能帮助你,亚当

PS:如果你移动 pygame 窗口,它不起作用,因为在计算中,我假设 pygame 屏幕位于整个屏幕的中心。

© www.soinside.com 2019 - 2024. All rights reserved.