Trying to re-loop a game only if a user says to - python-2.7

I'm trying to make an old rock, paper, scissors game I made better by asking the user if they would like to replay or not..
This is the code I have been working on:
# ROCK, PAPER, SCISSORS !!!
# BY: NICK GRIMES
from random import randint
replay = True
while replay == True:
replay = False
userChoice = raw_input("> Choose rock, paper, or scissors: ")
computerChoice = randint(1, 101)
if computerChoice <= 34:
computerChoice = "rock"
elif computerChoice <= 67:
computerChoice = "paper"
else:
computerChoice = "scissors"
print "> The computer chooses: " + str(computerChoice)
if userChoice == computerChoice:
print "> It's a tie! Thank you for playing!"
askUserPlayAgain = raw_input("> Would you like to play again? Enter [yes or no]: ")
if askUserPlayAgain.lower()[0] == "y":
replay == True
elif askUserPlayAgain.lower()[0] == "n":
break
# ---
elif userChoice == "rock":
if computerChoice == "scissors":
print "> Rock crushes scissors!"
print "> You win!"
else:
print "> Paper covers rock!"
print "> Computer wins!"
# ---
elif userChoice == "paper":
if computerChoice == "rock":
print "> Paper coveres rock!"
print "> You win!"
else:
print "> Scissors cuts paper!"
print "> Computer wins!"
# ---
elif userChoice == "scissors":
if computerChoice == "rock":
print "> Rock crushes scissors"
print "> Computer wins!"
else:
print "> Scissors cuts paper"
print "> You win!"
# ---
else:
print "Please choose either rock, paper, or scissors only!"
Now, the actual game has always worked, but with trying to implement this new idea, I actually deleted the function that compared the two choices, and just left them to the if/else's...
The main problem is this: when a user types 'yes', it should restart the game, but it does absolutely nothing for some reason. If anyone see's anything that could be causing this, please let me know. Thank you!

This doesn't make much sense to me:
replay = True
while replay == True:
replay = False
I think you'd be better off using a while True: loop. Use the continue keyword if the user selects to restart the game and the replay variable is not required.
from random import randint
while True:
userChoice = raw_input("> Choose rock, paper, or scissors: ")
computerChoice = randint(1, 101)
if computerChoice <= 34:
computerChoice = "rock"
elif computerChoice <= 67:
computerChoice = "paper"
else:
computerChoice = "scissors"
print("> The computer chooses: " + str(computerChoice))
if userChoice == computerChoice:
print("> It's a tie! Thank you for playing!")
askUserPlayAgain = raw_input("> Would you like to play again? Enter [yes or no]: ")
if askUserPlayAgain.lower()[0] == "y":
continue
elif askUserPlayAgain.lower()[0] == "n":
break

Just changed
while replay == True:
to
while True:
and it just work fine for me.

Related

How to make Python continue with a game after while loop or if statement

I’m trying to get my game to continue to the games after a user inputs “yes” or “no”. Here is the code:
user_name =input ("What is your name? ")
user = user_name
print(f"Welcome {user}!")
user_ans = ''
while True:
user_ans = input("Are you ready to play ROCK, PAPER, SCISSORS? (yes or no?) ")
if user_ans.lower() == 'yes':
print("Alright, Let's play!")
continue
elif user_ans.lower() == 'no':
print('Not ready to play? Okay, see ya later!')
exit()
else:
print('Type yes or no')
if user_ans.lower() == 'yes':
def get_choices(): #get_choices is a function
player_choice = input("Enter a choice (rock, paper, scissors): ")
options = ['rock', 'paper', 'scissors']
computer_choice = random.choice(options)
choices = {"player":player_choice, "computer":computer_choice}
return choices
def check_win(player, computer ):
print(f"You chose {player}, computer chose {computer}.")
if player == computer:
return "It's a tie!"
#if player chooses "ROCK"
elif player == "rock":
if computer == "scissors":
return "Rock smashes scissors! You win!"
The main part I need help with is yes or no part. The loop works except for the fact that it won’t continue to the game after that.
I initially tried using an if/else statement but I’d didn’t work well. I’ve only made progress with the while loop.
You can do that way:
import random
user_name = input("What is your name? ")
user = user_name
print(f"Welcome {user}!")
user_ans = ''
while True:
user_ans = input("Are you ready to play ROCK, PAPER, SCISSORS? (yes or no?) ")
if user_ans.lower() == 'yes':
print("Alright, Let's play!")
break
elif user_ans.lower() == 'no':
print('Not ready to play? Okay, see ya later!')
exit()
else:
print('Type yes or no')
def get_choices():
player_choice = input("Enter a choice (rock, paper, scissors): ")
options = ['rock', 'paper', 'scissors']
computer_choice = random.choice(options)
choices = {"player": player_choice, "computer": computer_choice}
return choices
def check_win(player, computer):
print(f"You chose {player}, computer chose {computer}.")
if player == computer:
return "It's a tie!"
elif player == "rock":
if computer == "scissors":
return "Rock smashes scissors! You win!"
else:
return "Paper covers rock! You lose!"
elif player == "paper":
if computer == "rock":
return "Paper covers rock! You win!"
else:
return "Scissors cut paper! You lose!"
elif player == "scissors":
if computer == "paper":
return "Scissors cut paper! You win!"
else:
return "Rock smashes scissors! You lose!"
else:
return "Invalid input. Please try again."
while True:
choices = get_choices()
result = check_win(choices["player"], choices["computer"])
print(result)
play_again = input("Do you want to play again? (yes or no) ")
if play_again.lower() == "no":
print("Thanks for playing!")
break

