How can I clean this code ? (rock paper scissors) - python

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.

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")

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

Stuck inside the while loop

I was writing code for Rock Paper Scissors game in Python. This is kinda tournament style (3 rounds)
But it just keeps playing after the 3rd round is over.
def play():
player = input("Please type 'r' for Rock, 'p' for Paper and 's' Scissors: \n").lower()
while (player != 'r') and (player != 'p') and (player != 's'):
player = input("That is not an valid option. Please try again:\n").lower()
computer = random.choice(['r', 'p', 's'])
commands = {
"r" : "Rock",
"p" : "Paper",
"s" : "Scissors"
}
if player == computer:
print("It's a draw! Game Over.")
return("Draw")
elif user_win(player, computer):
print(f"You won! The computer used {commands[computer]} against your {commands[player]} and lost.")
return("Won")
print(f"You lost! The computer used {commands[computer]} against your {commands[player]} and won.")
return("Lost")
def user_win(player, computer):
# r > s, s > p and p > r
if (player == 'r' and computer == 's') or (player == 's' and computer == 'p') or (player == 'p' and computer == 'r'):
return True
print("Hello, Player! Choose your weapon.")
count, user, comp = 0, 0, 0
while count < 3:
count =+ 1
outcome = play()
if outcome == 'Won':
user =+ 1
elif outcome == 'Lost':
comp =+ 1
if user > comp:
print(f"You win. You: {user} Computer: {comp}")
elif comp > user:
print(f"You lost. You: {user} Computer: {comp}")
else:
print(f"Its a draw. You: {user} Computer: {comp}")
This is the full code. Below is the part which have problem (if i understood it right)
while count < 3:
count =+ 1
outcome = play()
if outcome == 'Won':
user =+ 1
elif outcome == 'Lost':
comp =+ 1
Ps: This is my first time posting on stackoverflow so sorry if i posted in wrong way.
The error is count =+ 1. Try count += 1, that should work.
(As a little background: count =+ 1 will simply assign a value of 1 to the variable count. After that, count never chnages, so it can never reach 3, and you're stuck in an infinite loop. The increment you want is count += 1.)
When you do
count =+1, it just assigns the value +1 to variable count, which is less than the required exit value of 3. You can try to log the value of count across iterations for a better understanding.
Fix:
Change the =+ to += for what I suppose is your requirement, ie to increment value by 1 on each iteration. Read through What is the difference between '+=' and '=+'?

*Python Too many if-statements are executing

I'm currently testing my skill by making a "rock paper scissors" game. I ran into a problem.
Some of the code: (I know it's kind of a lot for a problem, but look towards the end where most serval similar statements are and where # Win and # Lose also appear.)
import random
computerScore = 0
Score = 0
print("> Type \"help\" for help. <")
print("---")
print("Loading Rock Paper Scissors...")
while True:
guesses = [
"rock", "paper", "scissors"
]
guessesShortcuts = [
"r", "p", "s"
]
cmd = input("> ")
cmd = cmd.lower()
if cmd == "help":
print("Help - Opens this menu.\nQuit - Quits and stops the game.\nRPS - Starts a classic game of Rock Paper Scissors.")
if cmd == "rps" or cmd == "rock paper scissors":
Guess = str(input(f"Choose your weapon. {guesses[0].capitalize()}, {guesses[1].capitalize()}, or {guesses[2].capitalize()}? "))
Guess = Guess.lower()
computerGuess = random.choice(guesses)
if Guess == guesses[0] or Guess == guesses[1] or Guess == guesses[2]:
if Guess == computerGuess:
print("It's a tie!")
print(f"{Score} / {computerScore}")
# Win
if Guess == guesses[0] or Guess == guessesShortcuts[0] and computerGuess == guesses[2]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[1] or Guess == guessesShortcuts[1] and computerGuess == guesses[0]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[2] or Guess == guessesShortcuts[2] and computerGuess == guesses[1]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
# Lose
if Guess == guesses[2] or Guess == guessesShortcuts[2] and computerGuess == guesses[0]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[0] or Guess == guessesShortcuts[0] and computerGuess == guesses[1]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[1] or Guess == guessesShortcuts[1] and computerGuess == guesses[2]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
else:
print("Invalid response.")
In python, all if statements that are true will execute without regard to the previous if statements. What you want to do is have your first statement as an if statement, then the rest are elif statements.
Example:
if (condition):
(code)
elif (condition):
(code)
elif (condition):
(code)
...
or has a lower precedence than and. When you say condition1 or condition2 and condition3, that's treated as condition1 or (condition2 and condition3), and it's true if condition1 is true, even if the other conditions are false.
When you say
if Guess == guesses[0] or Guess == guessesShortcuts[0] and computerGuess == guesses[2]:
that's true if Guess == guesses[0], regardless of what computerGuess is.
Also, you don't have any handling for ties if the user enters a 1-letter input, and guess is a misleading name for these choices.
Welcome to Python and SO, your problem is already explained by above answers, just use if-elif-else and double-check your condition
I suggest you should merge 2 list into a dict. It will make you see it more clear:
rps = {"rock": ['rock', 'r'],
"paper": ['paper', 'p'],
"scissor": ['scissor', 's']}
About if statements, you should consider splitting condition into some sub if-elif-else statements, it makes your code clearer:
Guess = str(input(f"Choose your weapon: {list(rps.keys())}? "))
Guess = Guess.lower()
computerGuess = random.choice(list(rps.keys()))
# Rock
if Guess in rps['rock']:
print(f"Computer: {computerGuess}")
if computerScore is 'rock':
print("It's a tie!")
elif computerGuess is 'paper':
print("You lose!")
computerScore += 1
else:
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
# Paper
elif Guess in rps['paper']:
print(f"Computer: {computerGuess}")
if computerScore is 'paper':
print("It's a tie!")
elif computerGuess is 'scissor':
print("You lose!")
computerScore += 1
else:
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
# Scissor
elif Guess in rps['scissor']:
print(f"Computer: {computerGuess}")
if computerScore is 'scissor':
print("It's a tie!")
elif computerGuess is 'rock':
print("You lose!")
computerScore += 1
else:
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
else:
print("Invalid response.")
As #panwen suggested, you can reduce the if statement clutter by using a dict as a lookup table. Consider using the following to make it easier to find an outcome.
solutions = {
'rock': {'rock': 'tie', 'paper': 'loss', 'scissors': 'win'},
'paper': {'rock': 'win', 'paper': 'tie', 'scissors': 'loss'},
'scissors': {'rock': 'loss', 'paper': 'win', 'scissors': 'tie'},
}
For example,
guess_player = 'rock'
guess_computer = 'scissors'
result = solutions[guess_player][guess_computer]
print(f"It's a {result}. You picked {guess_player} "
f"and the computer picked {guess_computer}")
The while True need some variable in the form
run = True to make the program know when to end the guessing loop by reassigning it a false value at some point or exit like;
run = Tru
while run:
....
....
run = False

how to loop rock paper scissors

import random
print('Ви граєте у гру \'Камінь, ножниці, папір\' !')
choices = ['Камінь' , 'Папір' , 'Ножниці']
user_choice = input('Виберіть : Камінь, Ножниці або Папір : \nВаш вибір : ')
computer_choice = random.choice(choices)
print('Комп\'ютер вибрав : ' + computer_choice)
computer_score = 0
user_score = 0
game = False
while game == False:
if user_choice == 'Камінь' and computer_choice == 'Папір':
computer_score += 1
print('Ви програли !')
elif user_choice == 'Камінь' and computer_choice == 'Ножниці':
user_score += 1
print('Ви перемогли !')
elif user_choice == 'Папір' and computer_choice == 'Ножниці':
computer_score += 1
print('Ви програли !')
elif user_choice == 'Папір' and computer_choice == 'Камінь':
user_score += 1
print('Ви перемогли !')
elif user_choice == 'Ножниці' and computer_choice == 'Камінь':
computer_score += 1
print('Ви програли !')
elif user_choice == 'Ножниці' and computer_choice == 'Папір':
user_score += 1
print('Ви перемогли !')
elif user_choice == computer_choice:
print('Нічия !')
else:
print('Неправильне введення. Перевірте написання слова.')
break
print('Користувач : ' + str(user_score)+ ' |----| ' + 'Комп\'ютер : ' + str(computer_score))
So I have a problem, I just wrote whis program 'Rock Paper Scissors' (and I know its simple and you might even laugh at me, but Im just starting out) and I don`t know how to make it play few times. I run it choose one of the items and I get a score and program closes. how to loop it maybe ?
You can use the following structure (translated into English for others):
import random
choices = ['Rock' , 'Paper' , 'Scissors']
computer_score = 0
user_score = 0
game = True
while game:
user_choice = input('Choose : Rock, Scissors, or Paper : \nYour choice : ')
computer_choice = random.choice(choices)
print('Computer chose : ' + computer_choice)
if user_choice == 'Rock' and computer_choice == 'Paper':
computer_score += 1
print('You lost !')
elif user_choice == 'Rock' and computer_choice == 'Scissors':
user_score += 1
print('You won !')
# Other choices...
game = (input('Play again? (y/n)\n') == 'y')
print('User : ' + str(user_score)+ ' |----| ' + 'Computer : ' + str(computer_score))
game is now by default True which can change if the user decides they don't want to play and input n after a given game. They keep playing by inputting y instead. The user and computer choices are now moved inside the while loop (to have a set of choices per game). The score is cumulative and displays at the end, once the user decided not to play again (though that's just a matter of how you want your game to work).
Note that you need to remove the break statement from the while loop (assuming the indentation in the OP was wrong and the break was part of the while). The only components of your original code between the first if for choices and the check if user wants to keep on playing should be the other choices (including the else for an unknown choice).
I would probably use recursion, but you need to add a case when the recursion should top, otherwise you will eventually run out of memory.
def start() :
~~~~~~~~~~~ bla bla bla ~~~~~~
start()
start()

while loop argument not take into account

I have just begin to learn to program with Python and I try to make a rock-paper-scissor game to train myself.
I have a problem at the end of the the code with the while loop
It doesn't take account of my computer_score so if I have to create a variable and add an argument to not finish with an infinite loop
user_choice = "Rock"
user_score = 0
computer_score = 0
def fight(user_choice):
if user_choice == "Rock":
scissor = 1
rock = 2
paper = 3
user_choice = rock
computer_choice = randint(1, 3)
print computer_choice
if user_choice == computer_choice:
print 'DRAW!'
elif user_choice > computer_choice:
print 'User win, consciousness can\'t be beaten, you win'
global user_score
user_score += 1
elif user_choice < computer_choice:
print 'Computer win, singularity has been reach'
global computer_score
computer_score += 1
i = 0
while (computer_score < 3 or i < 30):
fight(user_choice)
i = i + 1
There may be the case that randint(1, 3) always returns 1. So computer never wins. This way your while loop continues infinitely.

Python rock paper scissors score counter

I am working on a rock paper scissors game. Everything seems to be working well except the win/loss/tie counter. I have looked at some of the other games people have posted on here and I still cannot get mine to work. I feel like I am soooooo close but I just can't get it! thanks for any help guys. this is my first time posting in here so I am sorry if I messed up the formatting.
I edited the code but still cannot get the program to recognize the counter without using global variables. at one point of my editing I managed to get it to count everything as a tie... i dont know how and I lost it somewhere along my editing. lol. -thanks again everyone!
here is what I get when I run the program:
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 1
Computer chose PAPER .
You chose ROCK .
You lose!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 2
Computer chose PAPER .
You chose PAPER .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 3
Computer chose SCISSORS .
You chose SCISSORS .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. n
Your total wins are 0 .
Your total losses are 0 .
Your total ties are 0 .
#import the library function "random" so that you can use it for computer
#choice
import random
#define main
def main():
#assign win, lose, and tie to zero for tallying
win = 0
lose = 0
tie = 0
#control loop with 'y' variable
play_again = 'y'
#start the game
while play_again == 'y':
#make a welcome message and give directions
print('Prepare to battle in a game of paper, rock, scissors!')
print('Please input the correct number according')
print('to the object you want to choose.')
#Get the player and computers choices and
#assign them to variables
computer_choice = get_computer_choice()
player_choice = get_player_choice()
#print choices
print('Computer chose', computer_choice, '.')
print('You chose', player_choice, '.')
#determine who won
winner_result(computer_choice, player_choice)
#ask the user if they want to play again
play_again = input("Play again? Enter 'y' for yes or 'n' for no. ")
#print results
print('Your total wins are', win, '.')
print('Your total losses are', lose, '.')
print('Your total ties are', tie, '.')
#define computer choice
def get_computer_choice():
#use imported random function from library
choice = random.randint(1,3)
#assign what the computer chose to rock, paper, or scissors
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#define player choice
def get_player_choice():
#assign input to variable by prompting user
choice = int(input("Select rock(1), paper(2), or scissors(3): "))
#Detect invalid entry
while choice != 1 and choice != 2 and choice != 3:
print('The valid numbers are rock(type in 1), paper(type in 2),')
print('or scissors(type in 3).')
choice = int(input('Enter a valid number please: '))
#assign what the player chose based on entry
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#determine the winner from the variables
def winner_result(computer_choice, player_choice):
#if its a tie, add 1 to tie variable and display message
if computer_choice == player_choice:
result = 'tie'
print("It's a tie!")
#if its a win, add to win tally and display message
elif computer_choice == 'SCISSORS' and player_choice == 'ROCK':
result = 'win'
print('ROCK crushes SCISSORS! You win!')
elif computer_choice == 'PAPER' and player_choice == 'SCISSORS':
result = 'win'
print('SCISSORS cut PAPER! You win!')
elif computer_choice == 'ROCK' and player_choice == 'PAPER':
result = 'win'
print('PAPER covers ROCK! You win!')
#if it does not match any of the win criteria then add 1 to lose and
#display lose message
else:
result = 'lose'
print('You lose!')
def result(winner_result,player_choice, computer_choice):
# accumulate the appropriate winner of game total
if result == 'win':
win += 1
elif result == 'lose':
lose += 1
else:
tie += 1
return result
main()
Your winner_result function returns before it increments the win counters. If you remove all the return statements from it, the counters should be updated. The return statements aren't needed anyway because the if/elif/else structure ensures that only one of the possible outcomes will be executed.
As Junuxx says in a comment, you also need to assign values to the winner_result variable properly, i.e. winner_result = 'win' instead of winner_result == 'win'. I'd also rename the winner_result variable or the function, because it's confusing to have both use the same name.
And the win/lose/tie variables are currently local, which means that main and winner_result will have their own copies of these variables, so main's values will always be zero. What you can do is make them global variables: Assign them to zero in the global scope (outside any function), and add the line global win, lose, tie inside the function winner_result.
Obviously been a few years since this question was answered but it came up while I was looking the same info. Here's my code if anyone is interested.
#! usr/bin/python3
import random
def game():
computer_count = 0
user_count = 0
while True:
base_choice = ['scissors', 'paper', 'rock']
computer_choice = random.choice(base_choice)
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock' or \
user_choice == 'paper' and computer_choice == 'scissors' or \
user_choice == 'rock' and computer_choice == 'paper':
print(computer_wins)
computer_count += 1
elif user_choice == 'rock' and computer_choice == 'scissors' or \
user_choice == 'scissors' and computer_choice == 'paper' or \
user_choice == 'paper' and computer_choice == 'rock':
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
computer_count += 1
user_count += 1
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
I was trying to do the same project, and I have found a solution that works well for me.
from random import randint
win_count = 0
lose_count = 0
tie_count = 0
# create a list of play options
t = ["Rock", "Paper", "Scissors"]
# assign a random play to the computer
computer = t[randint(0, 2)]
# set player to false
player = False
print()
print("To stop playing type stop at any time.")
print()
while player == False:
# set player to True
player = input("Rock, Paper or Scissors? ")
if player.lower() == "stop":
print()
print(
f"Thanks for playing! Your final record was {win_count}-{lose_count}-{tie_count}")
print()
break
if player.title() == computer:
print()
print("Tie!")
tie_count += 1
print()
elif player.title() == "Rock":
if computer == "Paper":
print()
print(f"You lose. {computer} covers {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} smashes {computer}.")
win_count += 1
print()
elif player.title() == "Paper":
if computer == "Scissors":
print()
print(f"You lose. {computer} cuts {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win!, {player.title()} covers {computer}.")
win_count += 1
print()
elif player.title() == ("Scissors"):
if computer == "Rock":
print()
print(f"You lose. {computer} smashes {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} cuts {computer}.")
win_count += 1
print()
else:
print()
print("Sorry, we couldn't understand that.")
print()
# player was set to True, but we want it to be false to continue loop
print(f"Your record is {win_count}-{lose_count}-{tie_count}")
print()
player = False
computer = t[randint(0, 2)]
This works (kinda)
there are many issues with the code at the top of the page.
Firstly, Scoring doesn't work.
Secondly, nothing is indented meaning that nothing inside of the other def functions will work.
Thirdly, The other def functions are referred to in the first def main statement which causes Python to show an invalid syntax due to Python not knowing the other functions as they were referred to before they were introduced to python.

Categories

Resources