如何插入重启游戏选项? [英] How do I insert a restart game option?

查看:94
本文介绍了如何插入重启游戏选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在骰子游戏结束时有一个选项,说:

I would like to have an option at the end of my dice game which says:

您要重新启动吗?是或否

Do you want to restart? Yes or No

如果用户键入是,则游戏将重新启动,并进行无数次,直到用户玩够了游戏并退出.

If the user types yes, the game restarts and this an infinite number of times, until the user has had enough of the game and quits.

我知道您可以循环执行此操作,但是如何执行呢?

I know you can do this with a loop, but how?

import random

print("Dice Game: try to roll a bigger number than the computer! Good luck!")

print("Type 'go' to roll")
dieroll = input()
if dieroll == 'go':
    myNumber = random.randint(1,6)
    pcNumber = random.randint(1,6)
    print("You rolled " + str(myNumber))
    print("He rolled " + str(pcNumber))
    if myNumber < pcNumber:
        print("You lose!")
    if pcNumber < myNumber:
        print("You win!")

推荐答案

最好将您的程序划分为每个任务的单独函数.它将易于阅读和修改,因此可以轻松创建和实现重启功能.

It's a good idea to divide your program up into separate functions for each task. It will become easy to read and modify, so a restart function can easily be created and implemented.

函数restart()根据用户输入返回布尔值.主startGame循环在while循环的每次迭代中都检查此值.

The function restart() returns a bool depending on the users input. The main startGame loop checks for this value each iteration of the while loop.

当用户想要停止播放(False)时,该函数返回并且程序停止.

When the user wants to stop playing (False) the function returns and the program stops.

import random

def rollDie():
    myNumber = random.randint(1, 6)
    pcNumber = random.randint(1, 6)

    print("You rolled %d" % myNumber)
    print("The PC rolled %d" % pcNumber)

    if myNumber > pcNumber:
        return "--- You win! ---"
    else:
        return "--- You lose! ---"

def restart():
    user_input = input("Would you like to play again? Type 'Yes' or 'No'\n\n")

    if user_input.lower() == "no": # Converts input to lowercase for comparison
        return False
    elif user_input.lower() == "yes":
        return True

def startGame():
    while True:
        user_input = input("Dice Game: Try to roll a bigger number than the computer! Good Luck \n" +
                          "Type 'go' to roll the die... \n\n")

        if user_input == "go":
             print(rollDie())
            if not restart():
                return

startGame()

这篇关于如何插入重启游戏选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