Error in Tic tac toe Program (Python)

The code shown below is that of a Tic tac toe game in which there are two players (Player1 and Player2 are humans). I have an issue in the if else statements in the "# Player 1 Plays now" and "# Player 2 Plays now" sections of the code. To be precise, the computer always thinks that every box is already filled with some value other than 1,2,3,4,5,6,7,8,9 and it keeps displaying the message "That cell is already marked. Please try another cell" defined in the nested else statement.
Can somebody enlighten me how to fix this problem ?
board = [0,1,2,3,4,5,6,7,8,9]
print type(board[1])
def board_invoke():
print "| ",board[1], " | ", board[2], " | ", board[3], " | ", "\n", "-------------------", "\n", "| ", board[4], " | ",board[5], " | ", board[6], " | ", "\n", "-------------------", "\n", "| ", board[7], " | ",board[8], " | ", board[9], " | "
def game_start():
Player1= raw_input("Select Player 1 between X or O : ")
if Player1 not in ('X','x','O','o'):
print "That is not an expected player"
game_start()
else:
print "\nSince you have selected Player 1 as %s" %Player1
print "\nThe Player 2 is assigned :",
if Player1 in ('X','x'):
Player2 = ("O")
else:
Player2 = ("X")
print Player2
print "\nThe game Starts now....\n"
board_invoke()
while (1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9) in board:
# Winning Condition
if board[1]==board[2]==board[3]==Player1:
print Player1," wins"
break
elif board[4]==board[5]==board[6]==Player1:
print Player1, " wins"
break
elif board[7]==board[8]==board[9]==Player1:
print Player1, " wins"
break
elif board[1]==board[2]==board[3]==Player2:
print Player2, " wins"
break
elif board[4]==board[5]==board[6]==Player2:
print Player2, " wins"
break
elif board[7]==board[8]==board[9]==Player2:
print Player2, " wins"
break
elif board[1]==board[5]==board[9]==Player1:
print Player1, " wins"
break
elif board[3]==board[5]==board[7]==Player1:
print Player1, " wins"
break
elif board[1]==board[5]==board[9]==Player2:
print Player2, " wins"
break
elif board[3]==board[5]==board[7]==Player2:
print Player2, " wins"
break
elif board[1]==board[4]==board[7]==Player1:
print Player1, " wins"
break
elif board[2]==board[5]==board[8]==Player1:
print Player1, " wins"
break
elif board[3]==board[6]==board[9]==Player1:
print Player1, " wins"
break
elif board[1]==board[4]==board[7]==Player2:
print Player2, " wins"
break
elif board[2]==board[5]==board[8]==Player2:
print Player2, " wins"
break
elif board[3]==board[6]==board[9]==Player2:
print Player2, " wins"
break
# Player 1 Plays now
Cell_no = raw_input("Player 1 : Please select a number you want to mark....")
Cell_no = int(Cell_no)
if Cell_no not in board:
print "Please enter a cell number within the scope of available cells"
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
continue
else:
board[Cell_no] = Player1
board_invoke()
# Player 2 Plays now
Cell_no = raw_input("Player 2 : Please select a number you want to mark....")
Cell_no = int(Cell_no)
if Cell_no not in board:
print "Please enter a cell number within the scope of available cells"
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
continue
else:
board[Cell_no] = Player2
board_invoke()
print "Do you want to play again ?"
user_decision = raw_input("Please type Yes or No : ")
if user_decision == ('YES' or 'Yes' or 'yes'):
game_start()
else:
print "Ok. I take it that we will wrap up !"
print "See you again !"
game_start()
Your if statement is not completely correct.
You are evaluating:
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
which is always true. The or keywords combines each comparison logically. The first compare statement would then simply be 'X', which is not null or 0 and therefor always true. As the first statement is true, the whole if-statement is true.
I see this quite often on people starting to learn programming. If-statements can't be written exactly like human sentences. You have to compare every single character to your variable.
Here is a simple (not python specific and quite ugly) solution to your problem:
else:
if 'X' == board[Cell_no] or 'x' == board[Cell_no] or 'O' == board[Cell_no] or 'o' == board[Cell_no]:
print "That cell is already marked. Please try another cell"
An even better approach though would be to turn that check around and compare it with a list:
else:
if board[Cell_no] in ['X','x', 'O', 'o']:
print "That cell is already marked. Please try another cell"

