How to make Python continue with a game after while loop or if statement - 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

Related

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"

calling function twice or more and getting TypeError 'int' is not callable

I need some help with one my functions, The first time you call it, it works perfectly, however on subsequent runs through an if/else statement it gives out TypeError 'int' is not callable. in order to see this, when given the option use Hunt, then on the second run use Hunt again. I am using Python 2.7, code is: -
from sys import exit
import random
equipment = ['Bolter', 'Bolt Pistol', 'Combat Knife']
print "Your ship has crash landed on an unknown planetoid, what do you do?
Explore, Overwatch, Hunt or Nothing"
def enemy_attack():
enemy_attack = random.randrange(0, 7)
if enemy_attack <= 5:
print "Enemy Misses"
print "Your Turn"
you_attack()
elif enemy_attack == 6:
print "Enemy kills you"
else:
print "Enemy ran away"
def you_attack():
you_attack = random.randrange(0, 7)
if you_attack <= 2:
print "You missed"
print "Thier Turn"
enemy_attack()
else:
print "You killed the enemy"
print "What do you do? Explore, Overwatch, Hunt, or Nothing"
do = raw_input("> ")
if "Explore" in do:
print "You find a sealed container"
print "Your Equipment is", equipment
print "Do you want to open the container? Yes or No"
container = raw_input("> ")
if "Yes" in container:
open_container()
else:
print "You left it alone"
elif "Overwatch" in do:
print "Orks Attack!!!"
enemy_attack()
elif "Hunt" in do:
print "You attack the Orks!"
you_attack()
else:
print "The planetoid swallows you whole, and adds your mass to it!!"
exit(0)
def open_container():
open_container = random.randrange(0,5)
if open_container == 0:
print "You have found a Plasma Gun!"
equipment.append('Plasma Gun')
print "Your equipment is now", equipment
elif open_container == 1:
print "You have found a Chainsword!"
equipment.append('Chainsword')
print "Your equipment is now", equipment
elif open_container == 2:
print "You have found a Power Sword"
equipment.append('Power Sword')
print "Your equipment is now", equipment
else:
print "There is nothing here for you!!"
do = raw_input("> ")
if "Explore" in do:
print "You find a sealed container"
print "Your Equipment is", equipment
print "Do you want to open the container? Yes or No"
container = raw_input("> ")
if "Yes" in container:
open_container()
else:
print "You left it alone"
elif "Overwatch" in do:
print "Orks Attack!!!"
enemy_attack()
elif "Hunt" in do:
print "You attack the Orks"
you_attack()
else:
print "The planetoid swallows you whole, and adds your mass to it!!"
exit(0)

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()

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

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.

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]