for an exercise we need to recreate the game played by the members of the bigbang theory: Rock, Paper, Scissor, Spock, Lizard. I managed to recreate it almost completely, the only problem is: Player 2 automatically wins. Can someone tell me where I need to change the code and also explain why?
import sys
t = len(sys.argv)
if(t < 2 or t > 3):
print("Usage: rpsls.py symbool1 symbool2")
exit()
i = 1
while (i > 0):
a = sys.argv[1]
b = sys.argv[2]
a = a.lower()
b = b.lower()
if(a != "rock" and a != "paper" and a != "scissor" and a != "lizard" and a != "spock"):
print("What's that? please use a real symbol!")
elif(b != "rock" and b != "paper" and b != "scissor" and b != "lizard" and b != "spock"):
print("What's that? please use a real symbol!")
else:
if (a == "paper" and b == "scissor"):
s = True
i = 0
else:
s = False
i = 0
if(a == "paper" and b == "rock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "rock" and b == "lizard"):
s = True
i = 0
else:
s = False
i = 0
if(a == "lizard" and b == "spock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "spock" and b == "scissors"):
s = True
i = 0
else:
s = False
i = 0
if(a == "scissor" and b == "lizard"):
s = True
i = 0
else:
s = False
i = 0
if(a == "lizard" and b == "paper"):
s = True
i = 0
else:
s = False
i = 0
if(a == "paper" and b == "spock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "spock" and b == "rock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "rock" and b == "scissor"):
s = True
i = 0
else:
s = False
i = 0
if(a == b):
print("It's a tie!")
i = 0
exit()
if(s == True):
print("Player 1 wins!")
if(s == False):
print("Player 2 wins!")
Each of your if statements has an else. Only one of the if statements can be true, so that means that all the other else statements are evaluated. The result of that is that the last else statement - which sets s to False - will "win", so player 2 wins.
You should drop all your else statements, and restructure your code as a series of if...elif... blocks:
if a == "paper" and b == "scissor":
s = True
i = 0
elif a == "paper" and b == "rock":
(Note, if conditions don't need parentheses.)
Related
I wrote a Rock, Paper and Scissor game in Python. And I want to have a function that scores the game. The only way I managed to do that was by using global variables inside the function. I know that's not a good practice and I'd like to know how can I make this function without the need for global variables.
import random
def validate_user_input(input):
"""Verify if user input is a valid."""
try:
usr_input = int(input)
except:
return 0
else:
if (usr_input >= 1) and (usr_input <= 3):
return usr_input
else:
return 0
def compare_results(player_choice):
"""Get computer choice and compare it with user choice"""
computer_option = random.randint(1,3)
result_to_word = {0:'- Draw', 1:'- You loose.', 2:'- You Win'}
if player_choice == computer_option:
result = 0
if (player_choice == 1 and computer_option == 2):
result = 1
if (player_choice == 1 and computer_option == 3):
result = 2
if (player_choice == 2 and computer_option == 1):
result = 2
if (player_choice == 2 and computer_option == 3):
result = 1
if (player_choice == 3 and computer_option == 1):
result = 1
if (player_choice == 3 and computer_option == 2):
result = 2
return (result, result_to_word[result], computer_option)
def codify_result(input):
"Transform number of choice into word"
num_to_word = {1: "Rock", 2: "Paper", 3:"Scissor"}
return num_to_word[input]
def make_score(result):
global computer_score
global player_score
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
player_score = 0
computer_score = 0
intro = "\nHello!\nLet's play 'Rock, Paper and Scissors'.\nChoose an option and wait to see the result (Press 'q' at any time to exit)"
print(intro)
while True:
user_input = input("\n1) Rock, 2) Paper os 3) Scissors?: ")
if (user_input == 'q'):
break
else:
user_choice = validate_user_input(user_input)
if user_choice == 0:
print("You have to choose a number between 1 and 3.")
else:
result = compare_results(user_choice)
print("You chose: " + codify_result(user_choice) + ".")
print("The computer chose: " + codify_result(result[2]) + '.')
print(result[1])
make_score(result[0])
print("You: " + str(player_score) + "\nComputer: " + str(computer_score))
So how could I implement this function in a better way?
A "pure functional" approach could be to change your make_score function to take the old scores as arguments, and then return the updated scores:
def make_score(result, computer_score, player_score):
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
return computer_score, player_score
When you call make_score you pass the old scores and assign the new scores:
computer_score, player_score = make_score(result[0], computer_score, player_score)
Taking a step back, though, I might suggest taking an approach that doesn't require you to have a function that translates an opaque result int value into a modification to one or another variable. Maybe put the scores in a dict:
scores = {
"computer": 0,
"player": 0,
}
and then instead of a magic result int, assign a winner that matches one of the dict keys:
if (player_choice == 1 and computer_option == 2):
winner = "computer"
and then you can get rid of the make_score function completely and just do:
scores[winner] += 1
I would recommend making a dictionary which you can then pass into make_score
score_dict = {'computer_score': 0, 'player_score': 0}
make_score(score_dict, result):
if result == 1:
score_dict['computer_score'] += 1
...
Two people participate in competition . There will be one easy, difficult and medium question
Difficulty Score
E 1
M 3
H 5
User will enter two strings e and b , and function should find out greater scores or tie.
My code is:
def winner(e, b):
sume = 0
sumb =0
highest = 0
x = False
for i in (range(len(erica))):
if (erica[i] =='E'):
sume +=1
x = True
elif (erica[i] =='M'):
sume = sume+3
x = True
elif (erica[i] =='H'):
sume +=5
x = True
return sume
if __name__ == '__main__':
erica = input()
bob = str(input())
print(winner(e,b))
When I enter HEM for e, it should give 9 but it only gives 5.
There is a problem with the return statement indentation. Try Below.
Also, you are not passing the correct variables.
def winner(e, b):
sume = 0
sumb =0
highest = 0
x = False
for i in (range(len(e))):
if (e[i] =='E'):
sume +=1
x = True
elif (e[i] =='M'):
sume = sume+3
x = True
elif (e[i] =='H'):
sume +=5
x = True
return sume
if __name__ == '__main__':
e = input()
b = str(input())
print(winner(e,b))
def winner(e, b):
sume = 0
sumb =0
highest = 0
for i in (range(len(e))):
if (e[i] =='E'):
sume +=1
elif (e[i] =='M'):
sume = sume+3
elif (e[i] =='H'):
sume +=5
for i in (range(len(b))):
if (b[i] =='E'):
sumb +=1
elif (b[i] =='M'):
sumb = sumb+3
elif (b[i] =='H'):
sumb +=5
if(sume>sumb):
return "Erica"
else:
return "Bob"
if __name__ == '__main__':
e = input()
b = str(input())
print(winner(e,b))
I am running a program that plays rock, paper, scissors. I have executed the code multiple times and everytime I do, the input asking the user to pick 0,1,2 repeats more than one time. It is only supposed to be asked one time per game cycle. Can anyone help me figure out why this is happening, and how to fix it?
import random
# Function: Display Menu
# Input: none
# Output: none
# displays the game rules to the user
def displayMenu():
print("Welcome! Let's play rock, paper, scissors.")
print("The rules of the game are:")
print("\tRock smashes scissors")
print("\tScissors cut paper")
print("\tPaper covers rock")
print("\tIf both the choices are the same, it's a tie")
# Function: Get Computer Choice
# Input: none
# Output: integer that is randomly chosen, a number between 0 to 2
def getComputerChoice():
computerChoice = random.randrange(0,3)
return computerChoice
# Function: Get Player Choice
# Input: none
# Output: integer that represents the choice
# Asks the user for their choice: 0 for rock, 1 for paper, or 2 for scissors
def getPlayerChoice():
playerChoice = int(input("Please choose (0) for rock, (1) for paper or (2) for scissors"))
return playerChoice
# Function: Play Round
# Input: two integers--one representing the computer's choice and the other representing the player's choice
# Output: integer (-1 if computer wins, 1 if player wins, 0 if there is a tie)
# This method contains the game logic so it stimulates the game and determines a winner
def playRound(getcomputerChoice, getplayerChoice):
if getplayerChoice == 0 and getcomputerChoice == 2:
return 1
elif getcomputerChoice == 0 and getplayerChoice == 2:
return -1
elif getplayerChoice == 2 and getcomputerChoice == 1:
return 1
elif getcomputerChoice == 2 and getplayerChoice == 1:
return -1
elif getplayerChoice == 1 and getcomputerChoice == 0:
return 1
elif getcomputerChoice == 1 and getplayerChoice == 0:
return 1
else:
return 0
# Function: Continue Game
# Input: none
# Output: boolean
# Ask the user is they want to continue (Y/N), and then return True or False accordingly
def continueGame():
playAgain = input("Do you want to continue playing? Enter (y) for yes or (n) for no.")
if playAgain.lower() == "y":
return True
elif playAgain.lower() == "n":
return False
# Function: main
# Input: none
# Output: none
def main():
displayMenu()
getPlayerChoice()
if getPlayerChoice() == 0:
choicePlayer = "rock"
elif getPlayerChoice() == 1:
choicePlayer = "paper"
elif getPlayerChoice() == 2:
choicePlayer = "scissors"
getComputerChoice()
if getComputerChoice() == 0:
choiceComputer = "rock"
elif getComputerChoice() == 1:
choiceComputer = "paper"
elif getComputerChoice() == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
while continueGame() == True:
displayMenu()
getPlayerChoice()
getComputerChoice()
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
playerCounter = 0
computerCounter = 0
tieCounter = 0
while playRound(getPlayerChoice(), getPlayerChoice()) == -1:
computerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
playerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
tieCounter += 1
print()
print("You won", playerCounter, "game(s).")
print("The computer won", computerCounter, "game(s).")
print("You tied with the computer", tieCounter, "time(s).")
print()
print("Thanks for playing!")
# Call Main
main()
It's because when you do:
if getPlayerChoice() == 0:
choicePlayer = "rock"
You are actually calling the method again.
You should do:
p_choice = getPlayerChoice()
if p_choice == 0:
...
My problem is, my rock, paper, scissors program seems trapped in a loop somewhere. I suspect it's either the inner loop that asks the user for the number of rounds, or the outer loop that asks the user how many players should play; both might even have indentation problems but I am not sure.
import random
from os import system, name
from time import sleep
#variable declarations and initializations
computer,players, rounds, wins, loses, draws, yourPlay, count, rec, playerRange = 0, 0, 0, 0, 0, 0, 0, 0, 0, 3
#function definitions
def RoundsWonResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[yourPlay] + " beats " + playerMoves[computer] +"!")
print ("You win!")
return
def RoundsLostResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[computer] + " beats " + playerMoves[yourPlay] +"!")
print ("You lose!")
return
def DrawMatch():
global draws
while (yourPlay == computer):
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print ("It's a draw!")
draws+=1
return
def WinsMatch():
global wins
while (yourPlay != computer):
if (yourPlay == 0 and computer != 1):
if (computer == 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 1 and computer == 0):
if (computer != 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 2 and computer != 0):
if (computer == 1):
RoundsWonResult()
wins+=1
return
def LosesMatch():
global loses
while (yourPlay != computer):
if (yourPlay == 0 and computer == 1):
if (computer != 2):
RoundsLostResult()
loses+=1
elif (yourPlay == 1 and computer == 2):
if (computer != 0):
RoundsLostResult()
loses+=1
elif (yourPlay == 2 and computer == 0):
if (computer != 1):
RoundsLostResult()
loses+=1
return
try:
players = int(input("Enter number of players[1-3]:"))
while (players < 1 or players > playerRange):
print ("Invalid range selected!")
players = int(input("Enter number of players[1-3]:"))
except ValueError:
print ("Only numeric values are allowed!")
players = int(input("Enter number of players[1-3]:"))
if (players > 0 and players <= 3):
print ("Good luck to all " + str(players) + " of you. May the better player win!")
while (rec < players):
try:
rounds = int (input("Enter number of rounds to play:"))
while (rounds <= 0):
print ("Value must be greater than zero!")
rounds = int (input("Enter number of rounds to play:"))
print(rec)
print(rounds)
except ValueError:
print ("Only numeric values are allowed!")
rounds = int (input("Enter number of rounds to play:"))
if (rounds != "" and rounds > 0):
print ("Let the games begin!")
else:
print ("Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. Good Luck!")
print("You entered " + str(rounds) + " round(s)!")
playerMoves = ["Rock","Paper","Scissors"]
while (count < rounds):
try:
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
while (yourPlay < 0 or yourPlay > 2):
print ("Invalid selection!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
except ValueError:
print ("Only numeric values are allowed!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
else:
computer = random.randint(0,2) #randomizes the numbers 0 - 2
if (yourPlay == computer):
DrawMatch()
elif (yourPlay != computer):
WinsMatch()
LosesMatch()
count+=1
print ("End of Round ", count)
if (count == rounds):
print ("Wins:",wins)
print ("Loses:",loses)
print ("Draws:",draws)
#resultLog = {"Wins":wins,"Loses":loses,"Draws":draws}
fileName = input("Enter Your name: ")
#print (resultLog)
with open (fileName,"w") as plyrRec:
print ("Your file has been created!")
plyrRec.close()
with open (fileName, "a") as plyrRec:
plyrRec.write ("{}{}\n{}{}\n{}{}\n".format("Wins:",wins,"Loses:",loses,"Draws:",draws))
plyrRec.close()
rec+=1
print ("End of Record ", rec)
So the code works fairly well except that at the end of the first round it repeatedly asks the user to enter number of rounds to play. I hope someone can advise me please.
#Date first created: September 6, 2018 v.0
#Version: v.1, modified 2021/08/31
#This is a Rock, Paper, Scissors game.
#Rock beats scissors, scissors beats paper, and paper beats rock.
import random
#variable declaration and initialization
game_moves = ["Rock","Paper","Scissors"]
def is_input_numeric(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY numeric values greater than zero
>>> is_input_numeric('4')
True
>>> is_input_numeric("like 7")
False
'''
return str_val.isnumeric() and int(str_val) > 0 and int(str_val) <= 20
def is_input_numeric_range(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY a numeric value greater than zero but less than
or equal to two
>>> is_input_numeric_range('y')
False
>>> is_input_numeric_range('3')
False
>>> is_input_numeric_range('2')
True
'''
return str_val.isnumeric() and int(str_val) >= 0 and int(str_val) <= 2
def validate_rounds():
'''(string) -> string
checks str_val and passes control to is_input_numeric function, then returns a string value
>>> validate_rounds() -> is_input_numeric("time")
False
>>> validate_rounds() -> is_input_numeric('0')
False
>>> validate_rounds()-> is_input_numeric('10')
True
'''
valid_rounds = False
while not valid_rounds:
rounds = input("Enter number of rounds to play[min = 1, max = 20]: ")
valid_rounds = is_input_numeric(rounds)
return rounds
def validate_player_input():
'''(string) -> string
checks string and passes control to is_input_numeric_range function, then returns the string value
>>> validate_player_input() -> is_input_numeric_range('-1')
False
>>> validate_player_input() -> is_input_numeric_range('i')
False
>>> validate_player_input() -> is_input_numeric_range('3')
False
>>> validate_player_input() -> is_input_numeric_range('0')
True
'''
valid_player_control = False
while not valid_player_control:
player_move = input("ONLY (0)Rock,(1)Paper,(2)Scissors, allowed: ")
valid_player_control = is_input_numeric_range(player_move)
return player_move
def get_computer_play():
'''Returns a whole number in the range 0:2
'''
computer_move = random.randint(0,2)
return computer_move
def human_player_wins(plyr, comp):
wins = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 2:
rock_beats_scissors = True
elif human_hand == 1 and computer_hand == 0:
paper_beats_rock = True
elif human_hand == 2 and computer_hand == 1:
scissors_beats_paper = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[human_hand] + " beats " + game_moves[computer_hand] + "!")
print("You Win!")
wins += 1
return wins
def human_player_lose(plyr, comp):
lose = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 1:
paper_beats_rock = True
elif human_hand == 1 and computer_hand == 2:
scissors_beats_paper = True
elif human_hand == 2 and computer_hand == 0:
rock_beats_scissors = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[computer_hand] + " beats " + game_moves[human_hand] + "!")
print("You Lose!")
lose += 1
return lose
def players_draw():
draws = 0
print("It's a draw!")
draws += 1
return draws
def start_game():
rounds_played = 0
total_wins = 0
total_losses = 0
total_draws = 0
highest_score = 0
game_rounds = input("Enter number of rounds to play[Max = 20]: ")
rounds_valid = is_input_numeric(game_rounds)
if not rounds_valid:
game_rounds = validate_rounds()
while rounds_played < int(game_rounds):
player_hand = input("(0)Rock,(1)Paper,(2)Scissors: ")
valid_control = is_input_numeric_range(player_hand)
print('plyr:', player_hand)
if not valid_control:
player_hand = validate_player_input()
computer_hand = get_computer_play()
print('comp:', computer_hand)
if int(player_hand) == computer_hand:
total_draws += players_draw()
if int(player_hand) != computer_hand:
total_wins += human_player_wins(int(player_hand),computer_hand)
total_losses += human_player_lose(int(player_hand),computer_hand)
rounds_played += 1
if total_wins > highest_score:
highest_score = total_wins * 10
print('\n--------------------------GAME RESULTS--------------------------')
print('\nHigh Score = ', highest_score )
print('\nrounds played = ', rounds_played, '||','wins = ', total_wins,'||', 'losses = ', total_losses, '||','draws = ', total_draws )
print('\n--------------------------END OF RESULTS------------------------')
start_game()
Thanks to those who tried to helped me it was appreciated. This is the new version now after four years. Yikes!
I have a game of Rock Paper Scissors with an AI that learns from you by trying everything until it gets a good algorithm, but my code stops working as soon as the AI gets a point, can someone help?
import random
print "Rock. Paper. Scissors. Awesome, a quick project made by me"
a = ["R", "P", "S"]
Ai = 0
Player = 0
samples = ['R']
l = 't'
c = random.choice(a)
play = 0
rndm = ['r.c', '+', '-']
count = 0
max = len(samples)
it = 0
def learn():
global rndm
global samples
global Ai
global Player
global l
global play
global c
global max
global it
number = random.randint(1,5)
if l == 'p':
#Random Learning
choice = random.choice(rndm)
if choice == "-":
choicetwo = random.randint(0,len(samples))
if choicetwo == len(samples):
choicetwo -= 1
samples.pop(choicetwo)
if len(samples) == 0:
q = random.choice(a)
samples.append(q)
if choice == "+":
q = random.choice(a)
samples.append(q)
if choice == "r.c":
choicetwo = random.randint(0,len(samples))
if choicetwo == len(samples):
choicetwo -= 1
samples.pop(choicetwo)
samples.insert(choicetwo,random.choice(a))
if l == 'a':
if it > max:
it = 0
print "oh"
if it < max:
it += 1
it1 = it - 1
c = samples[it1:it1 + 1]
print "Ok"
loop()
def loop():
global a
global Ai
global Player
global l
global c
global play
b = raw_input("R, P, or S? :")
b = b.upper()
if b != "R" and b != "P" and b != "S":
loop()
elif b == "R" and c == "S":
print "Rock .VS. Scissors"
print "You win!"
Player += 1
l = 'p'
elif b == "R" and c == "P":
print "Rock .VS. Paper"
print "You lose!"
Ai += 1
l = 'a'
elif b == c:
print "Tie!"
l = 'p'
elif b == "R" and c == "R":
# Just for errors
print "Tie!"
l = 'p'
elif b == "P" and c == "R":
print "Paper .VS. Rock"
print "You win!"
Player += 1
l = 'p'
elif b == "P" and c == "S":
print "Paper .VS. Scissors"
print "You lose!"
Ai += 1
l = 'a'
elif b == "S" and c == "R":
print "Scissors .VS. Rock"
print "You lose!"
Ai += 1
l = 'a'
elif b == "S" and c == "P":
print "Scissors .VS. Paper"
print "You win!"
Player +=1
l = 'p'
print ""
print "Ai: " + str(Ai) + ", Player: " + str(Player)
print ""
play += 1
learn()
loop()