so i am trying to make this rock paper scissors game, i want to make a while loop that terminates when user input is "quit" but it doesnt seem to work, it either fails to repeat or continues indefinitly, any idea why?
import random #this module is used to select randomly one of the three values, rock paper or scissors
words = ["rock", "paper", "scissors"]
badwords = ["fuck","shit","bitch", "cunt", "fuck off", "piss off", "nigger","motherfucker"]
def check_word_input(word, word_list, bad_word_list=None):
"""
this function compares the word, in this case user input against a wordlist to see if input is correct, by checking if
words is present in a wordlist. if not, user is notified that his input is not valid.
optionally checks the word against a list of bad words and gives feedback
arguments:
word -- word you want to check
word_list -- list of words you want your word to compare against
keyword arguments:
bad_word_list -- list of words that give custom feedback to the user. (default None)
"""
if word in word_list:
return word
elif bad_word_list and word in bad_word_list:
print("How dare you?!")
else:
print("invalid input, (check for typos)")
def game():
computer_wins = 0
player_wins = 0
feedback = input("Welcome to my rock, paper scissors game, type 'rock', 'paper' or 'scissors': ")
checked_feedback = " "
while checked_feedback != "quit":
checked_feedback = check_word_input(feedback, words, badwords)
computer = random.choice(["rock","paper","scissors"])
if checked_feedback == computer:
print("its a tie!")
if (checked_feedback == 'rock' and computer == 'scissors') or (checked_feedback == 'paper' and computer == 'rock') or (checked_feedback == 'scissors' and computer == 'paper'):
player_wins += 1
print("you won!, your current score is now %d" %player_wins)
else:
computer_wins += 1
print("you lost!, opponents current score is now %d" %computer_wins)
print("type 'quit' to quit")
checked_feedback = check_word_input(feedback, words, badwords)
break
print("computer score: ", computer_wins)
print("player score: ", player_wins)
you need to change
print("type 'quit' to quit")
to
feedback = input("type 'quit' to quit")
Also I would change
feedback = input("Welcome to my rock, paper scissors game, type 'rock', 'paper' or 'scissors': ")
to
print("Welcome to my rock, paper scissors game")
then at the first line of the loop should have
feedback = input("Rock, paper or scissors")
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 trying to create a Rock Paper Scissors program against a computer but running into some issues.
I have made two methods, one for the computer's choice and the user's choice. For the computer, it randomly generates 0,1,2 and selects rock, paper or scissors from an array which I declared as a local variable, rps. When I try to run the game with the game_play() method, I am able to enter in input but don't get an output of the result between the player and the computer.
class RockPaperScissors():
global rps
rps = ['rock', 'paper','scissors']
def computer_choice(self): #computer randomly picks rock paper or scissors
x = random.randint(0,2)
w = rps[x]
return w
#print(rps[x])
def player_choice(self): #does the player choose rock paper or scissors
x = True
while x:
choice = (input("Player- would you like rock, paper, or scissors? enter rock,paper, or scissors?: "))
if choice.lower() == 'rock':
return 'rock'
elif choice.lower() == 'paper':
return 'paper'
elif choice.lower() == 'scissors':
return 'scissors'
else:
("please enter in rock, paper or scissors")
def game_play(self):
rock = RockPaperScissors()
user = rock.player_choice()
comp= rock.computer_choice()
if comp == 'rock' and user == 'paper':
return "the player wins!"
elif comp == 'rock' and user == 'scissors':
return "the computer wins!"
elif comp == 'paper' and user == 'rock':
return "the computer wins!"
elif comp == 'paper' and user == 'scissors':
return "the player wins!"
elif comp == 'scissors' and user == 'paper':
return"the computer wins!"
elif comp == 'scissors' and user == 'rock':
return "the player wins"
I am trying to test it this way:
rock = RockPaperScissors()
rock.game_play()
If you are running it as a script instead of everything in the Python interpreter. You must explicitly print the value.
One possible solution is:
rock = RockPaperScissors()
print(rock.game_play())
Directly answering your question: you are not "printing" the game, which would be...
print(rock.game_play())
However, there's some other improvements I would do.
Avoid global variables so that you can provide greater clarity to
the code. Maybe it's a better idea to define rps inside the function
computer_choice() instead of having it as a global variable.
You can simplify player_choice() as:
x = input("Player- would you like rock, paper, or scissors? enter rock,paper, or scissors?: ").lower()
while x != 'rock' and x != 'paper' and x != 'scissors':
choice = (input("Player- would you like rock, paper, or scissors? enter rock, paper, or scissors?: "))
x = input("please enter in rock, paper or scissors").lower()
return x
Possibly, your code wasn't copied correctly, but everything below the first line (class RockPaperScissors:) is missing one indent.
Finally, another possible solution is to print the game's result inside function game_play() instead of returning a string.
Good luck and keep learning.
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
I am working on Rock, Paper, Scissors in Python 3. I need help trying to implement where the computer keeps track of the users choices so it can tell what the player favors and have an advantage over the player. I also have the computer choosing random using an integer but I need to make the players choice a lowercase 'r' 'p' 's' and a 'q' to quit so it can check for invalid entry and display message and ask again. I don't want to use integers for the player.
Here is what I have:
import os
import random
import time
#global variable
#0 is a placeholder and will not be used
choices = [0, 'rock', 'paper', 'scissors']
player_wins = 0
computer_wins = 0
tie_count = 0
round_number = 1
keep_playing = True
# sets cls() to clear screen
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# function to display stats
def stats():
print("Current Statistics:")
print("Player Wins: {}".format(player_wins))
print("Computer Wins: {}".format(computer_wins))
print("Tied Games: {}\n".format(tie_count))
# function to check outcome
def game_outcome(player, computer):
#this makes the variables global, else you'll get error
global player_wins, tie_count, computer_wins
if computer == player:
print("It's a tie!\n\n")
tie_count += 1 # incraments tie
# checks all possible win conditions for player. and if met, declares player a winner. If not, declares compute the winner.
elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
print("Player wins\n\n")
player_wins += 1 # incraments player's wins
else:
print("Computer wins!\n\n")
computer_wins += 1 # incraments computer's wins
# clears screen
cls()
print("Let's play Rock Paper Scissors!")
# 3-second time out before clearing and asking for input
time.sleep(3)
while keep_playing == True:
# make computer choice random from defined list. Only selects a range of 1-3 ignoring the "0" placeholder
# this is because the user selects a number, instead of typing the weapon, and that number pulls the weapon from the list
computer = random.choice(choices[1:4])
cls()
# prints starting of round and shows stats
print("+++++++++++++[Starting Round {}]+++++++++++++\n".format(round_number))
stats()
# ask for player input
player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
player = choices[int(player)]
cls()
print("\n\nThe player's choice: [{}]\n".format(player))
print("The computer's choice: [{}]\n\n".format(computer))
game_outcome(player, computer)
round_number += 1
# ask if player wants to play again. If not, stop
play_again = input('Would you like to play again [y/n]? ')
if play_again.lower() == 'n':
break
print("Thanks for playing!")
Try using a dictionary:
# put this with the imports at the top
import sys
# replace `choices` at the top
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
# get computer choice
# replaces `computer = random.choice(choices[1:4])`
computer = random.choice(['rock', 'paper', 'scissors'])
# ask for player input
# replace these two lines of code:
# player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
# player = choices[int(player)]
while True:
try:
player = choices[input("What is your choice?\n(r) Rock\n(p) Paper\n(s) Scissors?\n(q) to quit.\n\nEnter the letter before the weapon of choice: ")]
if player == 'quit':
sys.exit(0)
break
except KeyError:
print('Please try again.')
I'm not sure how to go about putting these two lots of code together with a menu to be able to select either one to run, like something similar to this:
Welcome to (etc etc)
What would you like to play?
All computer generated OR You vs computer?
Selection 1 or 2? Please enter your selection:
Or something along those lines.
I'm very new to coding so I have no idea as to how I should approach this. All help would be greatly appreciated :)
Here are the two codes if that helps at all:
Code 1 (Computer Generated);
import sys
import time
import random
#Build a list to convert move numbers to names
move_names = "rock Spock paper lizard scissors".split()
#Build a dict to convert move names to numbers
move_numbers = dict((name, num) for num, name in enumerate(move_names))
win_messages = [
"Computer 2 and Computer 1 tie!",
"Computer 1 wins!",
"Computer 2 wins!",
]
def rpsls(name):
# convert Computer 1 name to player_number
player_number = move_numbers[name]
# generate random guess Computer 2
comp_number = random.randrange(0, 5)
# compute difference modulo five to determine winner
difference = (player_number - comp_number) % 5
print "\nComputer 2 chooses", name
print "Computer 1 chooses", move_names[comp_number]
#print "Score was:", difference # XXX
#Convert difference to result number.
#0: tie. 1: Computer 1 wins. 2:Computer 2 wins
if difference == 0:
result = 0
elif difference <= 2:
result = 2
else:
result = 1
return result
def main():
banner = "! ".join([word.capitalize() for word in move_names]) + "!.\n"
print "Welcome to..."
for char in banner:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.02)
print "Rules!:"
print """\nScissors cuts Paper
Paper covers Rock
Rock crushes Lizard
Lizard poisons Spock
Spock smashes Scissors
Scissors decapitates Lizard
Lizard eats Paper
Paper disproves Spock
Spock vaporizes Rock
(and as it always has) Rock crushes scissors"""
print "\n<Follow the enter key prompts!>"
raw_input("\n\nPress the enter key to continue.")
#A list of moves for Computer 1
computer1_moves = [
"rock",
"Spock",
"paper",
"lizard",
"scissors",
"rock",
"Spock",
"paper",
"lizard",
"scissors",
]
#Create a list to hold the scores
scores = [0, 0, 0]
for name in computer1_moves:
result = rpsls(name)
scores[result] += 1
print result, win_messages[result], scores
raw_input("\n\nPress the enter key to continue.")
print "\nFinal scores"
print "Computer 1 wins:", scores[1]
print "Computer 2 wins:", scores[2]
print "Ties:", scores[0]
raw_input("\n\nPress the enter key to exit")
if __name__ == "__main__":
main()
Code 2 (You vs Computer);
import random
data = "rock", "spock", "paper", "lizard", "scissors"
print "Rules!:"
print """Scissors cuts Paper
Paper covers Rock
Rock crushes Lizard
Lizard poisons Spock
Spock smashes Scissors
Scissors decapitates Lizard
Lizard eats Paper
Paper disproves Spock
Spock vaporizes Rock
(and as it always has) Rock crushes scissors"""
def playgames():
tally = dict(win=0, draw=0, loss=0)
numberofgames = raw_input("How many games do you want to play? ")
numberofgames = int(numberofgames)
for _ in range(numberofgames):
outcome = playgame()
tally[outcome] += 1
print """
Wins: {win}
Draws: {draw}
Losses: {loss}
""".format(**tally)
def playgame():
choice = ""
while (choice not in data):
choice = raw_input("Enter choice (choose rock , paper , scissors , lizard, or spock):")
choice = choice.lower()
print "Player choice is:{}".format(choice)
player_number = data.index(choice)
computer_number = random.randrange(5)
print "Computer choice is: {}".format(data[computer_number])
difference = (player_number - computer_number) % 5
if difference in [1, 2]:
print "Player wins!"
outcome = "win"
elif difference == 0:
print "Player and computer tie!"
outcome = "draw"
else:
print "Computer wins!"
outcome = "loss"
return outcome
playgames()
raw_input("\n\nPress the enter key to exit.")
A quick and easy hack is to just create a menu.py that runs code1.py or code2.py depending on the user input.
#menu.py
import os
print """
Welcome to (etc etc)
What would you like to play?
All computer generated OR You vs computer?
Selection 1 or 2? Please enter your selection:
"""
choice = raw_input()
if choice == '1':
os.system('code1.py')
elif choice == '2':
os.system('code2.py')
else:
print 'invalid choice'
Put menu.py, code1.py and code2.py all in the same directory and then run menu.py.
Name your first script as script1.py. Now add this at the top of your second script
import script1
And the following code snippet at the end of your second script:
print("Welcome! What would you like to play?")
print("All computer generated OR You vs computer?")
print("Selection 1 or 2? Please enter your selection:")
while True:
choice = int(input())
if choice == 1:
script1.main()
elif choice == 2:
playgames()
else:
print("Enter either 1 or 2!\n")
( I have used python 3 syntax but it should be no problem to convert them to python 2).