when an invalid answer (a number higher than 2) is given and is sent back to the intro(name) (see the else statement at the bottom) which is the introduction, the choise1 is auto completed and is redirected to crowbar()
def intro(name):#added the whole code
print( name + " you are in a back of a car hands tied, you can't remember anything apart the cheesy pizza you had for breakfast")
time.sleep(1)
print("you can see 2 men outside the car chilling out, they haven't seen that you have waken up")
time.sleep(1)
print("you figure out that your hands are not tied hard and manages to break free")
time.sleep(1)
print("and you see a piece of paper with your adress in it on the armrest in the middle of the front seats")
time.sleep(1)
print(" you see a crowbar under the back seat ")
time.sleep(1)
print("CHOOSE WISELY")
time.sleep(1)
print("""
1)grab the crowbar
2)check to see if the door was open""")
def car():
if choise1 == 1:
crowbar()
elif choise1 == 2:
door()
else:
print("that's not a valid answer")
intro(name)
choise1 = int(input("enter 1 or 2"))
car()
you can use function with parameter in this example (x )
def car(x):
if x == 1:
print("crowbar()")
elif x == 2:
print("door()")
else:
print("that's not a valid answer")
print("intro(name)")
choise1 = int(input("enter 1 or 2"))
car(choise1)
Related
It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))
I am pretty much a beginner at Python and for my assignment I am creating a text based game and I want to make an item system. However, there is an error in part7a that says TypeError: part7a() missing 1 required positional argument: 'part5'.
I am unsure why the item_count is not carrying over and if someone could provide any kind of assisstance it would be greatly appreciated. Thanks!
def part5():
print("As you venture across the path, you reach a crossroads...")
time.sleep(1)
print("You stop at the crossroads as you are met with 3 different paths...")
time.sleep(2)
print("Something shiny on the floor catches your eye...")
time.sleep(2)
print("You look down and it appears to be an old sword with a blue gem in its core...")
answer = ""
while answer.lower().strip() != "yes" and answer.lower().strip() != "no":
answer = input("Take the sword? (yes/no): ")
if answer.lower().strip() == "yes":
item_count = 0
item_count = item_count + 1
time.sleep(1)
print("- Item added to your backpack -")
time.sleep(2)
print("You pick up the sword, now it's time to make your decision.")
time.sleep(2)
part6()
elif answer.lower().strip() == "no":
time.sleep(2)
print("You think nothing of the sword and carry on to make your decision.")
time.sleep(2)
part6()
return
def part6():
answer = ""
while answer != "1" and answer != "2" and answer != "3":
answer = input("What path will you choose? (1/2/3): ")
battleAnswer = "2"
if answer == battleAnswer:
time.sleep(2)
print("You head down path", answer+"...")
part7a()
else:
time.sleep(2)
print("You head down path", answer+"...")
part7b()
return
def part7a(part5):
time.sleep(2)
print("After travelling for a while you find the path becoming darker...")
time.sleep(2)
print("And darker...")
time.sleep(2)
print("Until...")
time.sleep(2)
print("A tall dark monster appears before you...")
time.sleep(2)
print("Lets hope you know what you're doing!!")
time.sleep(1)
answer = ""
while answer.lower.strip() != "yes" and answer.lower().strip() != "no":
answer = input("Fight the monster? (yes/no): ")
if answer == "yes" and item_count == 1:
time.sleep(2)
print("- Sword equipped from backpack -")
time.sleep(2)
print("You firmly grasp the sword in your hands...")
time.sleep(2)
print("It fills you with determination...")
time.sleep(2)
print("The monster charges towards you...")
time.sleep(2)
print("You run up with your sword, challenging the monster...")
time.sleep(1)
print("The monster accepts your challenge and begins running towards you...")
time.sleep(2)
print("Stomp, stomp, STOMP!!")
time.sleep(1)
print("SLICEEEEEEEE!")
time.sleep(2)
print("With a brave slash of your sword you slice through the monster...")
time.sleep(2)
print("You face monster that had been cut in two...")
time.sleep(2)
print("It looks you in the eye as it slowly fades away into dust.")
time.sleep(3)
part8()
else:
time.sleep(2)
print("In a brave effort you attempt to sprint around the monster...")
time.sleep(2)
print("It looks down at you and stomps on you as if you are an ant.")
time.sleep(2)
restart()
def part7b():
print('hello')
I'll try to keep it short and sweet.
I'm writing an interactive story that changes based on the "roll" of a d20 dice. I've managed to figure out getting started, but I've hit a point where I don't think Python is actually listening to the parameters I'm giving it, because it kind of just does whatever.
Essentially, here's what's supposed to happen:
Player agrees that they want to play the game -> Player Rolls dice -> Game uses the randomly rolled number to determine which start that the player will have.
What's currently happening is, all goes well until it's supposed to spit out the start that the player has. It doesn't seem to actually decide based on my parameters. For example, you're supposed to have the "human" start if the player rolls 5 or less, and an "elf" start for anything between 6 and 18. Here's what happened yesterday:
venv\Scripts\python.exe C:/Users/drago/PycharmProjects/D20/venv/main.py
Hello! Would you like to go on an adventure? y/n >> y
Great! Roll the dice.
Press R to roll the D20.
You rolled a 15!
You start as a human.
As a human, you don't have any special characteristics except your ability to learn.
The related code is below:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
print("You rolled a " + str(RollD20()) + "!")
PostGen()
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
def PostGen():
if RollD20() <= 5:
print("You start as a human.")
PostStartHum()
elif RollD20() >= 6:
print("You start as an elf.")
PostStartElf()
elif RollD20() >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
def RollD20():
n = random.randint(1, 20)
return n
def PostStartHum():
print("As a human, you don't have any special characteristics except your ability to learn.")
def PostStartElf():
print("As an elf, you have a high intelligence and a deep respect for tradition.")
def PostStartDemi():
print("As a demigod, you are the hand of the gods themselves; raw power incarnated in a human form...")
print("However, even mighty decendants of gods have a weakness. Be careful."
Thanks for all your help.
Turn your PostGen function into the following:
def PostGen(rollValue):
if rollValue <= 5:
print("You start as a human.")
PostStartHum()
elif rollValue >= 6:
print("You start as an elf.")
PostStartElf()
elif rollValue >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
Change your NewGame function to the following:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
rollValue = RollD20()
print("You rolled a " + str(rollValue) + "!")
PostGen(rollValue)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
You are generating a new random number every time you call RollD20(). You need to store the value somewhere and reuse it for the game session.
Each time you call RollD20, you get a new random number. So if you want to use the same random number in multiple ifs, you need to tuck that value into another variable.
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
result = RollD20()
print("You rolled a " + str(result) + "!")
PostGen(result)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
And from there you change PostGen() to accept the result:
def PostGen(result):
if result <= 5:
print("You start as a human.")
PostStartHum()
elif result >= 6:
print("You start as an elf.")
PostStartElf()
elif result >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()
#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your
name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you
enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
inp = input(" enter enter or leave: ")
if inp != "enter" and inp != "leave":
print(" You must type enter or leave")
if inp == "enter":
print(" You push with all your might on the large gates, it swings open with
a loud clunk.")
if inp == "leave":
print("")
print(" You turn around and go back, probably for the best.")
print("")
print(" Your character", character_name, "turned back and never returned.")
input(" Press enter to exit")
SystemExit("")
def choose_room():
#key = False is so the person does not have the key until going upstairs
global key
key = False
while True:
print("")
print(" Bookshelfs line the walls, a staircase is to the left and a door
is straight ahead.")
print("")
print(" Type 'a' to: Go up the stairs")
print(" Type 'b' to: To go through the door")
print(" Type 'c' to: To check the bookshelfs")
ans = input("")
if ans=='a':
print(" You walk up the creaking stairs")
print(" At the top of the spiral staircase is a small observatory.")
print(" Looking around on some of stacks of books littering the room
you")
print(" find a small key!")
key = True
continue
elif ans=='b':
#The door detects whether the key is True or not/they have the key or not.
if key == True:
print(" You open the door with the small key.")
elif key == False:
print(" The door is locked, you will need a key to go through
it.")
continue
return
choose_room()
else:
print("The door is locked, you will need a key to go through
it.")
continue
return
choose_room()
else:
ans == 'c'
print(" You look through the thousands of books.")
print(" None of them interest you.")
continue
return
choose_room()
Excuse my terrible Coding, this is my first project and I am surprised it works in the first place.
Also this is my first post on stack overflow.
My problem is this code worked perfectly did everything I needed it to, but then when I went to add some more detail to it, I decided to do that later and deleted everything I "added" now the code doesn't run anything but the first part before def choose_room():
No error message appears when I run it, it just does the first part then ignores the bit at "def choose_room():" completely.
Well that's all I can think of to add that might help find the cause. Next time I will make a copy of the file before changing anything so this doesn't happen again.
If nobody can find what the problem is, I will just try to remake the program from scratch again.
In Python, indentation is part of the syntax, so if you have things improperly indented your code won't behave as you would expect it to.
Corrected indentation:
#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
inp = input(" enter enter or leave: ")
if inp != "enter" and inp != "leave":
print(" You must type enter or leave")
if inp == "enter":
print(" You push with all your might on the large gates, it swings open with a loud clunk.")
if inp == "leave":
print("")
print(" You turn around and go back, probably for the best.")
print("")
print(" Your character", character_name, "turned back and never returned.")
input(" Press enter to exit")
SystemExit("")
def choose_room():
#key = False is so the person does not have the key until going upstairs
global key
key = False
while True:
print("")
print(" Bookshelfs line the walls, a staircase is to the left and a door is straight ahead.")
print("")
print(" Type 'a' to: Go up the stairs")
print(" Type 'b' to: To go through the door")
print(" Type 'c' to: To check the bookshelfs")
ans = input("")
if ans=='a':
print(" You walk up the creaking stairs")
print(" At the top of the spiral staircase is a small observatory.")
print(" Looking around on some of stacks of books littering the room you")
print(" find a small key!")
key = True
continue
elif ans=='b':
#The door detects whether the key is True or not/they have the key or not.
if key == True:
print(" You open the door with the small key.")
elif key == False:
print(" The door is locked, you will need a key to go through it.")
continue
return
choose_room()
else:
print("The door is locked, you will need a key to go through it.")
continue
return
choose_room()
else:
ans == 'c'
print(" You look through the thousands of books.")
print(" None of them interest you.")
continue
return
choose_room()
You defined the function choose_room() but never used/called it. It would go something like this.
#...
if inp == "enter":
print(" You push with all your might on the large gates, it swings open with a loud clunk.")
choose_room()
#...
Make sure to define the function before calling it. Place the def choose_room():... on top of the script or before actually choose_room