为什么我的标题屏幕播放按钮无法启动我的游戏?



我正试图在游戏中添加一个播放按钮。当我启动游戏时,我点击播放按钮,它会给我一个错误

Traceback (most recent call last):
File "C:UsersZee_SOneDriveDesktoppython projectslil ShooterPlayerLil Shooter.py", line 370, in <module>
game_intro()
File "C:UsersZee_SOneDriveDesktoppython projectslil ShooterPlayerLil Shooter.py", line 336, in game_intro
button("LETS PLAY!", 20, 450, 115, 50, green, bright_green, run)
File "C:UsersZee_SOneDriveDesktoppython projectslil ShooterPlayerLil Shooter.py", line 308, in button
action()
TypeError: 'bool' object is not callable
[Finished in 8.3s]

我已经查看了这个"bool"的代码,但我什么都找不到。这是按钮和标题屏幕的代码

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()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen, ic, (x, y, w, h))
smallText = pygame.font.SysFont("comicsansms", 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
screen.blit(textSurf, textRect)
def quitgame():
pygame.quit()
quit()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(white)
largeText = pygame.font.SysFont("comicsansms", 115)
TextSurf, TextRect = text_objects("Lilshooter", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
screen.blit(TextSurf, TextRect)
button("LETS PLAY!", 20, 450, 115, 50, green, bright_green, run)
button("Quit", 480, 450, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)

这就是我在游戏循环中称之为的地方

run = True
game_intro()
while run:
[...]

能帮我解决这个问题吗

函数button的最后一个参数必须是函数。因此它不能是run,因为run是布尔值。

如果您想在按下按钮时更改intro变量的状态,请编写一个startGame函数:

def startGame():
global intro
intro = False

startGame传递给button,而不是run:

button("LETS PLAY!", 20, 450, 115, 50, green, bright_green, startGame)

请注意,变量intro需要是全局命名空间中的变量:
(请参阅global语句(

intro = True
def game_intro():
global intro
while intro:   
# [...]   

名称action有问题。您的错误是

in按钮操作((TypeError:"bool"对象不可调用

这意味着在代码的某个地方,您使用action作为函数,但它是bool。首先,让我们看看button()函数中的action。我们看到它是一个输入参数,在if检查之后,action有可能被调用为函数:问题的出现是因为你在action上进行的唯一检查是它不是None,所以如果它不是None,但也不是函数,就会引发错误。在代码的某个地方,您调用button()并将True(或等效变量(作为action参数传递给它。

特别是,按钮被game_intro()调用两次:

button("LETS PLAY!", 20, 450, 115, 50, green, bright_green, run)
button("Quit", 480, 450, 100, 50, red, bright_red, quitgame)

由于在game_intro()内部没有run的初始化,我假设变量run与while循环(run = True(外部初始化的变量相同。

最新更新