Rock ^ Paper ^ Scissors Total Amounts没有收到更新的值...... Python

时间:2015-04-01 19:47:19

标签: python variables python-3.x

所以这是我的代码:

import os
import random
import time

def main():
    ### Declarations ###
    items = []
    userItems = []
    machineItems = []
    totalTies = 0
    userWins = 0
    cpuWins = 0

    ### Adding elements ###
    items.append("rock")
    items.append("paper")
    items.append("scissors")

    ### Function calls ###
    replay(items, userItems, machineItems, totalTies, userWins, cpuWins)
    os.system('cls')
    printResults(userItems, machineItems, totalTies, userWins, cpuWins)

def replay(items, userItems, machineItems, totalTies, userWins, cpuWins):
    response = 'yes'
    while (response == 'yes'):
        print("*Please enter only lower-cased words*")

        ### It was a tie! ###
        ## This is also Input Validation for the below loop ##
        print("Do you pick: ",
              "\n\t1. Rock?",
              "\n\t2. Paper?",
              "\n\t3. Scissors?")
        userChoice = input("Object: ")
        machineChoice = random.choice(items)

        if (userChoice == machineChoice):
            print("Another game is to be played.")
            time.sleep(.5)
            print("Seting up...")
            time.sleep(1)

            os.system('cls')

            print("Do you pick: ",
                  "\n\t1. Rock?",
                  "\n\t2. Paper?",
                  "\n\t3. Scissors?")
            userChoice = input("Object: ")
            machineChoice = random.choice(items)

            totalTies += 1
            userItems.append(userChoice)
            machineItems.append(machineChoice)

            os.system('cls')

            while (userChoice == machineChoice):
                print("Another game is to be played.")
                time.sleep(.5)
                print("Seting up...")
                time.sleep(1)

                print("Do you pick: ",
                      "\n\t1. Rock?",
                      "\n\t2. Paper?",
                      "\n\t3. Scissors?")
                userChoice = input("Object: ")
                machineChoice = random.choice(items)

                totalTies += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)

                os.system('cls')

        ### User picked "rock" ###
        elif(userChoice == "rock"):
            if(machineChoice == "paper"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Paper covers rock.")
                time.sleep(.5)
                print("You lose.")

                cpuWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

            elif(machineChoice == "scissors"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Rock crushes scissors.")
                time.sleep(.5)
                print("You win!")

                userWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

        ### User picked "paper" ###
        elif(userChoice == "paper"):
            if(machineChoice == "scissors"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Scissors cuts paper.")
                time.sleep(.5)
                print("You lose.")

                cpuWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

            elif(machineChoice == "rock"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Paper covers rock.")
                time.sleep(.5)
                print("You win!")

                userWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

        ### User picked "scissors" ###
        elif(userChoice == "scissors"):
            if(machineChoice == "rock"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Rock smashes scissors.")
                time.sleep(.5)
                print("You lose.")

                cpuWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

            elif(machineChoice == "paper"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Scissors cuts paper.")
                time.sleep(.5)
                print("You win!")

                userWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

        response = input("Replay? ('yes' to continue) ")
        os.system('cls')

def printResults(userItems, machineItems, totalTies, userWins, cpuWins):
    print("You chose: ", "\n")
    for i in userItems:
        print("\t", i)

    print("The computer chose: ", "\n")
    for i in machineItems:
        print("\t", i)

    print("Total ties: ", totalTies)
    print("User wins: ", userWins)
    print("Computer wins: ", cpuWins)

    gamesPlayed = (totalTies + userWins + cpuWins)
    print("Games played: ", gamesPlayed)

    input("Press [Enter] to continue...")

main()

这应该是一个Rock_Paper_Scissors程序,如果存在平局则会重新启动,记录userWinscpuWinstotalTies。当我运行它时,一切正常,除了userWinscpuWinstotalTies没有收到更新的值,所以当我在程序结束时打印出结果时,为了向用户展示他们是如何做的,它会说userWinscpuWinstotalTiesgamesPlayed都是0.我不明白,因为这些列表userItemsmachineItems,用于向用户显示每方选择的内容,但不是先前声明的变量。有人可以告诉我我做错了什么吗?提前谢谢!

4 个答案:

答案 0 :(得分:0)

Python中的列表是可变的。整数不是。因此,您不能通过将其作为函数参数传递来更新整数值。

最小可重现代码:

def f(a_list, an_integer):
     a_list.append(3)
     an_integer += 1
     print a_list, an_integer


l = []
i = 1
f(l, i)  # output: [3] 2
f(l, i)  # [3, 3] 2
f(l, i)  # [3, 3, 3] 2
print l, i  # [3, 3, 3] 1

解决方案是从函数返回这些值并显式更新这些整数。

totalTies, userWins, cpuWins = replay(...)

答案 1 :(得分:0)

在Python中将值传递给函数会创建值的副本,因此无法通过修改函数中的值来更新原始函数参数:

def a(mynumber):
    mynumber = 10

mynumber = 5 
a(mynumber) 
print(mynumber)  # will print 5

即使对于列表和复杂对象,这也是一样的 - 虽然你可以修改调用对象的方法,这可能会修改它的状态,你不能替换调用者代码中的实际引用。

在您的情况下,一种可能的解决方案是使用全局变量并且不将“共享”变量作为参数传递:

userItems = 0
machineItems = 0 
totalTies = 0 
userWins = 0 
cpuWins = 0

def replay(items):
    global userItems, machineItems, totalTies, userWins, cpuWins
    ...

def printResults():
    global userItems, machineItems, totalTies, userWins, cpuWins
    ...

答案 2 :(得分:0)

感谢您的所有帮助,但我已经明白了。

这是main()printResults()应该是这样的:

def main():
    ### Declarations ###
    items = []
    userItems = []
    machineItems = []
    totalTies = []
    userWins = []
    cpuWins = []

    ### Adding elements ###
    items.append("rock")
    items.append("paper")
    items.append("scissors")

    ### Function calls ###
    replay(items, userItems, machineItems, totalTies, userWins, cpuWins)
    os.system('cls')
    printResults(userItems, machineItems, totalTies, userWins, cpuWins)

def printResults(userItems, machineItems, totalTies, userWins, cpuWins):
    print("You chose: ", "\n")
    for i in userItems:
        print("\t", i)

    print("The computer chose: ", "\n")
    for i in machineItems:
        print("\t", i)

    print("Total ties: ", sum(totalTies))
    print("User wins: ", sum(userWins))
    print("Computer wins: ", sum(cpuWins))

    gamesPlayed = (sum(totalTies) + sum(userWins) + sum(cpuWins))
    print("Games played: ", gamesPlayed)

    input("Press [Enter] to continue...")

答案 3 :(得分:0)

这里的问题是整数在python中是不可变的。当您递增变量userWinscpuWinstotalTies的值时,变量的值会在replay函数内更新。另一方面,列表是可变的。因此,如果修改函数内的列表(添加或删除元素),则更改将反映在函数外部。

您可以做两件事:

  1. 将三个整数变量设置为全局变量。此方法有效,但不建议
  2. 使函数返回已更改的整数值。

    replay功能

    的末尾添加以下行
    return (totalTies, userWins, cpuWins)
    

    此外,将您调用replay函数的行修改为以下内容:

    (totalTies, userWins, cpuWins)=replay((items, userItems, machineItems, totalTies, userWins, cpuWins)
    

    此代码现在应该有效。