在pygam中用鼠标移动图像

2024-06-09 13:43:45 发布

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

我已经做了一些代码,移动一个图像(使用鼠标)称为灯泡使用pygame,但当我把它移动到屏幕底部的左手边时,它会变得很糟糕,不能再被拾起任何帮助将是惊人的,非常感谢

import pygame
import math

pygame.init()

width = 800
height = 800

black = (0,0,0)
white = (255, 255, 255)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((width, height)) #make the display
pygame.display.set_caption("car game") #title of the window
clock = pygame.time.Clock()  #frames per second defined here

bulb = pygame.image.load("bulb.png")

def bulbfunc(x,y):
    gameDisplay.blit(bulb, (x,y))


def mainloop():
    gameExit = False
    mouseDown = False
    x = width - 170
    y = 20
    while not gameExit:
        for event in pygame.event.get(): #when any action is done by the user
            if event.type == pygame.QUIT:
                quit()
        gameDisplay.fill(white)
        bulbfunc(x,y)
        clock.tick(60)
        pygame.display.update()


        clickstatus = pygame.mouse.get_pressed()
        (xs, ys) = pygame.mouse.get_pos()
        if mouseDown == False:
            if (x - 45) < xs < (x + 45) and (y - 45) < ys < (x + 45):
                print("true")
                print(x)
                if clickstatus[0] == 1:
                    mouseDown = True

        if mouseDown == True:
            if clickstatus[0] == 1:
                (x, y) = (xs, ys)
            else:
                mouseDown = False



mainloop()
pygame.exit()
exit()

Tags: theimporteventfalsegetifdisplaywidth
2条回答

你有一行这样的代码:

if (x - 45) < xs < (x + 45) and (y - 45) < ys < (x + 45):

我假设您的意思是最后一个条件是(y + 45)。这就解释了它在底部的左手边卡住了,ys很大,x很小,所以第二个条件永远不会满足。如果你不小心,复制和粘贴是危险的!在

您在这一行有一个错误:

if (x - 45) < xs < (x + 45) and (y - 45) < ys < (x + 45)

它应该是:

^{pr2}$

注意结尾是(y+45)而不是(x+45)

相关问题 更多 >