How i make the code skip to a certain point in a if-statement

I'm working on a basic game. I'd like to know how I can make the code go to a specific point in the code/if-statement, rather than starting off at the beginning.
For example, in my code at line 19: kithcen() I don't want to redirect it to the start of the if-statement; again going on the describe the kitchen and then asking for an input: choice02 = raw_input("What do you do?"), but rather i want it to directly skip to the input part.
def kitchen():
print "You see a dusty old kitchen, nobody has probably used it for quite a while."
print "There are 3 different cupboards(0, 1, 2) or a letter(3) placed on the counter."
choice02 = raw_input("What do you do? >")
if choice02 == "0" or choice02 == "first cupboard" or choice02 == "check first cupboard" or choice02 == "open first cupboard":
print "You see a dusty empty bottles of milks, with spiderwebs at the corners of the cupboard. Nothing of Interest here."
raw_input(">")
kitchen()
elif choice02 == "1" or choice02 == "second cupbaord" or choice02 == "check second cupboard" or choice02 == "open second cupboard":
print "You see some packs of likely expired cereal and a key(0)."
choice_02_A = raw_input("What do you do? >")
#----------------------------------------------------------------------------------------------------------#
if choice02_A == "pick key" or choice02_A == "key" or choice02_A == "0" or choice02_A == "get key":
print "You picked the key. This probably unlocks some door."
raw_input("> ")
kitchen()
elif choice02_A == "close cupboard" or choice02_A == "kitchen" or choice02_A == "go back to kitchen":
kitchen()
else:
print "Not a valid option."
#-----------------------------------------------------------------------------------------------------------#
elif choice02 == "2" or choice02 == "third cupboard" or choice02 == "check third cupboard" or choice02 == "open third cupboard":
print "You see an empty or dusty cupboard. Nothing of interest here."
raw_input("> ")
kitchen()
elif choice02 == "3" or choice02 == "check letter" or choice02 == "letter" or choice02 == "read letter":
print """
You read the letter:
\n"Dear Shawn............\n"
It makes no sense to you.
"""
elif choice02 == "go back" or choice02 == "entrance hall" or choice02 == "go to entrance hall":
entrance_hall()
else:
"Not a valid Option."
I see no loop, but if you only want the print statements when you call the function from outside, you could have an optional boolean like this:
def kitchen(already_there=False):
if not already_there:
print('...')
choice02 = raw_input("What do you do? >")
# ...
elif # ...
# ...
kitchen(already_there=True)
You might want to consider refactoring your code and using dictionaries to avoid long if-else statements.
See https://stackoverflow.com/a/27365077/2884613.
print "There are 3 different cupboards(0, 1, 2) or a letter(3) placed on the counter."
alias = {
'0': '0',
'first cupboard': '0',
'check first cupboard': '0',
'open first cupboard': '0',
'1': '1',
'second cupboard': '1',
'check second cupboard':'1',
...
}
dic = {
"0":"You see a dusty empty bottles of milks, with spiderwebs at the corners of the cupboard. Nothing of Interest here.", \
"1":"You see some packs of likely expired cereal and a key(0).", \
"2":"You see an empty or dusty cupboard. Nothing of interest here."
...
}
while(True):
choice02 = raw_input("What do you do? >")
if choice02 in alias:
print dic[alias[choice02]]
break
else:
print "Not a valid option"

Rock, paper and scissors improvement: Python 2.7?

