所以我试着让这个按钮在我悬停在它上面时改变颜色,但是pygame.mouse.get_pos游戏()在我打开程序后没有更新。在
我对python和程序都是新手,所以如果有任何帮助,我将不胜感激。在
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Click to Adventure')
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
gameDisplay.fill(white)
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
ycrd = int((y+(h/2)))
r = int(h/2)
print(mouse)
if x+(w+(h/2)) > mouse[0] > x-(h/2) and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay,ac,(x,y,w,h))
pygame.draw.circle(gameDisplay,ac,(x,ycrd),r,0)
pygame.draw.circle(gameDisplay,ac,(x+w,ycrd),r,0)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay,ic,(x,y,w,h))
pygame.draw.circle(gameDisplay,ic,(x,ycrd),r,0)
pygame.draw.circle(gameDisplay,ic,(x+w,ycrd),r,0)
smallText = pygame.font.SysFont("comicsansms",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(w/2)),(y+(h/2)))
gameDisplay.blit(textSurf, textRect)
button("Hi",300,200,100,50,red,green,None)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#print(event)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
我不知道为什么pygame.mouse.get_pos游戏()没有更新,因为我两者都有游戏时间时钟()和时钟滴答声(60)。在
pygame使用“更新/绘制循环”模式,通常在游戏开发框架中找到。这个模式由一个大部分是非终止的循环组成,在代码中它是
while not gameExit:
。在这个循环中,必须通过使用事件标志来处理所有用户输入。例如,您的代码处理QUIT
事件。在但是,您的按钮代码并不是特别适合这种模式。相反,它希望在屏幕上创建一个“按钮”作为某种静态对象,比如基于事件的gui。在
分开第一步,并更新第一步。更新会改变游戏状态,绘图步骤只需检查状态并在屏幕上绘制内容。在您的例子中,更新步骤应该检查鼠标是否在按钮上方,并定义使用的颜色。在
让我们分开:
既然
^{pr2}$button()
函数分离了更新和绘制步骤,您可以在游戏循环中正确地使用它:现在,这应该行得通。但是如果你知道面向对象编程(OOP),你可以定义一个类按钮来保存它的位置和颜色,一个更新方法来检查鼠标并正确地改变按钮的状态,以及一个绘制按钮的draw方法。如果你不懂OOP,这是一个学习OOP的好机会:)
我自己不是
pygame
专家,但我能看到的是,你只在游戏开始时调用button()
函数一次。你需要做一个函数,在每一帧中都会被调用,在你的例子中,改变按钮的颜色。 在屏幕上制作一个普通按钮。然后,创建一个当鼠标位于按钮顶部时调用的函数并更改颜色。 有点像在
^{pr2}$while not gameExit:
这些是引导您开始的伪代码。在
相关问题 更多 >
编程相关推荐