How can I implement a function/loop in a cmd game? - python

I've started to make a cmd-based minigame, and I wanna implement a feature, where you come across choices which you have to decide that what option will you choose. My problem however is that in my code, if you type anything other than the two options listed, than the game will just 'end' there.
print('Welcome to \'The Exchange\'.')
print('This game is all about making wise decisions with your money.')
print('At the beginning, you\'ll start out with 10$, and from here,')
print('Everything is YOUR choice! Have fun!\n')
# Starter informations. #
yourMoney = 100
# First choise part of the game. #
print('You\'ve come to your first decision of the game -')
print('Do you want to make an insurance for 5 dollars, or you just wanna skip it for now?')
firstDecision = input('Type \"make\" to make one, and \"skip\" to just skip it.\n')
if(firstDecision == "make"):
print("Fine.")
elif(firstDecision == "skip"):
print("Not fine.")
else:
print("You've misspelled it, try again!")
But I want to make it that if you type anything other than the two options, then the game would simply ask the question again, and again, until you type any of the two optins, and then, it would move on. I know, that I have to use some kind of loop, or function, and I also tried these in my code, but it haven't turned out too great. I'd greatly appreciate the help.

My suggestion with minimal change in the code.
print('Welcome to \'The Exchange\'.')
print('This game is all about making wise decisions with your money.')
print('At the beginning, you\'ll start out with 10$, and from here,')
print('Everything is YOUR choice! Have fun!\n')
# Starter informations. #
yourMoney = 100
# First choise part of the game. #
print('You\'ve come to your first decision of the game -')
print('Do you want to make an insurance for 5 dollars, or you just wanna skip it for now?')
firstDecision = input('Type \"make\" to make one, and \"skip\" to just skip it.\n')
while(firstDecision != 'make' or firstDecision != 'skip'):
if(firstDecision == "make"):
print("Fine.")
### Do here all your logics and in the end add the line below
break
elif(firstDecision == "skip"):
print("Not fine.")
### Do here all your logics and in the end add the line below
break
else:
print("You've misspelled it, try again!")
firstDecision = input('Type \"make\" to make one, and \"skip\" to just skip it.\n')
Please let me know if there were problems or this is not what you wanted.

Related

Betting system won't seem to process the user input correctly, how can this be improved?

I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned.
Here is what I have so far:
import random
import sys
money = "500"
# start the game
a = input("Hello travler, to start the game, please type 'yes'. If you are not ready to begin your journey, type 'no' ")
if a.lower() == "no":
sys.exit()
else:
print("Welcome")
print("Hold on... I'm missing something,")
name = input("What is your name, traveler?: ")
print("Welcome,", (name))
# those who need instructions can ask for it,
# others can start the game directly.
a = input("Welcome to a game that'll determine the rest of your life. Do you need instructions? (yes) or (no)? \n")
if a.lower() == "yes":
print('''1. the player will roll two six sided dice. the sum of the two dice is the player's number for the round.
2. rolling a 7 or an 11 as your first roll win you the game, but be weary, a 2, 3, or 12 automatically causes the player to lose. no more game for you. If a 4, 5, 6, 8, 9, or 10 are rolled on this first roll, that number becomes the 'point.'
3. the fated player continues to roll the two dice again until one of two things occur: either they roll the 'point' again, causing them to win the game; or they roll a 7, causing them to be doomed to the eternals.''')
elif a.lower() == "no":
print("may luck be with you on this fateful day,", name)
print("You will start off with 500 pieces of luck, if you leave this game with over 1000 pieces of luck, you will be fated for sucsess. On the other hand, should you drop below 0 peices of luck, you will find yourself in debt to the universe, a misfortune that few recover from.")
print("You currently have", money, "luck to spare")
# betting time
while True:
bet = input("How much luck do you wish to bet? ")
if bet.isdigit() is True:
if money > bet:
print("Bet accepted")
if bet.isdigit() is True:
if bet > money:
print("How unfortunate, you do not have the luck to make this bet.")
elif bet.isdigit() is False:
print ("Sorry, luck can only be quantitated in number values.")
# if you bet higher than your money, it wont allow you to bet within after that.
The code below the line # betting time is where I am hitting my head over.
I need the code to do the following:
check if the user input is in fact a number, if it's not a number, make them enter a new input
if the user input is a number, determine if it is within the amount they have in their 'wallet' (if not, make them input a new number)
if the number is within the amount in their 'wallet' and is a digit, give the user the option to "roll dice" triggering the game to start.
If they win, they need to be granted double what they bet, if they lose, they need to lose the amount they bet. The wallet will need to update after each play, giving the user the option to play again with their updated wallet (so if they bet 50 and win, their new balance will be 550. The process continues until the user either reaches 1000 or 0, causing the game to end either way.)
For checking if the user's bet is a number use the .isnumeric() function on your bet like:
bet.isnumeric()
to do the second thing you needed help with you could do:
if bet < wallet: blah blah blah elif
bet > wallet: print("You do not enough money")
around like that it with actual good syntax
to do dice you could use the random.randint() function like this:
random.randint(1,6)
I hope that helps!