I am new to python and have attempted to write a little project relating to the subject above.
import random
option = ["rock", "paper", "scissors"];
pc_selection = ["rock", "paper", "scissors"];
pc_move = random.choice(pc_selection)
#-------------------------------------------------------------------------------
def first_condition():
select = raw_input("Please select your choice\n")
print "Your choice:", select
if select in option:
pc_move
print "Computer choice:", pc_move
else:
first_condition()
if select == pc_move:
print "Result: draw"
elif select == "rock" and pc_move == "paper":
print "Result: Computer wins"
elif select == "paper" and pc_move == "scissors":
print "Result: Computer wins"
elif select == "scissors" and pc_move == "rock":
print "Result: Computer wins"
elif select == "rock" and pc_move == "scissors":
print "Result: You win"
elif select == "paper" and pc_move == "rock":
print "Result: You win"
elif select == "scissors" and pc_move == "paper":
print "Result: You win"
first_condition()
I know my code aren't very efficient (fastest and cleverest), so my question is:
Which part could I amend to make my project as shortest as possible without losing its functionaility, i.e. using other functions that could reduce the length of my code?
Thanks!
Every option in the option list is beaten by the option that precedes it. If the choices are different then it can be assumed that user wins if the computer did not choose the item that precedes the user's choice in the list. Example:
import random
option = ["scissors", "paper", "rock"] # I reversed the original list
#----------------------------------------------------------------------
def first_condition():
pc_move = random.choice(option) # there only needs to be 1 option list
select = raw_input("Please select your choice\n")
print "Your choice:", select
if select in option:
print "Computer choice:", pc_move
else:
return first_condition()
if pc_move == select:
print("Draw")
return
# find the index of the user's choice
index = option.index(select)
# did the pc choose the item before this one?
you_win = option[index-1] != pc_move
print("You %s" % ("win" if you_win else "lose"))
while True:
print("-"*50)
first_condition()

How do you make a conditional statement In Python?

I'm confused on how to make conditional statements. I just can't seem to figure it out. In the example bellow I want the shoot input to only work if the user chose in this case the gun earlier in the game. Same with the knife and so on.
def chap4():
print "You feel around the room.\n"
time.sleep(3)
print "You find a small chest...\n"
time.sleep(3)
print "You open the chest...\n"
time.sleep(2)
print "[pickaxe, shovel, lighter, axe, 9mm(0), knife]\n"
while (True):
chest = raw_input("What will you take?: ")
if chest == "pickaxe":
print "You take the pickaxe"
break
elif chest == "shovel":
print "You take the shovel"
break
elif chest == "lighter":
print "You take the axe"
break
elif chest == "9mm":
print "You take the empty 9mm pistol"
break
elif chest == "knife":
print "You take the knife"
break
elif chest == "axe":
print "You take the axe"
break
else:
print "Invalid choice. Try again..."
chap4()
def zombie():
print "A zombie is seem in the distance"
while (True):
attack = raw_input("> ")
if attack == "shoot":
print "Zombie hp 50/100"
elif attack == "stab":
print "Zombie hp 70/100"
else:
print "Invalid input. Try again..."
So as you can tell by the code in having trouble... I originally thought maybe I'd make another if statement within the if statement but I'm not sure. Please help if you can... Thanks!
I recommend putting a conditional if
def chap4():
....
return(chest)
def zombie()
weapon = chap4()
if weapon == "9mm":
if attack =="shoot":
print(...)
elif attack =="stab":
...
And so on.
So specify the weapon in the conditional in zombie(). Also, zombie() will have to know the chest variable, soreturn(chest) at the end of chap4() function, and call chap4() within zombie()
EDIT: when calling chap4() in zombie(), it needs to called a variable, in this case, weapon
The conditional statements are fine, so far as they go. The problem is that you aren't saving the outcomes anywhere. Do something like
if chest == "pickaxe":
print "You take the pickaxe"
weapon = "pickaxe"
elif chest == "shovel":
print "You take the shovel"
weapon = "shovel"
etc.
When the user choose an attack mode, you can check that he has the appropriate weapon:
if attack == "shoot":
if weapon == "9mm":
print "Zombie hp 50/100"
else:
print "you don't have a pistol"
Here too, printing is probably not enough. You'll want to keep track of what's happened, I would think
You can store what chest cointain like this:
chestContainer= {"pickaxe": "pickaxe", "shovel": "shovel", "lighter": "lighter", "9mm(0)": "9mm(0)", "knife": "knife", }
And then you can print the option like this:
print chestContainer[chest]
And you can evaluate if the input is valid like this:
if chestContainer[chest] == None:
print "Invalid choice. Try again..."
Edit:
As user908293 said you have to save what weapon you chose.
weapon = chestCointainer[chest]