How can I optimize the loop and condition statements? - python

winner = False
def player():
global winner
while winner==False:
print("player 1: please choose rock/paper/scissor !")
choice1 = input()
print("player 2: please choose rock/paper/scissor !")
choice2 = input()
if choice1!=choice2:
if choice1=="rock" and choice2=="scissor" :
print("player 1 is the winner, Congrats!!")
elif choice1=="rock" and choice2=="paper" :
print("player 2 is the winner, Congrats!!")
elif choice2=="rock" and choice1=="scissor" :
print("player 2 is the winner, Congrats!!")
elif choice2=="rock" and choice1=="paper" :
print("player 1 is the winner, Congrats!!")
elif choice1=="scissor" and choice2=="paper" :
print("player 1 is the winner, Congrats!!")
elif choice1=="paper" and choice2=="scissor" :
print("player 2 is the winner, Congrats!!")
else:
print("its a draw")
print("do you want to start a new game?,yes or no")
answer = input()
if answer=="yes":
print("lets start another game!")
winner = False
elif answer=="no":
print("see you next time!")
winner = True
player()
as you can see there is too much inefficient if statements in my code ,how can i minimize them if possible

def player():
while True:
print("player 1: please choose rock/paper/scissor !")
choice1 = input()
print("player 2: please choose rock/paper/scissor !")
choice2 = input()
beats = dict(
rock='scissor',
scissor='paper',
paper='rock',
)
if choice1 != choice2:
if beats[choice1] == choice2:
winner = 1
else:
winner = 2
print("player %s is the winner, Congrats!!" % winner)
else:
print("its a draw")
print("do you want to start a new game?,yes or no")
answer = input()
if answer == "yes":
print("lets start another game!")
else:
print("see you next time!")
break
player()

