I am a complete python newbie and this is my first question on stackoverflow, so please be patient with me :)
So to get some excersise, I tried programming my own rock, paper, scissors game in Python. However, my code is relatively long compared to other rock, paper, scissor programs. This is because I programmed every single possible option in the game. Is there a possibility to simplify this code? As in not having to programm every single possibiliy in the game? Because doing so might be possible in Rock, Paper, Scissors, but probably not in more advanced problems.
Let me know what you think, thank you!!!
All the best,
Luca Weissbeck
The code:
#Rock, Paper, Scissors
while True:
Game_list = ["Rock", "Paper", "Scissors"]
User_1 = str(input("Rock, Paper, Scissors?"))
#Let the computer make its choice
import random
Computer_1 = random.choice(Game_list)
#Possibility of a draw
if str(Computer_1) == User_1:
Draw_choice = str(input("It's a draw. Do you want to replay?(Y/N)"))
if Draw_choice == "Y":
continue
else:
break
#Possibility of player winning
if str(Computer_1) == "Rock" and User_1 == "Paper" or str(Computer_1) ==
"Paper" and User_1 == "Scissors" or str(Computer_1) == "Scissors" and User_1
== "Rock":
UW1 = str(input("You won. The computer chose:" + Computer_1 + " Do
you want to play again? (Y/N)"))
if UW1 == "Y":
continue
else:
break
#Possibility of computer winning
if str(Computer_1) == "Rock" and User_1 == "Scissors" or str(Computer_1)
== "Paper" and User_1 == "Rock" or str(Computer_1) == "Scissors" and User_1
== "Paper":
UL1 = str(input("You lost. The Compuer chose:" + Computer_1 + " Do
you want to play again? (Y/N)"))
if UL1 == "Y":
continue
else:
break
#End sentence
print("Bye, thank you for playing!")
There are a lot of repeated strings in this program. They can be collapsed.
import random
States = ['Rock','Paper','Scissors']
playAgain = True
while playAgain:
User = str(input("Choose your play: "))
try:
User = States.index(User)
except:
print('Your choice is not one of the choices in Rock, Paper, Scissors')
break
Comp = random.randint(0,2)
winner = (Comp-User)%3
if winner==0:
print("There is a tie. Both User and Computer chose " + States[User])
elif winner==1:
print("Computer wins. Computer chose "+States[Comp]+" and User chose "+States[User])
else:
print("User wins. Computer chose "+States[Comp]+" and User chose "+States[User])
if str(input("Do you want to play again? (Y/N)")) == "N":
playAgain = False
print("Thanks for playing!")
You can try to store the win possibilities.
win_case = [['rock','scissor'], ['scissor','paper'], ['paper','rock']]
Then the main program will be like
if (user == comp):
// draw
elif ([user,comp] in win_case):
// user win
else:
// comp win
Length of code is one thing. Organization and readability is another (more important) one. What often helps is a separation of code and config. Set constants, settings, messages first, then use them in the code:
import random
# game config
R, P, S = "Rock", "Paper", "Scissors"
BEATS = {R: S, P: R, S: P}
MESSAGES = {
"draw": "It's a draw. Play again? (Y/N)\n",
"win": "You won. Comp chose: {}. Play again? (Y/N)\n",
"loss": "You lost. Comp chose: {}. Play again? (Y/N)\n",
"invalid": "Invalid input: {}. Play again? (Y/N)\n",
}
# game code
play = "Y"
while play.upper() == "Y":
u1 = str(input("{}, {}, {}?\n".format(R, P, S)))
c1 = random.choice([R, P, S])
if u1 not in BEATS:
play = input(MESSAGES["invalid"].format(u1))
elif c1 == u1:
play = input(MESSAGES["draw"])
elif BEATS[u1] == c1:
play = input(MESSAGES["win"].format(c1))
else:
play = input(MESSAGES["loss"].format(c1))
Related
I'm a beginner and writing a code for "Rock Paper Scissors" game. I don't want to run this game(code) over and over again, hence, used while loop. Now, at the "else:" step when any invalid choice is typed by the Player, Computer plays it's turn too after which "Invalid choice. Play your turn again!" is displayed.
I want when a Player types any invalid choice, the computer should not play it's turn and we get "Invalid choice. Play your turn again!" displayed, keeping the game running.
Please check my code and point me to the issue. Please explain with the correction. Thanks in advance!
print("Welcome to the famous Rock Paper Scissors Game. \n")
Choices = ["Rock", "Paper", "Scissors"]
while(True):
Player = input("Your turn: ")
Computer = random.choice(Choices)
print(f"Computer's turn: {Computer} \n")
if Player == Computer:
print("That's a tie, try again! \n")
elif Player == "Rock" and Computer == "Scissors":
print("You Won!!! \n")
elif Player == "Rock" and Computer == "Paper":
print("Computer won! \n")
elif Player == "Paper" and Computer == "Scissors":
print("Computer won! \n")
elif Player == "Paper" and Computer == "Rock":
print("You Won!!! \n")
elif Player == "Scissors" and Computer == "Paper":
print("You Won!!! \n")
elif Player == "Scissors" and Computer == "Rock":
print("Computer won! \n")
else:
print("Invalid choice. Play your turn again! \n")
You can check if the input is valid before the computer plays, and ask again if it is invalid using continue -
Choices = ["Rock", "Paper", "Scissors"]
while(True):
Player = input("Your turn: ")
if Player not in Choices: # If it is not in Choices list above
print("Invalid choice. Play your turn again! \n")
continue # This will re run the while loop again.
# If Player gives valid input, then continues this
Computer = random.choice(Choices)
print(f"Computer's turn: {Computer} \n")
# The next lines ....
Also check out - Break, Continue and Pass
I am fairly new in python coding. I made a simple rock, paper, scissor game using random module. I wrote it in three functions. when I am executing it, I get no error but it is not executing the functions.
what I wrote:
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == y:
main()
elif play == n:
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
it is not executing play_game() and user_choice().
It only ask for the input.
The first thing which is wrong is that y and n are not under "" thus python is treating them as a variable. the second thing which was wrong is the position of the play game which should come below the main() to get executed. All user_choice() was not indented properly
Try this code
import random
def main():
global comp
global user
global play
play = ''
# preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
# computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
# user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input(
"Do you want to continue? press y or n for yes and no respectively. ")
if play == "y":
main()
elif play == "n":
print("Thank you for playing!")
exit()
# conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
Create another function main() and call play_game() and user_choice() within main.
The code calls the main() function and this takes an input, but it does not call any of the other functions.
This is why.
Expect that you mean to call play_game() and user_choice() from within main().
Working code.
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
user_choice()
play_game()
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == 'y':
main()
elif play == 'n':
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
if __name__ == '__main__':
main()
So, I just recently started coding and decided to make a rock paper scissors game; However, my program has a bug where if the user enters "rock" the correct code block doesn't run. Instead it runs an else statement that's only meant to run when the user enters, "no". I tried using a while loop instead of just if else statements but it didn't make a difference.
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
user = str(input("Great, select Rock Paper or Scissors:"))
if q_1 != "yes":
if q_1 == comp:
print("Oh No, a Tie!")
elif q_1 == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif q_1 == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
else:
print("Ok :(")
There are a few issues with your code.
First of all your code only plays the game if the user doesn't enter "yes". You need to change if q_1 != "yes": to if q_1 == "yes":.
Secondly, your code asks the user to choose rock, paper or scissors regardless of whether they have said they want to play or not. Fix this by moving user = str(input("Great, select Rock Paper or Scissors:")) to under the if q_1 == "yes": if statement.
Thirdly, your code uses q1 instead of user as it should.
Here is how your code should look:
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
if q_1 == "yes":
user = str(input("Great, select Rock Paper or Scissors:"))
if user == comp:
print("Oh No, a Tie!")
elif user == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif user == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
print("I played:",comp)
else:
print("Ok :(")
I Was Practicing Programs Of Python And Then I Made This Rock, Paper, Scissors Program. And The Program Is Running Perfectly But The Problem Is Like This:
I Chose "Rock, Paper, Scissors" Like This Than It Runs.
But If I Enter Rock, Paper, Scissors In Any Other Way It Prints The Else Statment i.e., Invalid Choice.
I Want To Use Upper/Lower Case But How And Where.
import random
user = input("""Tell Me What Do You Choose:
~Rock
~Paper
~Scissors.
-> I Choose : """)
choose = ["Rock", "Paper", "Scissors"]
computer = random.choice(choose)
print(f"Computer Chose {computer}.")
#Function To Compare Choices
def compare(user, computer):
if user == computer:
return("It's A Tie :(....")
elif user == "Rock":
if computer == "Scissors":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Scissors":
if computer == "Paper":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Paper":
if computer == "Rock":
return("User Wins!")
else:
return("Computer Wins!")
else:
return("User Choose Out Of The Options!")
exit()
print(compare(user, computer))
just transform your input into lowercase with the lower() method
user = user.lower()
that makes sCiSsOrS into scissors
you also need to adjust your if statements to be all lowercase
elif user == "Rock": --> elif user == "rock":
I am new to coding. I want to try writing a simple rock paper scissors game. But I can't figure out how to end the game.
In the end of this program if the user input is wrong I want to go to the end variable again. I tried with the commented lines but its not working.
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
while True:
print(player1 + " What do you choose ? rock / paper / scissors : ")
a = input()
print(player2 + " What do you choose ? rock / paper / scissors : ")
b = input()
if a == "rock" and b == "scissors" :
print(player1, "won !!!")
elif a == "scissors" and b == "rock":
print(player2, "won !!!")
elif a == "paper" and b == "rock":
print(player1, "won !!!")
elif a == "rock" and b == "paper":
print(player2, "won !!!")
elif a == "scissors" and b == "paper":
print(player1, "won !!!")
elif a == "paper" and b == "scissors":
print(player2, "won !!!")
elif a == b:
print("Its a tie :-(")
elif a or b != "rock" or "paper" or "scissors":
print("Wrong input, Try again")
end = input("Do you want to play again ? yes/no ") == "yes"
if input == "yes":
continue
else:
print('''
GAME OVER''')
break
# elif input != "yes" or "no":
# print("Wrong input, Try again. yes or no ?")
I expect it to end game if the input is "no" and restart the game if input is "yes" if the input is not correct I want the prompt to appear again.
Your code has a few issues which need some addressing, and a few places where it can be streamlined. I have made a few changes to your program as well as added a few comments explaining the changes.
player1 = input("What is player 1's name ? ").title() #This uses chaining to streamline code
player2 = input("What is player 2's name ? ").title() #Same as above
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ") #no need to use a separate print statement
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
valid_entries = ["rock", "paper", "scissors"] #To check for valid inputs
if (a not in valid_entries) or (b not in valid_entries):
print("Wrong input, try again")
continue
a_number = valid_entries.index(a) #Converting it to numbers for easier comparison
b_number = valid_entries.index(b)
if(a_number == b_number):
print("Its a tie :-(")
else:
a_wins = ((a_number > b_number or (b_number == 2 and a_number == 0)) and not (a_number == 2 and b_number == 0)) #uses some number comparisons to see who wins instead of multiple if/elif checks
if(a_wins):
print(player1, "won !!!")
else:
print(player2, "won !!!")
end = input("Do you want to play again ? yes/no ")
while (end !="yes") and (end != "no"):
print("invalid input, try again")
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print("GAME OVER")
break
These changes also make the check by using another while loop to see if the input to restart the game was valid or not
*Note that I have not tested these changes and some edits may need to be be made
Just check the value of end
if end is True:
continue
else:
break
Since, you have set the value of end as a boolean by comparing the input() to "yes", it will say whether the user wants to end the game?
Also, you are not initializing the input variable, and the last elif condition will always be true as mentioned in the comment.
Well you can simplify your code using a list and then simplify your if tests. You can check the order of the options and based on it make a decision. You can also make the tests standard to minimize the number of if statements. This my suggestion to improve your code. I hope it helps:
# get playe names
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
# init vars
options = ["rock", "paper", "scissors"]
players = [player1, player2]
# start game
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check if inputs are correct
while (a not in options or b not in options):
print("Wrong input, Try again")
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check who won
if abs(options.index(a) - options.index(b)) == 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif abs(options.index(b) - options.index(a)) > 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif a == b:
print("Its a tie :-(")
# continue or drop game
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print('''
GAME OVER''')
break