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

我用 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 time

import pygame


HEIGHT = 800

WIDTH = 800

score = 0 

time_left = 10


banana = 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 = 740


def 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()


哔哔one
浏览 196回答 1
1回答

守候你守候我

一个肯定会阻止您的代码运行的问题是您建议的 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python