You can do something like this:
db = {'rockscissor': 1,
'rockpaper': 2,
'scissorrock': 2,
'scissorpaper': 1,
'paperrock': 1,
'paperscissor': 2}
if choice1!=choice2:
print("player {} is the winner, Congrats!!".format(db[choice1+choice2]
else:
print("its a draw")
and you can even add draws to the db as well:
db = {'rockscissor': 1,
'rockpaper': 2,
'scissorrock': 2,
'scissorpaper': 1,
'paperrock': 1,
'paperscissor': 2,
'paperpaper':0,
'rockrock':0,
'scissorscissor':0
}
then handle the if.

Related

When my code not exiting while loop in python?

It's a black jack game project. When user_score > 21 or 21 , it shold exit the while loop but it is not exiting while loop.I am new in coding. Plese tell me where is the problem.
I don't want to use break command. Because from which tutorial I am learning she has not taught me it yet.
You can get an idea of black jack game here.247blackjack
I tried these lines of code.
import random
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
random_index = random.randint(0,(len(cards)-1))
random_card = cards[random_index]
return random_card
def want_another_card():
want_card = input("Want another card type 'y' for yes and type 'n' for no.")
return want_card
user_card = []
computer_card = []
for x in range(0,2):
user_card.append(deal_card())
computer_card.append(deal_card())
def calculate_score(list):
score = sum(list)
return score
user_score = calculate_score(user_card)
computer_score =calculate_score(computer_card)
#final score function
def final_score_calculation():
while calculate_score(computer_card)< 17:
computer_card.append(deal_card())
line_gap()
print(f"Your final hand: {user_card}, final score: {user_score}")
print(f"Computer's final hand: {computer_card}, final score: {computer_score}")
if user_score > computer_score and user_score < 21:
winner = "User"
print(f"{winner} wins")
elif computer_score > user_score and computer_score < 21:
winner = "computer"
print(f"{winner} wins")
elif computer_score > 21:
print("Computer busted. You win.")
elif user_score > 21:
print("User busted, Computer wins")
elif user_score == 21:
print("user wins")
elif computer_score == 21:
print("computer wins")
elif computer_score == user_score:
print("It's a draw")
should_continue = True
while should_continue == True:
print(f"Your cards: {user_card}, current score {calculate_score(user_card)}")
print(f"computer's first card {computer_card[0]}")
#checking if user or computer has a black jack
if user_score == 21 and len(user_card) == 2:
print("User has the blackJack. You win")
should_continue = False
elif computer_score ==21 and len(computer_card) == 2:
print("Computer has the black jack .You lose")
should_continue = False
#checking if they got busted or got 21
if user_score > 21: #checking user
if 11 in user_card:
usr_indx_pos=user_card.index(11)
user_card[usr_indx_pos] = 1
if user_score > 21:
print("you got busted.You lose.")
should_continue = False
elif user_score ==21:
print("you have 21 . you win")
should_continue = False
else:
print("you got busted.You lose.")
should_continue = False
elif computer_score > 21: #checking computer
if 11 in computer_card:
com_indx_pos = computer_card.index(11)
computer_card[com_indx_pos] = 1
if computer_score > 21:
print("computer busted. you win")
should_continue = False
else:
print("computer got busted. You win")
should_continue = False
elif user_score ==21:
print("you win. you got 21")
should_continue = False
elif computer_score ==21:
print("computer win. computer got 21")
should_continue = False
line_gap()
if want_another_card() == "y":
user_card.append(deal_card())
user_score = calculate_score(user_card)
else:
final_score_calculation()
should_continue = False
Assuming your complaint is that it is prompting you if you want another card even after you bust (or win), the solution is to ensure you don't issue that prompt when the loop is supposed to be done anyway. Just change:
if want_another_card() == "y":
to:
if should_continue and want_another_card() == "y":
This will cause it to do the final_score_calculation() call in the else, which may be redundant; if it shouldn't report the results again when someone has already busted or got exactly 21, wrap the whole of:
if want_another_card() == "y":
user_card.append(deal_card())
user_score = calculate_score(user_card)
else:
final_score_calculation()
should_continue = False
in a check to see if it already knows it's done, making it:
if should_continue:
if want_another_card() == "y":
user_card.append(deal_card())
user_score = calculate_score(user_card)
else:
final_score_calculation()
should_continue = False
so it does no additional work when it already knows the game is over.

My main function is repeating in an infinite loop and I do not know why

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:
...

Variable not registering change in value

I wanted to make a simple Rock, Paper, Scissor game in Python. It goes well with the game, but the final scores are always being showed as a 0.
I wanted to show a smaller section of the code but, I don't know where the problem lies, so I am sorry for the length of the code.
I am still a novice learner, so please pardon me if the question is too silly or the code is not well formatted.
#Rock-Paper-Scissor Game
import random
print("Please enter your name:")
userName = input()
print("Welcome " + userName)
print("The following are the rules of the game:")
print("Press 'R' for Rock")
print("Press 'P' for Paper")
print("Press 'S' for Scissor")
print("This will be a 10 point match")
userTally = 0
compTally = 0
def gameProcess(userTally, compTally): #The process of the game. It increments or decrements the value depending on the result
print("Your turn:")
userInput = input()
computerChoice = random.choice(["R","P","S"])
if userInput == "R": #User Inputs R for Rock
if computerChoice == "R":
print("The computer chose Rock")
print("It's a Tie")
elif computerChoice == "P":
print("The computer chose Paper")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("You Won")
userTally = userTally + 1
elif userInput == "P": #User Inputs P for Paper
if computerChoice == "R":
print("The computer chose Rock")
print("You Won")
userTally = userTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("It's a Tie")
elif computerChoice == "S":
print("The computer chose Scissor")
print("Computer Won")
compTally = compTally + 1
elif userInput == "S": #User Inputs S for Scissor
if computerChoice == "R":
print("The computer chose Rock")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("You Won")
userTally = userTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("It's a Tie")
return(userTally,compTally)
def tryCount(): #The number of tries....
tryNum = 1
while tryNum < 11:
gameProcess(0, 0)
tryNum = tryNum + 1
tryCount()
print("You scored " + str(userTally))
print("The computer scored " + str(compTally))
if userTally > compTally:
print("CONGRATULATIONS, YOU WON.")
elif userTally < compTally:
print("Sorry, better luck next time.")
close = input()
if close == "Random Input.":
exit()
else:
exit()
You pass 0, 0 to gameProcess, which you treat as the scores within the function, and then return them modified, but you do not actually use the return value in the only place you call gameProcess (in tryCount), so the global userTally, compTally variables remain unchanged.
This is how you should change tryCount:
def tryCount(): #The number of tries....
global userTally, compTally
tryNum = 1
while tryNum < 11:
userTally,compTally=gameProcess(userTally,compTally)
tryNum = tryNum + 1

NameError: free variable 'player_one_rps' referenced before assignment in enclosing scope

I'm quite new to coding, and I've been trying to make a text-based game with a menu. The game itself works fine, but once I try to incorporate a menu, i get the error "NameError: free variable 'player_one_rps' referenced before assignment in enclosing scope".
I have been googling it like a mad for some time now, but the few answers I find uses too advanced code for me to understand it yet.
(I tried changing the scopes and indents, I tried calling different functions at different indents, I tried assigning an argument to the functions, also, to have the main menu as the last function in the code – the list goes on..)
Here is the code for the menu and game option 1:
def main():
print("\t\t*** Welcome to this totally adequate game! ***")
def game_menu():
"""Displays game menu and prompts user for input"""
menu_choice = input("""What do you want to do?
1 - One player: rock, paper, scissor, lizard, spock
2 - Two player: rock, paper, scissor, lizard, spock
3 - Surprise! Bonus feature
4 - User guide
5 - Quit
Enter the menu number to access: """)
while True:
if menu_choice == "1":
print("One player: rock, paper, scissor, lizard, spock")
player_one_rps()
break
elif menu_choice == "2":
print("Two player: rock, paper, scissor, lizard, spock")
player_two_rps()
break
elif menu_choice == "3":
print("Surprise! Bonus feature")
dad_jokes()
break
elif menu_choice == "4":
print("User guide")
user_info()
elif menu_choice == "5":
print("Quit game")
exit()
elif menu_choice != 1 - 5:
print("Error, choose a valid number")
# print(menu_choice)
game_menu()
main()
# First game
def player_one_rps():
"""One player rock, paper, scissor, lizard, spock - game"""
import random
def instructions():
"""Displays menu and simple instructions on how to play"""
print("Welcome to rock, paper, scissor, lizard, spock!")
play = input("\nNavigate by \"yes\", \"no\", and numbers.\nNew game?:").lower()
if play == "yes":
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Lizard")
print("5. Spock")
elif play != "no":
print("an error has occured. Please type \"yes\" or \"no\":")
instructions()
def get_user_choice():
"""Prompts the player to pick a 'weapon'"""
choice = int(input("What do you choose?: "))
if choice > 5:
print("Invalid number, please try again....")
get_user_choice()
elif choice < 1:
print("Invalid number, please try again....")
get_user_choice()
elif choice == 1:
print("You chose rock")
elif choice == 2:
print("You chose paper")
elif choice == 3:
print("You chose scissor")
elif choice == 4:
print("You chose lizard")
elif choice == 5:
print("You chose spock")
return choice
def get_pc_choice():
"""The computer chooses a random weapon"""
choice = random.randint(1, 5)
if choice == 1:
print("PC chose rock")
elif choice == 2:
print("PC chose paper")
elif choice == 3:
print("PC chose scissor")
elif choice == 4:
print("PC chose lizard")
elif choice == 5:
print("PC chose spock")
return choice
def winner(user_choice, pc_choice, user_wins, pc_wins, ties):
"""Calculates if the player or computer won the match"""
if user_choice == 1 and pc_choice == 3 or pc_choice == 4:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 2 and pc_choice == 1 or pc_choice == 5:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 3 and pc_choice == 2 or pc_choice == 4:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 4 and pc_choice == 2 or pc_choice == 5:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 5 and pc_choice == 1 or pc_choice == 3:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == pc_choice:
print("\nTie")
ties = ties.append(1)
else:
print("\nPC won")
pc_wins = pc_wins.append(1)
return
def game_total(user_wins, pc_wins, ties):
"""Displays the total score"""
user_wins = sum(user_wins)
pc_wins = sum(pc_wins)
ties = sum(ties)
print("Your final score: ", user_wins)
print("PC\'s final Score: ", pc_wins)
print("Total ties: ", ties)
def main_one_p():
"""Main instructions for how the game runs"""
user_choice = 0
user_wins = []
pc_choice = 0
pc_wins = []
ties = []
final_user_wins = 0
final_pc_wins = 0
final_ties = 0
Continue = "yes"
instructions()
while Continue == "yes":
user_choice = get_user_choice()
pc_choice = get_pc_choice()
winner(user_choice, pc_choice, user_wins, pc_wins, ties)
Continue = input("Would you like to play again: ").lower()
if Continue == "no":
print("This is the final scores.")
break
game_total(user_wins, pc_wins, ties)
main_one_p()
player_one_rps()
game_menu() # Returns player to the main menu
(sorry if it is quite long)
Could anyone help point me in the direction of my mistake? Explanations and tips on how to fix it would also be greatly appreciated :)
In general, I'm thankful for all feedback, as i really want to become better at coding.
The global function must have a higher declarative code than where it is called. Simply reposition the function. The function game_menu must be below the function play_one_rps. The other functions are the same.

Python Rock Paper Scissors game ( Loop for certain condition )

I made a simple Rock Paper Scissors program, and I need to add a certain condition to this program.. I have to Let the
user play continuously until either the user or the computer wins more than two times in a row.I tried to find the answer in and out but unfortunately couldn't find it..
First off I tried
gameOver = False
playerScore = 0
computerScore = 0
and added
while not gameOver:
main()
if playerScore == 2 :
gameOver = True
and also added playerScore += 1 to the if statements..
But wouldn't work ...
any advise would help and much appreciated in advance.. cheers!
And here is my code..
import random
import sys
def main():
player = input("Enter your choice in number (rock 1 / paper 2 / scissors 0) :")
if (player == 0):
player = "scissors"
elif (player == 1):
player = "rock"
elif (player == 2):
player = "paper"
else:
print("Invalid Input Quitting...")
sys.exit(0)
computer = random.randint(0,2)
if (computer == 0):
computer = "scissors"
elif (computer == 1):
computer = "rock"
elif (computer == 2):
computer = "paper"
if (player == computer):
print("Player is ",player, "Computer is ",computer," You Draw!")
elif (player == "rock"):
if (computer == "paper"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
elif (player == "paper"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Win!")
else:
print("Player is ",player, "Computer is ",computer," You Lost!")
elif (player == "scissors"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
If you have your main() function return a value corresponding to who won, you could do:
gameOver = False
playerScore = 0
computerScore = 0
while not gameOver:
player_wins = main()
if player_wins == True:
playerScore += 1
computerScore = 0
if player_wins == False:
playerScore = 0
computerScore += 1
if player_wins == None:
# Draw, do nothing to the scores
pass
if playerScore == 2 or computerScore == 2:
print("Game over")
print(" playerScore:", playerScore)
print(" computerScore:", computerScore)
gameOver = True
Note that I had it return True if the player won, False if the computer won, and None if it was a draw.
I think you are asking only a schema:
(this is no true code)
Program starts:
gameover = False
lastWinner = ""
Loop until gameover == True
ask for player answer
make the random choice of the computer
winner = "asigned winner"
if lastWinner == winner:
gameover = True
Print something cool about who is the winner
else:
lastWinner = winner
You may be getting an error when attempting to modify the globals, but from your example it's not entirely clear.
If you try to modify playerScore or computerScore in your main() method, it'll yell at you unless you have a statement like:
global computerScore
before you modify it.
Also, avoid repeating yourself in your code. I was able to trim much of your code out by using the following:
computerWins = False
print "Player is %s; Computer is %s" % (computer, player)
if (player == computer):
print "Draw"
return 0
elif (player == "rock"):
computerWins = computer == "paper"
elif (player == "paper"):
computerWins = computer == "scissors"
elif (player == "scissors"):
computerWins = computer == "rock"
if computerWins:
global computerScore
computerScore = computerScore + 1
print "Computer wins"
else:
global playerScore
playerScore = playerScore + 1
print "You win"

Categories

Resources