计数器在子程序 PYTHON 3.0 石头剪刀布中的 while 循环中未更新

Counter not updating in a while loop in the subprogram PYTHON 3.0 Rock Paper Scissors

提问人:MW2306RC 提问时间:11/2/2023 最后编辑:AdaMW2306RC 更新时间:11/4/2023 访问量:49

问:

from random import randint

# -------------------------
# Subprograms
# -------------------------

# Gets user input and directs it to the converter

def get_player_choose():
    global choose
    choose = input("Enter your choice, R,P,S")
    if choose.upper() == "R" or choose.upper() == "S" or choose.upper() == "P":
        choose = choose.lower()
        conver(choose)
    else:
        exit()

# converts the input to lower case and outputs full name 
# (NOTE conver(choose) - i was getting an error and i had to change all my variable names)

def conver(choose):
    if choose == "r":
        print("rock")
    elif choose == "p":
        print("paper")
    else:
        if choose == "s":
            print("scissors")
    cpu_chose()

# cpu's choice (pretty self explanitory)

def cpu_chose():
    num = randint(1, 4)
    if num == 1:
        cpu_choose = "r"
    elif num == 2:
        cpu_choose = "p"
    else:
        cpu_choose = "s"

    print(cpu_choose, "cpu")  # test cases to see where program fails etc
    who_won_round(cpu_choose, choose)


def who_won_round(cpu_choose, choose):
    # FIXED issue with the fact the cpu choice doesnt change so same output everytime maybe use num instead of cpu_choose variable

    counter = 0
    counter1 = 0

    print(counter, choose, cpu_choose)

    counter = 0
    counter1 = 0
    counterlist = []

    while counter != 5 or counter1 != 5:
        # **COUNTER not updating, in the loop it updates once and stays at 1**

        if counter == 5 or counter1 == 5:
            exit()

        elif cpu_choose == "r" and choose == "p":
            print("Human wins!")
            counterlist.append(
                counter + 1
            )  # just tried this as a last ditch effort didnt work :'(
            print("test1", counterlist)

        elif cpu_choose == "s" and choose == "r":
            print("Human wins!")
            counter = (str(counter), "1")
            print("test2", counter)

        elif cpu_choose == "p" and choose == "r":
            print("Human wins!")
            counter = (str(counter), "1")
            print("test3", counter)

        elif cpu_choose == choose:
            print("Its a draw")
            counter = (str(counter), "1")
            counter1 = (str(counter1), "1")
            print("test4", counter1)

        else:
            print("AI wins!")
            counter1 = (str(counter1), "1")
            print("test5", counter1)

        cpu_choose = cpu_chose()
    print("HAHSDAHSDA COUNTER", counter)  # test case which didnt print

    print(counter, "human")
    print(counter1, "ai")

    # This seems to work when the other code works
    if counter1 > counter:
        print("Ai wins, better luck next time!")
    elif counter > counter1:
        print("You win, good job!")
    else:
        print("error")


# IGNORE
"""def count(counter,counter1):
  counter = counter+1
  

def count1(counter,counter1):
  counter1 = counter1+1"""


def play_game():
    get_player_choose()


# -------------------------
# Main program
# ------------------------

play_game()

顺便说一句,对不起代码转储,但我认为您需要所有代码才能使其有意义

我只是一个学生,所以不要把我烤得太糟糕,但我预计每次人类/人工智能获胜时计数器都会增加一个,但事实并非如此。

我的问题是子程序 who_won_round() 的 while 循环中的计数器和 counter1 只更新一次,并且无限循环,就好像计数器每次都是 0 一样。因此,非常感谢任何帮助,我真的不确定问题是什么,我在任何地方都找不到解决方案? 任何帮助将不胜感激。 是的,该任务要求将每个代码位都放在子程序中

python while-loop 子进程 计数器

评论

2赞 Sayse 11/2/2023
在每个 elif 中,您将计数器更改为元组,因此它永远不会等于一个数字
0赞 tripleee 11/4/2023
你肯定不能使用 Python 3.0 吗?任何早于 3.7 的内容都已完全过时。
0赞 MW2306RC 11/6/2023
Python 3.0 中。不幸的是,这是最新的编辑和编码。

答:

1赞 Danyil 11/2/2023 #1

请参阅更正后的代码:

from random import randint

# No need for global variables here. It's better to pass them around functions.

# This function gets the player's choice and validates it
def get_player_choice():
    choice = input("Enter your choice (R, P, S): ").upper()
    if choice in ("R", "S", "P"):
        return choice.lower()  # Returning the value is better than using a global variable
    else:
        print("Invalid choice. Exiting the game.")
        exit()  # If the choice is invalid, exit the program

# This function converts the input to the full name
def convert(choice):
    choices = {"r": "rock", "p": "paper", "s": "scissors"}
    return choices.get(choice, "Invalid choice")

# This function generates the CPU's choice
def cpu_choose():
    num = randint(1, 3)  # The range should be 1, 3 because there are only 3 options
    choices = {1: "r", 2: "p", 3: "s"}
    cpu_choice = choices[num]
    print(f"{convert(cpu_choice)} cpu")  # Convert to full name before printing
    return cpu_choice

# This function determines who won the round
def who_won_round(cpu_choice, player_choice, player_counter, cpu_counter):
    win_conditions = {('p', 'r'): "Human wins!", ('r', 's'): "Human wins!", ('s', 'p'): "Human wins!"}
    lose_conditions = {('r', 'p'): "AI wins!", ('s', 'r'): "AI wins!", ('p', 's'): "AI wins!"}

    print(f"Player chose {convert(player_choice)}, CPU chose {convert(cpu_choice)}.")

    if player_choice == cpu_choice:
        print("It's a draw")
    elif (player_choice, cpu_choice) in win_conditions:
        print(win_conditions[(player_choice, cpu_choice)])
        player_counter += 1
    elif (player_choice, cpu_choice) in lose_conditions:
        print(lose_conditions[(player_choice, cpu_choice)])
        cpu_counter += 1

    return player_counter, cpu_counter

# Main function to play the game
def play_game():
    player_counter = 0
    cpu_counter = 0

    while player_counter < 5 and cpu_counter < 5:
        player_choice = get_player_choice()
        cpu_choice = cpu_choose()
        player_counter, cpu_counter = who_won_round(cpu_choice, player_choice, player_counter, cpu_counter)

        print(f"Current Score - Human: {player_counter} | AI: {cpu_counter}")

    if player_counter > cpu_counter:
        print("You win, good job!")
    elif cpu_counter > player_counter:
        print("AI wins, better luck next time!")
    else:
        print("It's a draw overall.")

play_game()

修正:

  1. 删除全局变量。它们通常会导致更难的代码调试\
  2. 固定范围。在这两个选项中都包括在内,因此如果使用 (1, 4),它将比其他选项给出更多的“s”。randintrandint()
  3. 清理了赢/输逻辑
  4. 乐谱存储。现在有简单的整数
  5. 游戏循环直到 5 场胜利
  6. 更正了函数名称

祝你好运!

评论

0赞 Ada 11/2/2023
漂亮优雅的答案:)
0赞 MW2306RC 11/3/2023
首先,非常感谢您的回复,但我仍然有几个问题。1.) 如何在另一个子程序中使用一个子程序中的变量,而不使其成为全局变量。和 2.)我的主要问题是计数器没有更新,我真的很困惑为什么它没有更新,即使我将计数器 = (str(counter), '1') 更改为计数器 = 计数器 +1?再次感谢您的帮助。