Python:我的代码应该在完成之后重复

时间:2016-03-18 10:44:00

标签: python

我正在用Python编写摇滚,纸张,剪刀游戏,但我的代码不能正常工作。我是Python的新手,所以如果我的代码没有按照格式进行格式化,请告诉我。假设你输入一个已经存在的答案,游戏运行正常。但是,如果输入一个不同的代码,代码似乎在执行'end()'函数后随机循环。

这是我的代码:

# imports needed files
from random import randint
import time
# creates a function that ends the game
def end(cpuScore,playerScore):
    time.sleep(1)
    cont = input("Would you like to play again? (y or n)\n")
    if cont=="y":
        time.sleep(1)
        start()
    else:
        print("Well... That's a bit rude.")
# creates a function to play the game
def rps(cpuScore,playerScore,num):
    # loops code 3 times (unless 'num' is different)
    for x in range(num):
        num-=1
        # creates options
        options = ["rock","paper","scissors"]
        # picks a random choice for cpu
        cpu = options[randint(0,2)]
        # asks the player to choose
        player = input("rock, paper or scissors?\n")
        # why not gun?
        if player=="gun":
            result = "w"
        elif player==cpu:
            result = "d"
        elif player=="rock":
            if cpu=="paper":
                result = "l"
            if cpu=="scissors":
                result = "w"
        elif player=="paper":
            if cpu=="scissors":
                result = "l"
            if cpu=="rock":
                result = "w"
        elif player=="scissors":
            if cpu=="rock":
                result = "l"
            if cpu=="paper":
                result = "w"
        # if they choose something other than rock, paper, scissors or gun
        else:
            print("That's an invalid input!")
            # adds one to num so that this round is not counted as one of the 3
            num+=1
            # plays the game again with the amount of rounds remaining
            rps(cpuScore,playerScore,num)

        # tells the player how they did
        if result=="w":
            playerScore+=1
            time.sleep(1)
            print("Fine! You win! Your silly " + player + " beat my " + cpu + "!!!")
        if result=="l":
            cpuScore+=1
            time.sleep(1)
            print("Ha! Sucker!! My epic " + cpu + " smashed your measly " + player + "!!!")
        if result=="d":
            time.sleep(1)
            print("Ah! We drew by both choosing %s! Like they say, great minds think alike!" % cpu)
        # announces the scores
        print("You are on %s and the computer is on %s!" % (playerScore,cpuScore))
    # ends the game after 3 rounds
    end(cpuScore,playerScore)
# creates the funtion that sets the variables and starts the game
def start():
    result=""
    cont=""
    cpuScore=0
    playerScore=0
    rps(cpuScore,playerScore,3)
# begins the game
start()

谢谢, Reece Coombes

1 个答案:

答案 0 :(得分:2)

基本上,您的rps函数循环num次,最初为num = 3。如果用户输入了错误的输入,您将在新的上下文中回调函数,它将再次启动整个过程 num+1次。

因此,如果你第一次玩至少六场比赛时回答错误:四个新增加了,两个初始你没有尝试过。

我的建议首先尝试做一个只进行一次摇滚纸剪刀游戏迭代的程序。添加更多迭代是添加全局循环的一个简单事实。