I am looking for ways to shorten and simplify my python code. Here is one example of one small rock/paper/scissors game I wrote earlier. The code kinda looks too long to me and I want to try to learn how to shorten my code.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
if game_limit == 5 and comp_wins > user_wins:
print("The game is over, YOU LOST!")
elif game_limit == 5 and comp_wins < user_wins:
print("The game is over, YOU WON!")
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "rock":
print("its a draw")
elif user_input == "rock" and comp_input == "paper":
print("You lose!")
comp_wins += 1
if user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "scissors" and comp_input == "scissors":
print("its a draw")
elif user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
if user_input == "paper" and comp_input == "rock":
print("You win")
user_wins += 1
elif user_input == "paper" and comp_input == "paper":
print("its a draw")
elif user_input == "paper" and comp_input == "scissors":
print("You lose!")
comp_wins += 1
Yes. You could simplify your logic by having compound and/or tests for the player and user. Following is a revised version of your code with some simplified logic.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
if game_limit >= 5: # Tweak
if comp_wins > user_wins:
print("The game is over, YOU LOST!")
break
if comp_wins < user_wins:
print("The game is over, YOU WON!")
break
else:
print("We go to sudden death!")
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors" or user_input == "paper" and comp_input == "rock" or user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "paper" or user_input == "paper" and comp_input == "scissors" or user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
else:
print("It's a draw")
This way all of the scenarios where the user can win are in one logical test and all of the scenarios where the computer can win are in another logical test. If neither test is true, then the default would have to be a draw.
Also, I tweaked game limit test because if the computer and user have the same score when the game limit is reached, the test result would be false and the game would then continue on and not stop. So there is a bit of additional code to handle a tie after five rounds.
Give that a try.
Related
WHile I was attempting a simple rock, paper scissors, I ran into this proble. When I execute the file and input the user_input, it says to me that the variable computer_choice doesn’t exist, even though it does exist. I would appreciate if someone could help me, thank you.
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint (0, 2)
computer_choice = options[random_number]
print ("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors" :
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper" :
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_pick == "rock" :
print("You Won!")
user_wins += 1
continue
else:
print("You Lost!")
computer_wins += 1
continue
print("You won", user_wins,"times and the computer won", computer_wins, "times.")
print("Goodbye")
You have to be careful with indentation when using python:
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
# not at this level
# at this level
random_number = random.randint(0, 2)
computer_choice = options[random_number]
print("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors":
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper":
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_choice == "rock": #not computer_pick
print("You Won!")
user_wins += 1
continue
Also you wrote computer_pick in line 31, probably you mean computer_choice
could you tell me why my program doesnt increment "bot_points = 0"
"your_points = 0" to stop the while loop when some of these values reach 3
import random
rock_paper_scissors = ["ROCK", "PAPER", "SCISSORS"]
bot_points = 0
your_points = 0
while bot_points <= 3 or your_points <= 3:
user_choice = input('type "rock", "paper" or "scissors": ').upper()
bot_choice = random.choice(rock_paper_scissors)
if bot_choice == "ROCK" and user_choice == "ROCK":
print("Draw")
elif bot_choice == "ROCK" and user_choice == "PAPER":
print("You win")
your_points = your_points+1
elif bot_choice == "PAPER" and user_choice == "PAPER":
print("Draw")
elif bot_choice == "PAPER" and user_choice == "SCISSORS":
print("You win")
your_points= your_points+1
elif bot_choice == "PAPER" and user_choice == "ROCK":
print("You lose")
bot_points = bot_points+1
elif bot_choice == "SCISSORS" and user_choice == "PAPER":
print("You lose")
bot_points = bot_points+1
elif bot_choice == "SCISSORS" and user_choice == "ROCK":
print("You win")
your_points = your_points+1
elif bot_choice == "SCISSORS" and user_choice == "SCISSORS":
print("Draw")
elif bot_choice == "ROCK" and user_choice == "SCISSORS":
print("You lose")
bot_points = bot_points+1
Two issues:
You test for <= 3, so it won't end until someone wins four times
You test bot_points <= 3 or your_points <= 3, so it won't end until both players win at least four times; and would end when either reaches the threshold
If you want to end when either player wins three times, change the test to:
while bot_points < 3 and your_points < 3:
Alice and Bob are playing rock-paper-scissors game.
Input Specification
The first line contains one integer N (1≤N≤100) that represents the number of games.
The second line is Alice's shape sequence and third line is Bob's shape sequence.
Output Specification
Two integers separated by a space, representing the number of games won by Alice and the number of games won by Bob.
I first made Alice and Bob's shapes in a list using .split() and then I set up a bunch of elif and if statements for each possible scenario. But the problem I'm having is that it is not iterating correctly for example if I input
3
rock rock rock
rock rock paper
instead of output being 0, 1 I get 0,0 and I can't seem to figure out why. Here's my code below.
games = input()
alice = input()
bob = input()
alice = alice.split()
bob = bob.split()
awin = []
bwin = []
a = 0
while a < len(alice):
for i in range(len(alice)):
if alice[i] == "rock" and bob[i] == "rock":
break
elif alice[i] == "scissors" and bob[i] == "scissors":
break
elif alice[i] == "paper" and bob[i] == "paper":
break
elif alice[i] == "rock" and bob[i] == "scissors":
awin.append('rock beat scissors')
break
elif alice[i] == "rock" and bob[i] == "paper":
bwin.append('paper beat rock')
break
elif alice[i] == "paper" and bob[i] == "rock":
awin.append('paper beat rock')
break
elif alice[i] == "paper" and bob[i] == "scissors":
bwin.append('scissors beat paper')
break
elif alice[i] == "scissors" and bob[i] == "paper":
awin.append('scissors beat paper')
break
elif alice[i] == "scissors" and bob[i] == "rock":
bwin.append('rock beat scissors')
break
i += 1
a+=1
print('output:')
print(awin)
print(bwin)
print(str(len(awin)) + " " + str(len(bwin)))
Here's a more simplified version of your code:
games = input()
alice = input()
bob = input()
alice = alice.split()
bob = bob.split()
awin = []
bwin = []
for i in range(len(alice)):
# If both players play the same move
if alice[i] == bob[i]:
continue
elif alice[i] == "rock" and bob[i] == "scissors":
awin.append('rock beat scissors')
elif alice[i] == "rock" and bob[i] == "paper":
bwin.append('paper beat rock')
elif alice[i] == "paper" and bob[i] == "rock":
awin.append('paper beat rock')
elif alice[i] == "paper" and bob[i] == "scissors":
bwin.append('scissors beat paper')
elif alice[i] == "scissors" and bob[i] == "paper":
awin.append('scissors beat paper')
elif alice[i] == "scissors" and bob[i] == "rock":
bwin.append('rock beat scissors')
print('output:')
print(awin)
print(bwin)
print(str(len(awin)) + " " + str(len(bwin)))
Others have given some direction on the original code. I'm just stopping by to offer an alternative approach that is a little more 'pythonic'...and because coding games like this can be a bit of fun!
This implementation doesn't play the same as code in the original question, but has the advantage of following how the game flows in real life.
from collections import defaultdict
# defaultdict returns 0 (int() initial value) if the key does
# not exist. So, encode contests in format AB where 1 means
# A beats B. All other scenarios default to 0 i.e. B wins.
game = defaultdict(int)
game['RS'] = 1
game['SP'] = 1
game['PR'] = 1
num_games = input()
aw,bw = 0,0
while num_games:
alice = raw_input('Shape for Alice:')
bob = raw_input('Shape for Bob:')
aw += game[alice + bob]
bw += game[bob + alice]
num_games -= 1
print(aw,bw)
import random
def rpc():
a = ["rock", "paper", "scissor"]
b = random.choice(a)
print(b)
userinput = input('please type rock, paper or scissor:')
if userinput == "":
print("please print the right thing")
rpc()
if userinput != "rock":
print("type the right thing!")
rpc()
if userinput != "paper":
print("type the right thing!")
rpc()
if userinput != "scissor":
print("type the right thing!")
rpc()
while b == userinput:
print("it is a draw, do you want to play another one?")
c = input("type 'y' if you want to play one more time or press 'n': ")
if c == 'y':
rpc()
elif c =='n':
break
else:
print("print the right words please")
if b == 'rock' and userinput == 'paper':
print("you win!")
rpc()
elif b == 'rock' and userinput == 'scissor':
print("you lost")
rpc()
elif b == 'paper' and userinput == 'scissor':
print("you win!")
rpc()
elif b == 'paper' and userinput == 'rock':
print("you lost!")
rpc()
elif b == 'scissor' and userinput == 'rock':
print("you win!")
rpc()
elif b == 'scissor' and userinput == 'paper':
print("you lost!")
rpc()
rpc()
This is my code for rock paper and scissor, it's pretty simple but when I run my code and input my rock, paper and scissor, I get my please print the right thing statement, O have no idea why it's happening, any help would be wonderful, thank you!
Lets clean this up....
userinput = input('please type rock, paper or scissor:')
while userinput not in acceptable_inputs:
userinput = input('please type rock, paper or scissor:')
opponents_choice = random.choice(objects)
# Check and print. Loop to keep playing - 2 out of 3 wins....
import random
def winner(riya,siya):
if (riya==siya):
return None
elif (riya=="s"):
if (siya=="p"):
return False
elif(siya=="k"):
return True
elif (riya=="p"):
if (siya=="s"):
return False
elif (siya=="k"):
return True
elif (riya=="k"):
if (siya=="s"):
return True
elif (siya=="p"):
return False
print("riya pick: stone(s) paper(p) sessior(k)")
a= random.randint(1,3)
if a==1:
riya="s"
elif a==2:
riya="p"
elif a==3:
riya="k"
siya=input(" siya pick: stone(s) paper(p) sessior(k)")
b=winner(riya,siya)
print(f"riya pick{riya}")
print(f"siya pick {siya}")
if b==None:
print("tie")
elif b:
print("winner")`enter code here`
else:enter code here
print("loose")
I'm trying to write a rock-paper-scissors game in python.this is the code:
D_0 = {1: "rock", 2: "scissors", 3: "paper"}
from random import randint
play = False
name = input("What is your name?: ")
print("%s you have to pick among rock,paper and scissors." % name)
while play == False:
p_1 = input("which one?")
computer = D_0[randint(1, 3)]
print("my choice is: ",computer)
if p_1 == computer:
print("it's a draw")
elif p_1 == "scissors" and computer == "paper":
print("you won!")
elif p_1 == "paper" and computer == "scissors":
print("you lost!")
elif p_1 == "scissors" and computer == "rock":
print("you lost!")
elif p_1 == "rock" and computer == "paper":
print("you lost!")
elif p_1 == "rock" and computer == "scissors":
print("you won!")
elif p_1 == "paper" and computer == "rock":
print("you won!")
else:
print("Invalid input")
break
again = input("do you want another round?:")
if again == "yes":
play = False
else:
play = True
the program works well but I want it to ask the player whether or not he/she wants to do another round.If the answer is yes the program must restart the loop.
The problem is I don't know how to do that.I know it's probably related to True and False and I attempted to do something as you can see in the code but it didn't work.
please Help me.
A simple fix might be just putting your while loop as True and continuing to loop until you break the execution:
D_0 = {1: "rock", 2: "scissors", 3: "paper"}
from random import randint
name = input("What is your name?: ")
print("%s you have to pick among rock,paper and scissors." % name)
while True:
p_1 = input("which one?")
computer = D_0[randint(1, 3)]
print("my choice is: ", computer)
if p_1 == computer:
print("it's a draw")
elif p_1 == "scissors" and computer == "paper":
print("you won!")
elif p_1 == "paper" and computer == "scissors":
print("you lost!")
elif p_1 == "scissors" and computer == "rock":
print("you lost!")
elif p_1 == "rock" and computer == "paper":
print("you lost!")
elif p_1 == "rock" and computer == "scissors":
print("you won!")
elif p_1 == "paper" and computer == "rock":
print("you won!")
else:
print("Invalid input")
again = input("do you want another round?:")
if again != "yes":
break