Choose your own adventure - choice function?

I'm working on a choose-your-own-adventure game in Python to try to learn how to code. I might be doing this entirely wrong, but I thought rather than just nesting if-elif-else statements endlessly, I could write some sort of function that would be a template for all choices in the game.
My ideas was to have every decision in a given scene to generate two lists - choices and outcomes. The "multitemplate" function would then load the choose and outcomes lists, present the options to the player, take in the answer, and call the correct function for the outcome given.
My issue is that the outcome list is a list of functions, which Python doesn't seem to like. It says I've not defined the functions properly, but when I define my outcome functions before calling "multitemplate", it just prints them first.
Here's my code:
#Function to allow the adventurer to make choices
def refusal():
print("You stop at the roadsign you passed on your way into town. There are only two directions - towards Tarroway, or towards Angion, the town from whence you came.")
def guards():
print("The guards stop you.")
def theinn():
print("You follow the joyful chatter down the deserted street. Its source is a squat, one story building. A sign above the door reads \"The Forked Tongue\"")
choose = ["I walk towards the merry sounds.", "I turn on my heels and head back where I came from.","I stay where I am and watch the night quietly."]
outcome = [theinn(), refusal(), guards()]
def multitemplate(choose,outcome):
global mychoice
global carryon
for x in range(len(choose)):
print (f"{x+1}) " + choose[x], end="\n")
mychoice = (input())-1
while True:
if (mychoice) in range(len(choose)):
carryon = True
outcome[mychoice]
carrion()
else:
print("Please enter the number of the choice you wish to make.")
carryon = False
mychoice = int((input()))-1
I'd appreciate any input on how this should work properly, or if I'm going down a completely blind alley here.
Thanks!

How do I incorporate an if statement inside of another if statement?

