为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Python 进行游戏 - 添加选项“重启游戏”

使用 Python 进行游戏 - 添加选项“重启游戏”

哔哔one 2022-06-14 10:00:43
我用 Pygame Zero 和 MU IDE 创建了一个小游戏。游戏结束后,应询问用户是否想再玩一次。如果他选择是,游戏应该从头开始。我知道我可以用一个 While 循环来做到这一点,但我不知道怎么做。我试图插入一个while循环。在 while 循环中,游戏函数被调用,但它不起作用。我试过这个:play_again = raw_input("If you'd like to play again, please type 'yes'")while playagain == "yes"      draw()      place_banana()      on_mouse_down(pos)      update_time_left()....我知道这是不正确的,但我不知道如何正确地做from random import randint import timeimport pygameHEIGHT = 800WIDTH = 800score = 0 time_left = 10banana = Actor("banana")monkey = Actor("monkey")def draw():    screen.clear()    screen.fill("white")    banana.draw()    monkey.draw()    screen.draw.text("Number of bananas collected: " + str(score),      color = "black", topleft=(10,10))    screen.draw.text("Time: " + str(time_left), color = "black", topleft=(10,50))def place_banana():    banana.x = randint(125, 790)    banana.y = randint(186, 790)    monkey.x = 50    monkey.y = 740def on_mouse_down(pos):    global score    if banana.collidepoint(pos):         score = score + 1         place_banana() def update_time_left():    global time_left    if time_left:           time_left = time_left - 1    else:          screen.fill("pink")  # code is not executed        game_over() place_banana() clock.schedule_interval(update_time_left, 1.0)def game_over():    screen.fill("pink") # code is not executed    global time_left    message = ("Ende. Number of bananas collected")   # code is not   executed    time_left = 0    time.sleep(5.5)    quit()
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

一个肯定会阻止您的代码运行的问题是您建议的 while 循环中所有四个函数末尾的冒号。冒号用于定义函数或 if/else 语句等,而不是用于执行函数。


我不确定是否还有其他问题阻止它运行,因为您没有提供所有源代码,但是您的 while 循环应该如下所示:


play_again = "yes"

while playagain == "yes":

    draw()

    place_banana()

    on_mouse_down(pos)

    update_time_left()

    play_again = raw_input("If you'd like to play again, please type 'yes'")

另一件事是,对 pygame 程序使用 shell 输入并不是最好的,因为通常用户不会知道要查看终端,因此请研究将输入构建到游戏实际 UI 中的选项。


编辑:感谢 chepner 指出缺少的重新分配play_again


查看完整回答
反对 回复 2022-06-14
  • 1 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号