Python 尝试石头剪刀布中的错误代码 1

Error Code 1 in Python trying a Rock Paper Scissor

我正在通过在线课程学习 Python,我在整个课程中一直在写这个石头剪刀布,但是当我完成 check_for_winning_throw 部分时,出现了四个错误其次是“进程已完成,退出代码为 1”。我试过为每次抛出重写变量,但它们是相同的,检查每一行但我找不到错误。

import random

rolls = {
    'rock': {
        'defeats': ['scissors'],
        'defeated_by': ['paper']
    },
    'paper': {
        'defeats': ['rock'],
        'defeated_by': ['scissors'],
    },
    'scissors': {
        'defeats': ['paper'],
        'defeated_by': ['rock'],
    },
}


def main():
    show_header()
    play_game("You", "Computer")


def show_header():
    print("---------------------------")
    print(" Rock Paper Scissors v2")
    print("  Data Structure Edition ")
    print("---------------------------")


def play_game(player_1, player_2):
    rounds = 3
    wins_p1 = 0
    wins_p2 = 0

    roll_names = list(rolls.keys())

    while wins_p1 < rounds and wins_p2 < rounds:
        roll1 = get_roll(player_1, roll_names)
        roll2 = random.choice(roll_names)

        if not roll1:
            print("Try again!")
            continue

        print(f"{player_1} roll {roll1}")
        print(f"{player_2} rolls {roll2}")

        winner = check_for_winning_throw(player_1, player_2, roll1, roll2)

        if winner is None:
            print("This round was a tie!")
        else:
            print(f'{winner} takes the round!')
            if winner == player_1:
                wins_p1 += 1
            elif winner == player_2:
                wins_p2 += 1

        print(f"Score is {player_1}: {wins_p1} and {player_2}: {wins_p2}.")
        print()

    if wins_p1 >= rounds:
        overall_winner = player_1
    else:
        overall_winner = player_2

    print(f"{overall_winner} wins the game!")


def check_for_winning_throw(player_1, player_2, roll1, roll2):

    winner = None
    if roll1 == roll2:
        print("The play was tied!")

    outcome = rolls.get(roll1, {})
    if roll2 in outcome.get('defeats'):
        return player_1
    elif roll2 in outcome.get('defeated_by'):
        return player_2

    return winner


def get_roll(player_name, roll_names):
    print("Available rolls:")
    for index, r in enumerate(roll_names, start=1):
        print(f"{index}. {r}")

    text = input(f"{player_name}, what is your roll? ")
    selected_index = int(text) - 1

    if selected_index < 0 or selected_index >= len(rolls):
        print(f"Sorry {player_name}, {text} is out of bounds!")
        return None

    return rolls[selected_index]


if __name__ == '__main__':
    main()

这是结果:

---------------------------
 Rock Paper Scissors v2
  Data Structure Edition 
---------------------------
Available rolls:
1. rock
2. paper
3. scissors
You, what is your roll? 

我在这里为 Rock 输入“1”,然后出现:

Traceback (most recent call last):
  File "C:/Users/Bianconiglio/AppData/Local/Programs/Python/esercizi/notepad/rpsgame.py", line 101, in <module>
    main()
  File "C:/Users/Bianconiglio/AppData/Local/Programs/Python/esercizi/notepad/rpsgame.py", line 21, in main
    play_game("You", "Computer")
  File "C:/Users/Bianconiglio/AppData/Local/Programs/Python/esercizi/notepad/rpsgame.py", line 39, in play_game
    roll1 = get_roll(player_1, roll_names)
  File "C:/Users/Bianconiglio/AppData/Local/Programs/Python/esercizi/notepad/rpsgame.py", line 98, in get_roll
    return rolls[selected_index]
KeyError: 0

Process finished with exit code 1

get_roll 函数中,您正在 returning rolls[selected_index]rolls 是一个具有三个键(石头、布、剪刀)的字典,并且 selected_index 是 0、1 或 2。

将 return 值更改为 list(rolls.keys())[selected_index] 就可以了!