talkpython / python-for-absolute-beginners-course

Code samples and other handouts for our course.
https://training.talkpython.fm/courses/explore_beginners/python-for-absolute-beginners
MIT License
2.3k stars 1k forks source link

Chapter 7 error after adding outcome.get #9

Closed BatF0x closed 4 years ago

BatF0x commented 4 years ago

Hey, I keep getting this issue when I add outcome.get, It points out to,

main() at the bottom of the script function play_game(player, player2) in main roll1 = get_roll(player_1, roll_names) in play_game return rolls[selected_index]

my version of python is 3.8

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

player = "You"
player2 = "Computer"

play_game(player, player2)

def show_header(): print("------------------------") print(" Rock, Paper, Scissors v2") print(" Data Structures 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} rolls {roll1}")
    print(f"{player_2} rolls {roll2}")

    # test for a winner
    winner = check_for_winner(player_1, player_2, roll1, roll2)

    print("The end of the Round")
    if winner is None:
        print("It was a tie!")
    else:
        print(f"{winner} is the winner of 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}")

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

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

# Rock
#   Rock -> tie
#   Paper -> lose
#   Scissor -> win
# Paper
#   Rock -> win
#   Paper -> tie
#   Scissor -> lose
# Scissor
#   Rock -> lose
#   Paper -> win
#   Scissor -> tie

def check_for_winner(player_1, player_2, roll1, roll2): winner = None if roll1 == roll2: print("It's a tie!")

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 not a vaild play!")
    return None

return rolls[selected_index]

if name == 'main': main() `