我写了一个小pygame程序,通过点击和移动鼠标来移动图像。
我努力使移动函数movableImg
与我自己的x, y
参数一起工作,而不是像现在这样与预定义的x, y
参数一起工作。
这是我的代码:
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
white = (255, 255, 255)
gameDisplay = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()
drag = 0 #switch with which I am seting if I can move the image
x = 100 #x, y coordinates of the image
y = 100
img = pygame.image.load('button.png') #my image and then his width and height
imgWidth = 100
imgHeight = 100
def image(imgX,imgY): #function to blit image easier
gameDisplay.blit(img, (imgX, imgY))
def movableImg(): #function in which i am moving image
global drag, x, y
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
image(x, y)
if click[0] == 1 and x + imgWidth > mouse[0] > x and y + imgHeight > mouse[1] > y: #asking if i am within the boundaries of the image
drag = 1 #and if the left button is pressed
if click[0] == 0: #asking if the left button is pressed
drag = 0
if drag == 1: #moving the image
x = mouse[0] - (imgWidth / 2) #imgWidth / 2 because i want my mouse centered on the image
y = mouse[1] - (imgHeight / 2)
def main_loop():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
movableImg()
pygame.display.update()
clock.tick(60)
main_loop()
pygame.quit()
quit()
你不需要这个功能。你所需要的只是在你的
for
循环中的一些事件。您可以简单地找出鼠标单击的时间,而不是一个凌乱、复杂的函数:现在
coordinates
是我在这里创建的一个预定义变量,在本例中,它用于存储鼠标的坐标。当event.type
是MOUSEBUTTONDOWN
时,这意味着鼠标已被单击,程序应开始在该if
语句下执行代码。事件只激活一次,这意味着你不能拖动。我建议您创建一个函数,当用户按下鼠标时,该函数允许事件继续,如下所示:held
将是一个布尔变量:如果单击鼠标,则等于True
;否则等于False
。在这种情况下,为了防止程序认为您正在无限地单击鼠标,请添加另一个if
语句来检查鼠标是否已释放,如果已释放,请将held
更改为False
:另外,要确保函数将实际注册鼠标仍被按住的事实,请将这一行放在
if
语句中的MOUSEBUTTONDOWN
事件:最后,要运行该函数,请在循环前面添加一个
if
语句,以便在需要时运行该函数:要移动多个图像,请将它们的位置更改为等于
coordinates
或与coordinates
相关。if
语句不必一次只移动一个图像。这是我在网上找到的代码,我想怎么用就怎么用。SOURCE
相关问题 更多 >
编程相关推荐