石头^布^剪刀未收到更新值的总金额…Python

2024-09-30 01:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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

这应该是一个石头-布-剪刀程序,如果有领带,它会重新启动,记录userWinscpuWinstotalTies。当我运行这个程序时,除了userWinscpuWinstotalTies没有收到更新的值之外,其他的都可以正常工作,所以当我在程序末尾打印结果时,为了向用户展示它们是如何做的,它会说userWinscpuWinstotalTiesgamesPlayed都是0。我不明白,因为列表userItemsmachineItems,用于向用户显示每一方选择了什么,但不适用于前面所述的变量。有人能告诉我我做错了什么吗?提前谢谢!你知道吗


Tags: youtimeossleepsystemprintappenduserchoice
3条回答

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

在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
    ...

谢谢你的帮助,但我已经弄明白了。你知道吗

这就是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...")

相关问题 更多 >

    热门问题