So, I'm relatively new to Python and I apologise in advance if this question seems dumb.
In the practice game I am attempting to make to understand how to make my own text-based adventure, the player is asked if they will proceed and they must use their lantern to advance further down a tunnel, subsequently saying this;
elif nolamp and lan2 == ("use lantern") or lan2 == ("USE LANTERN") or lan2 == ("Use lantern") or lan2 == ("use LANTERN") or lan2 == ("Use LANTERN"):
litlamp = True
nolamp = False
tunnel2 = True
print ("")
print ("You light the lantern and can now see.")
print ("The tunnel is still very dark ahead.")
time.sleep(2)
print ("The walls look wet.")
time.sleep(1.6)
print ("Will you go back?")
print ("")
If their lantern is not on, it will print so with;
elif nolamp and lan2 == ("n") or lan2 == ("N") or lan2 == ("no") or lan2 == ("NO") or lan2 == ("No"):
print ("You would continue, but it's too dark and cold.")
print ("To go any farther like this would be a bad idea.")
time.sleep(2.5)
print ("Will you go back?")
The statements are defined above within a separate while loop;
lanternv2 = True
tunnelv1 = True
nolamp = False
tunnel2 = False
litlamp = False
The player should continue when their lantern is lit with this;
elif tunnel2 and lan2 == ("n") or lan2 == ("N") or lan2 == ("no") or lan2 == ("NO") or lan2 == ("No"):
tunnel3 = True
tunnel2 = False
print ("You continue onward.")
print ("You still see no light and the entrance is disappearing behind you.")
time.sleep(2.5)
print ("It's very very cold.")
time.sleep(1.1)
print ("Will you go back?")
My issue however, is when the player tries to use any other answer than "n" when their lantern is lit, what will be printed is as though their lamp hasn't been used.
Does anyone know why this could be and do I need to be more specific? Thanks and again, sorry if this a stupid question.
I wasn't able to follow what you want from the code, but hopefully below gives you some ideas to follow. Specifically you ask "any other answer than "n" when their lantern is lit [but it prints] as though their lamp hasn't been used". The only answer provided that is not "no" is the "use lantern option", but that option checks if the player has no lamp. And the other statements will only print if you do answer "no". So it seems to me that the part of the code that is printing is not included in the question.
I tried to keep it simple to follow along and maybe it can give some clues! I had fun writing it anyway.
import random
# I tried to keep the code similar to yours
lanternv2 = True
tunnelv1 = True
nolamp = False
tunnel2 = False
litlamp = False
lan2 = ""
#The statements are defined above within a separate while loop;
while lan2 != "no" and lan2 != "n" and lan2 != "y":
lan2 = input("Do you want to use a lantern to enter the dark and very spooky cave?")
lan2 = lan2.lower()
if lan2 == "y":
# Player has entered the cave
litlamp = True
nolamp = False
tunnel2 = True
inCave = True #always true while in the cave
print ("")
print ("You light the lantern and can now see.")
print ("The tunnel is still very dark ahead.")
#time.sleep(2)
print ("The walls look wet.")
#time.sleep(1.6)
while(inCave):
# generates a random number 0 - 1
if(random.random() <.1):
print("Your lantern sputters and the light disappears")
litlamp = False
caveInput = input("Will you go back?").lower()
if not litlamp and (caveInput == ("n") or caveInput == ("no")):
print ("You would continue, but it's too dark and cold.")
print ("To go any farther like this would be a bad idea.")
#time.sleep(2.5)
print ()
#The player should continue when their lantern is lit with this;
elif litlamp and (caveInput == ("n") or caveInput == ("no")):
# They can only continue into the cave
print ("You continue onward.")
print ("You still see no light and the entrance is disappearing behind you.")
#time.sleep(2.5)
print ("It's very very cold.")
#time.sleep(1.1)
else: # should check if yes but this is taking too long lol
print("you flee the cave, never to return")
#break out of the while loop
inCave = false
print("You have fled the cave")
Related
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
When im using python on codecademy the tutorials on there use if(): statement then else(): statement. But sometimes it uses if(): then elif(): statement. I dont understand when your suppose to switch them out or which to use first.
def fruit_color(fruit):
if fruit == "apple":
return "red"
elif fruit == "banana":
return "yellow"
elif fruit == "pear":
return "green"
We could survive in a world in which there was no elif statement. We could do this:
def fruit_color(fruit):
if fruit == "apple":
color = "red"
else:
if fruit == "banana":
color = "yellow"
else:
if fruit == "pear":
color = "green"
# ...
# ....
# ...
# ...
# ...
# ... --->
return color
but it's rather inconvenient that the nesting keeps increasing and increasing---limited only by the number of types of fruit you want to check, which may be large. It makes code hard to follow, and in Python it also means the indentation must keep increasing: soon you won't be able to see all your code within the same screen-width.
The elif statement solves this inconvenience by allowing you to collapse an else followed immediately by an if into a single statement that doesn't require an increase in nesting.
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"
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.
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]