Home > front end >  How can I clean this code ? (rock paper scissors)
How can I clean this code ? (rock paper scissors)

Time:11-06

I made rock paper scissors game with score counter. Although it works well, I realized that the code is too heavy.

import random

game = 3
userScore = 0
computerScore = 0

while game != 0:
    print(f"game left : {game}")
    user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
    computer = random.choice(['r', 'p', 's'])
    if user != computer:
        if user == 'p' and computer == 'r' or user == 's' and computer == 'p' or user == 'r' and computer == 's':
            userScore  = 1
        else:
            computerScore  = 1
    else:
        userScore  = 0
        computerScore  = 0
    print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")
    game -= 1
if userScore > computerScore:
    print("You Won")
elif computerScore > userScore: 
    print("You Lost")
else:
    print("Drawn")

I am trying to clean up this code so that it is more readable and soft.

CodePudding user response:

A few changes you can make to the main loop that make it a little simpler:

# use 'for' and 'range' to iterate over a sequence of numbers
for game in range(3, 0, -1):

    print(f"game left : {game}")
    user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
    # an iterable of single-character strings can be swapped for a single string
    computer = random.choice('rps')

    if user != computer:
        #  use 'in' to concisely test a bunch of different possibilities
        if user   computer in ('pr', 'sp', 'rs'):
            userScore  = 1
        else:
            computerScore  = 1
    # eliminate 'else' that doesn't do anything

    print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")

CodePudding user response:

import random

game = 3
userScore = 0
computerScore = 0

while game > 0:
    print(f"game left : {game}")
    user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
    computer = random.choice('rps')
    if user in 'rps':   
        if user != computer:
            if user   computer in ('pr', 'sp', 'rs'):  
                userScore  = 1
            else:
                computerScore  = 1
        print(f"you({userScore}): {user}  |  computer({computerScore}): {computer}\n")
        game -= 1
    else:
        print(f"'{user}' is not valid, try again")

if userScore > computerScore:
    print("You Won")
elif computerScore > userScore: 
    print("You Lost")
else:
    print("Drawn")
  • Related