Home > Software design >  Python - Rock, Paper, Scissors. Function and win counter
Python - Rock, Paper, Scissors. Function and win counter

Time:10-23

I want to try and make it so that the player plays the game 3 times. For each round of the game, it prints whether the player wins, loses, or draws. The function seems to be working, however, the if and elif statements do not. For some reason only the else statement works. I also don't know how to implement the return statement so that the player wins can be counted.

import random

def main():
    gameInput = ['1', '2', '3']
    win=0
    for attempt in range(1,4):
        pc = int(input('Enter 1(rock), 2(paper), or 3(scissor): '))
        npc = random.choice(gameInput)
        win = play_game(pc,npc) win
        #end of loop body
    print(f'You played three times, you won {win} times!')

def play_game(pc, npc):
    result = 0
    if pc == npc:
        print(f"You both chose {npc},it's a tie!")
    elif pc == 1 and npc == 3:
        print(f'You chose {pc}, you win!')
    elif pc == 2 and npc == 1:
        print(f'You chose {pc}, you win!')
    elif pc == 3 and npc == 2:
        print(f'You chose {pc}, you win!')
    else:
        print(f'npc chose {npc},you lost!') 
    return result

main()

CodePudding user response:

import random

def main():
    gameInput = ['1', '2', '3']
    win=0
    for attempt in range(1,4):
        pc = int(input('Enter 1(rock), 2(paper), or 3(scissor): '))
        npc = int(random.choice(gameInput))
        win = play_game(pc,npc) win
        #end of loop body
    print(f'You played three times, you won {win} times!')

def play_game(pc, npc):
    result = 0
    if pc == npc:
        print(f"You both chose {npc},it's a tie!")
    elif pc == 1 and npc == 3:
        result =1
        print(f'You chose {pc}, you win!')
    elif pc == 2 and npc == 1:
        result  = 1
        print(f'You chose {pc}, you win!')
    elif pc == 3 and npc == 2:
        result  = 1
        print(f'You chose {pc}, you win!')
    else:
        print(f'npc chose {npc},you lost!')
    return result

main()

There are two changes i have made which are:

  1. int(random.choice(gameInput)) : convert to int or gameInput=[1,2,3] because as your code compares int to strings so that condition always false that's why every time it's goes in else condition.
  2. I have increment result value in play_game()

I hope this will help you !!

Output :

Enter 1(rock), 2(paper), or 3(scissor): 2
npc chose 3,you lost!
Enter 1(rock), 2(paper), or 3(scissor): 3
You chose 3, you win!
Enter 1(rock), 2(paper), or 3(scissor): 1
You chose 1, you win!
You played three times, you won 2 times!
  • Related