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).
Related
This is a rock,paper,scissors game.
import random
options = ("rock", "paper", "scissors") # three options
running = True
score = 0
while running: # continuing the game
player = "" # storing the player's choices
computer = random.choice(options) # computer will choose a random choice from the options
while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
player = input("Enter a choice (rock, paper, scissors): ")
print("Player: " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
score = 0
print("It's a tie!")
elif player == "rock" and computer == "scissors":
score += 1
print("You win!")
elif player == "paper" and computer == "rock":
score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
score += 1
print("You win!")
else:
score += 1
print("You lose!")
print(score, "for computer")
print(score)
play_again = input("Play again? (y/n): ").lower()
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
My goal was trying to keep score for player and computer. If the user wins, they get a point. If the computer wins, they get a point. If its a tie, neither of them gets a point.
The following code shows you three rounds of three games of a simulated user input game with its result. It is your code only slightly changed to count properly the results:
import random
lst_user_input = [
"list faking user input:"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"n"
]
options = ("rock", "paper", "scissors") # three options
running = True
computer_score = 0
player_score = 0
round_no = 0
while running: # continuing the game
#player = "" # storing the player's choices
round_no += 1
computer = random.choice(options) # computer will choose a random choice from the options
#while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
# player = input("Enter a choice (rock, paper, scissors): ")
print(round_no)
player = lst_user_input[round_no]
print("Player : " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
player_score += 1
print("You win!")
elif player == "paper" and computer == "rock":
player_score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
player_score += 1
print("You win!")
else:
computer_score += 1
print("You lose!")
print("Player score:", player_score)
print("Computer score:", computer_score)
if not round_no % 3: # ask only each 3 rounds
#play_again = input("Play next 3-rounds? (y/n): ").lower()
round_no +=1
play_again = lst_user_input[round_no]
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
Here an example of printed output:
1
Player : scissors
Computer: paper
You win!
Player score: 1
Computer score: 0
2
Player : paper
Computer: scissors
You lose!
Player score: 1
Computer score: 1
3
Player : rock
Computer: paper
You lose!
Player score: 1
Computer score: 2
Yes sir!
5
Player : scissors
Computer: paper
You win!
Player score: 2
Computer score: 2
6
Player : paper
Computer: rock
You win!
Player score: 3
Computer score: 2
Thanks for playing!
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")
I created the loss() , win() and draw() function to change the score following the events .The problem is that they are not getting called in the while loop to change the score and set it correctly. I had the score lines under every if and elif statement but decided to use a function to make the code shorter and more efficient.
from random import randint
print("Welcome to this game of rock paper scissors against the computer.")
print("Good luck and have fun! Enjoy this game! ")
print("To stop playing, type quit when the round ends.If you want to continue playing, press any key ")
scoreH=0
scoreAI=0
Round=0
def loss():
scoreH=scoreH+0
scoreAI=scoreAI+1
def win():
scoreH=scoreH+1
scoreAI=scoreAI+0
def draw():
scoreH=scoreH+0
scoreAI=scoreAi+0
x=True
while x == True :
# Choice
Round=Round+1
print("Round",Round,"is going to start. ")
print("1.Rock")
print("2.Paper")
print("3.Scissors")
choice=input("Enter your choice: ").lower()
IntChoice=randint(1,3)
#Transforming AI_choice from an int to a string
if IntChoice == 1:
AI_choice="rock"
elif IntChoice == 2:
AI_choice="paper"
elif IntChoice == 3:
AI_choice="scissors"
print(AI_choice)
# Draw
if choice==AI_choice:
draw()
print("The computer chose",choice,".You draw.")
# PlayerWins
elif choice=="paper" and AI_choice=="rock":
win()
print("The computer chose",choice,".You win.")
elif choice=="scissors" and AI_choice=="paper":
win()
print("The computer chose",AI_choice,".You win.")
elif choice=="rock" and AI_choice=="scissors":
win()
print("The computer chose",AI_choice,".You win.")
# AIwins
elif AI_choice=="paper" and choice=="rock":
loss()
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="scissors" and choice=="paper":
loss()
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="rock" and choice=="scissors":
loss()
print("The computer chose",AI_choice,".You lose.")
else:
print("Invalid input.")
continue
end=input()
# Stop Playing
if end == "stop" or end == "quit":
print("The score is :",scoreH,"-",scoreAI)
if scoreH > scoreAI:
print("You win.")
elif scoreH < scoreAI:
print("You lose.")
else:
print("You draw.")
break
else:
continue
They are indeed being called but they are modifying the local variable inside themselves.
To modify the values do something like this:
def loss(scoreAI):
return scoreAI+1
scoreAI = loss(scoreAI)
Actually, the functions are really simple and in some cases you're adding up 0 which is the same as doing nothing, so I wouldn't make functions for this. This is much simpler:
#Win
scoreH += 1
#Loss
scoreAI += 1
and you need nothing for draw.
I hope it helps!
import random
print("Welcome to this game of rock paper scissors against the computer.")
print("Good luck and have fun! Enjoy this game! ")
print("To stop playing, type quit when the round ends.If you want to continue playing, press any key ")
scoreH=0
scoreAI=0
Round=0
def loss():
global scoreH
global scoreAI
scoreH=scoreH+0
scoreAI=scoreAI+1
def win():
global scoreH
global scoreAI
scoreH=scoreH+1
scoreAI=scoreAI+0
def draw():
global scoreH
global scoreAI
scoreH=scoreH+0
scoreAI=scoreAI+0
x=True
while x == True :
# Choice
Round=Round+1
print("Round",Round,"is going to start. ")
print("1.Rock")
print("2.Paper")
print("3.Scissors")
choice=input("Enter your choice: ").lower()
IntChoice=random.randint(1,3)
#Transforming AI_choice from an int to a string
if IntChoice == 1:
AI_choice="rock"
elif IntChoice == 2:
AI_choice="paper"
elif IntChoice == 3:
AI_choice="scissors"
print(AI_choice)
# Draw
if choice==AI_choice:
draw()
print("The computer chose",choice,".You draw.")
# PlayerWins
elif choice=="paper" and AI_choice=="rock":
win()
print("The computer chose",choice,".You win.")
elif choice=="scissors" and AI_choice=="paper":
win()
print("The computer chose",AI_choice,".You win.")
elif choice=="rock" and AI_choice=="scissors":
win()
print("The computer chose",AI_choice,".You win.")
# AIwins
elif AI_choice=="paper" and choice=="rock":
scoreH,scoreAI=loss(scoreH,scoreAI)
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="scissors" and choice=="paper":
loss()
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="rock" and choice=="scissors":
loss()
print("The computer chose",AI_choice,".You lose.")
else:
print("Invalid input.")
#continue
end=input()
# Stop Playing
if end == "stop" or end == "quit":
x=False
print("The score is :",scoreH,"-",scoreAI)
if scoreH > scoreAI:
print("You win.")
elif scoreH < scoreAI:
print("You lose.")
else:
print("You draw.")
break
else:
continue
Expected Output:
Welcome to this game of rock paper scissors against the computer.
Good luck and have fun! Enjoy this game!
To stop playing, type quit when the round ends.If you want to continue playing, press any key
Round 1 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 2 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
paper
The computer chose paper .You draw.
Round 3 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: scissors
paper
The computer chose paper .You win.
Round 4 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 5 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 6 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
scissors
The computer chose scissors .You lose.
Round 7 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
scissors
The computer chose scissors .You lose.
Round 8 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice:
paper
Invalid input.
stop
The score is : 4 - 2
You win.
def player_choice():
while True:
roundsplayed = int(input("Choose how many rounds you want to play from 1 to 5! "))
if roundsplayed < 1 or roundsplayed > 5:
print ("Please enter a valid number from 1 to 5! ")
continue
return player_choice
else:
print ("Lets play " + roundsplayed + "rounds! ")
roundsplayed = player_choice()
print ("Let's go go go!")
options = ("r", "p", "s", "l", "sp")
from random import randint
computer = options[randint(0,4)]
for i in range(roundsplayed):
wins = 0
loses = 0
draws = 0
player = input("""Choose your hand!
Rock (r)
Paper (p)
Scissor (s)
Lizard (l)
Spock (s)
Your Choice: """)
# if player chooses rock
if player == "r" and computer == "r":
print ("You tied!")
elif player == "r" and computer == "s":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "p":
print ("You got covered! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "l":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "sp":
print ("You got vaporized! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
So I have this line of code
for i in range(roundsplayed):
wins = 0
loses = 0
draws = 0
player = input("""Choose your hand!
Rock (r)
Paper (p)
Scissor (s)
Lizard (l)
Spock (s)
Your Choice: """)
# if player chooses rock
if player == "r" and computer == "r":
print ("You tied!")
elif player == "r" and computer == "s":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "p":
print ("You got covered! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "l":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "sp":
print ("You got vaporized! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
And want to make it repeat the number of times I want it to loop by entering a certain variable or input. I put the 'roundsplayed' variable there in the idea that the code would accept a variable entered by the user.
Obviously this doesn't work because the code doesn't define it as an interger.
Also for:
wins = 0
loses = 0
draws = 0
I want it to tally up when the rounds restart to the start of the loop, but obviously have a problem with that as whenever it chooses to restart the loop, the tally is reset to 0, most likely from by obvious mistake.
I hope somebody can help me out, this is all that needs to be fixed for my coding as a python learner, so that I can move on to my next project.
To convert a string to an integer,
int("stringhere")
If you don't want variables reset every time you loop, take them out of the loop.
In order to use the variables in the loop without reset it them, declare them above of the loop (outside the loop).
wins = 0
loses = 0
draws = 0
for i in range(roundsplayed):
player = input("""Choose your hand!
Rock (r)
Paper (p)
Scissor (s)
Lizard (l)
Spock (s)
Your Choice: """)
If you wanna cast a string you got from the console to an int, you can use the Int() function.
var number = int("1")
https://docs.python.org/2/library/functions.html
I'm building a simple rock paper scissors game. It works fine, except for the fact that the game won't stop when comp_count reaches 3. I can't seem to understand why, since it works fine for player_count. Help me out please!
from random import randint
player_count = 0
comp_count = 0
def game():
player_choice = raw_input('Do you choose rock [r], paper [p], or scissors [s]? ')
computer_choice = randint(0,2)
#Rock = 0 Paper = 1 Scissors = 2
#Player chooses paper, computer chooses rock
if player_choice == "p" and computer_choice == 0:
print 'Computer chose rock'
player_won()
#Player chooses rock, computer chooses scissors
elif player_choice == 'r' and computer_choice == 2:
print 'Computer chose scissors'
player_won()
#Player chooses scissors, computer chooses paper
elif player_choice == 's' and computer_choice == 1:
print 'Computer chose paper'
player_won()
#Computer chooses paper, player chooses rock
elif player_choice == 'r' and computer_choice == 1:
print 'Computer chose paper'
computer_won()
#Computer chooses rock, player chooses scissors
elif player_choice == 's' and computer_choice == 0:
print 'Computer chose rock'
computer_won()
#Computer chooses scissors, player chooses paper
elif player_choice == 'p' and computer_choice == 2:
print 'Computer chose scissors'
computer_won()
#Ties
elif player_choice == 'r' and computer_choice == 0:
print "It's a tie!"
game()
elif player_choice == 's' and computer_choice == 2:
print "It's a tie!"
game()
elif player_choice == 'p' and computer_choice == 1:
print "It's a tie!"
game()
#Wrong input
else:
print 'Please try again.'
game()
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
while player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
while comp_count < 3:
game()
print 'Welcome to Rock, Paper, Scissors! First to 3 points wins it all.'
game()
Your while loops are whats causing your problem. Simply change while to a if in your player_won and computer_won functions and it fixes the issue.
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
if player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
if comp_count < 3:
game()
Now go rock paper scissors your heart out!
I admit this isn't really a direct answer to your question, but I feel it might be useful to have a potentially simpler way to write this brought up.
You could make the user choose from three different numbers in the input instead of letters, or just convert the letters to numbers. One advantage of this is that to test for a tie, you could simply write:
if player_choice == computer_choice:
Even checking for who won in a game if it wasn't a tie wouldn't be very difficult, since if it is all numeric, an option that beats another one will be one away from it in a certain direction. So, for example, you could test if the player won like so:
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
If each number represented a different option (for example if you had a dictionary linking 0 to rock, 1 to scissors, and 2 to paper), then this would check if the user chose the option before the computer's, which would be the winning option.
That would actually let you check for who won and with which options with relatively few if statements. Your check could look something like this:
options = {0: "rock", 1:"scissors", 2:"paper"}
#collect player and computer choice here
print "computer chose "+options[computer_choice] #We will probably tell them what the computer chose no matter what the outcome, so might as well just put it once up here now that a variable can determine what the computer chose.
if player_choice == computer_choice:
print "It's a tie!"
game()
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
This isn't really necessary for making your code work, but I think it will be useful if you are interested.