I'm sort of a beginner at Python; I'm trying to write a text adventure game that prompts the user to explore a room given different options. After the user enters "1," I want the game to enter more choices through another if statement. How should I do that? And if this way is incorrect, what function should I use instead? I've tried putting another if statement in, but that leads to the program producing different results, like outputting a different part of the code instead of the one I want. Here is my code right now:
Name = input("What is your name, visitor?")
print(Name + (", you are being watched. Proceed carefully. A breeze of howling wind enters the room. Within the echo, something reaches out to you and offers a candle. Do you want to light the candle?"))
print("1 for YES")
print("2 for NO")
try:
Choice = int(input("What do you choose?"))
print("Choice:", Choice)
except ValueError:
print("Please input 1 or 2 only...")
Choice = int(input("What do you choose?"))
if Choice == 1 :
print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:")
print("1 for Table")
print("2 for Drawer")
print("3 for Lamp")
if Choice == 2 :
print("You sit in silence, wondering what to do. Without sight, you're losing options. Eventually, you muster up the courage to stand up. You can't hear your own steps. Fear climbs up your throat. The floor gives way under your feet. You are swallowed by the darkness. GAME OVER.")
quit()
if not 1:
print("Please enter either 1 or 2.")
if not 2:
print("Please enter either 1 or 2")```
There are several issues with this code, but to address your question: nest the if within the outer if:
if Choice == 1 :
print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:")
print("1 for Table")
print("2 for Drawer")
print("3 for Lamp")
Choice = int(input("What do you choose?"))
if Choice == 1:
# Do table stuff
elif Choice == 2:
# Do drawer stuff
elif Choice == 3:
# Do lamp stuff
else:
# Handle error

How do I continue a python program after a while loop exits?

I have a python3 program that guesses the last name of an individual based on the input of the user. But I figured out how to break if the user answer now, but when the user says yes it just re-enter the loop again with the same initial question.
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'no':
print("Great")
else:
time.sleep(2)
exit('Shame, thank you for playing')
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
DEMO - If the user answer 'yes'
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
etc.
So basically I want the program to exit on no, but continue on yes with the next question which is "Please tell me the first letter in your surname?"
Any idea?
I through after picking up some suggestion here, that I could use a while loop, but as the question stands, I did not get it right.
Please answer in a not so technical way, as my knowledge of python is very limited, still trying to learn.
I misunderstood the problem at first. You actually need to break the while loop when the user says Yes, so you can proceed to the 2nd question. And using an exit is fine when he says No, just remember that it will exit the whole program, so if you want to do something else after he says no, it might be better to use return and put them into functions.
Your code should be more or less like this:
import time
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
break # This will break the actual loop, so it can pass to next one.
elif answer.lower() == 'no':
# I recommend printing before so if it's running on a terminal
# it doesn't close instantly.
print('Shame, thank you for playing')
time.sleep(2)
exit()
# I suggest adding this else because users don't always write what we ask :P
else:
print('ERROR: Please insert a valid command.')
pass # this will make it loop again, until he gives a valid answer.
while True:
# code of your next question :P repeat proccess.
Feel free to ask any question you have about the code :)
As CoryKramer in the comments pointed out, use break instead of exit. Exit is a python function that exits the process as a whole and thus it shuts down the interpreter itself.
Break will close the closest loop it belongs to. Thus if you have two while loops, one written inside the other. A break will only close the inner while loop.
In general your code will go something like this
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
else:
time.sleep(2)
print("Thank you for playing!")
break
This will keep looping as long as the user keeps entering yes.
if you want to you an infinite while loop you need to control your loop state. Also i created a SurnameFunc. Using seperate functions is more readable for big projects.
def SurnameFunc():
return "Test Surname ..."
State= 0
lastname_tip = ""
while(True):
if(State== 0):
answer = input('Do you want me to guess your name? yes/no :')
if(answer == 'no') :
print ("You pressed No ! - Terminating Program ...")
break
else:
State = 1
elif(State == 1):
lastname_tip = input('Please tell me the first letter in your surname?').lower()
State = 2
elif(State == 2):
print ("Your Surname is ..." + SurnameFunc())
State = 0
print ("Program Terminated !")

Python text adventure woes

if schoice == 1:
print "You walk right up to the rat and proceed to BEAT THE SHIT OUT OF IT AHHHHHH. Ahem. Anyway, you look at your blood-covered fists and feel good about yourself. You know that you just leveled up your Unarmed to 11. BOOYA!"
skills("Unarmed") = 11
else:
"You proceed to be a little bitch and sneak past the rat. Even though you know that you are being a total coward, you feel good, and you know that you leveled up your sneak to 11. Oh Yeah!"
skills("Sneak") = 11
First off, I would like to say that I have the raw_input stuff with everything else set up, but I was just wondering if I HAVE to split off from here, and then have to write the same thing a gazillion times, or I could make both of these choices, no matter which is picked, to proceed to a shared new choice?
You don't have to split everything every time there is a choice, no.
Consider this:
print('This happens first')
choice = raw_input('Make a choice (1 or 2)')
if choice == 1:
print('Conditional event no1')
else:
print('Conditional event no2')
print('This happens after the choice, no matter what happened')
The story can go on from there. You can visualize this as a flowchart resembling this:
/------ Choice 1 -------\
Starting point / \____ Happens in either case
\ /
\------ Choice 2 -------/

Categories