constantly checking if a condition is true or false - python

I'm new to python and programming in general and I am currently taking a course on Udemy. One of the projects is to create a pick your own adventure game. I've been doing pretty
well until I came across something that has been picking at me. I wanted to display text depending on whether or not you have died by changing the condition of death from False to True. I know I can just add you died after the if/else statement with a print function but I wanted to make it a bit more challenging. Here's an example.
death = False
if death == True:
print("\nYou died")
choice_1 = input("left or right:\n")
if choice_1 == "left":
death = False
print("*The next piece of dialogue*")
else:
death = True
print("*The next piece of dialogue*")
It would then print "you died" after the next piece of dialogue if the death changed to True.

If all you're looking to do is constantly run the choices until death = True you just need to use a while loop before your if statements. This will constantly run the input until the value of death changes to True.
def player_died()
print('Do whatever you want to happen when player dies in this function')
death = False
while death == False:
choice_1 = input("left or right:\n")
if choice_1 == 'left':
death = False
print("*The next piece of dialogue*")
elif choice_1 == 'right':
death = True
print("\nYou died")
#This will break the while loop
player_died()
Whatever additional things you wish to do after death = True, I would make a new function for that situation like def player_died(), and call that function under the 'You died' print. The while loop will end, and you will go to the next function.
If you wish to return back to that loop, AFTER you do something else, then change player_died() call to death = player_died() - and have the function return False, and remove the death=True above it.
This will allow you to execute whatever additional actions you want to do in the function, and when all of that is complete it will return back to the while loop and start over.

Related

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 to ONLY pause an IF statement, not the entire code Python

So I have a game that requires the player to become immune to damage for 1 second, otherwise, the code wold instantly kills the player. The way I'm doing it is by checking if the enemy and player are colliding in an IF statement and then taking 1 away from health. The issue is that if I use the "pause" feature my entire code freezes for 2 seconds, I only need this single IF loop to freeze.
Thankyou Alex!
Like user1558604 said, you should make a boolean called is_immune set to false. When you take damage, set it to true, and set it to false after one second, and before removing health from the player, checking if the player is immune or not.
is_immune = False
if player_is_hit:
if not is_immune:
player_health -= 1 # Remove 1 from health
is_immune = True
# Wait one second
is_immune = False

Python programming: input variable is returning name error

So I have written this code for this game, using a user input, but it does not seem to be working. This is my code.
import random
print ("Welcome to the hungry dog game.")
print ("The aim of this game is to save the hungry dog. How long can you keep it alive for?")
true = True
false = False
aliveordeadlist1 = [true, false]
random.choice(aliveordeadlist1)
feed1 = input("Ok so here's your first choice. Are you going to feed your dog now or not?(he doesn't look very hungry...) type in yes or no.")
if feed1 == "no" and aliveordeadlist1 == false:
print ("Well you were wrong, he was hungry. Your dog died sorry. Better luck next time.")
if feed1 == "yes" and aliveordeadlist1 == false:
print ("As I told you he wansn't hungry> You overfed him so hed died sorry. Better luck next time.");
if feed1 == "no" and aliveordeadlist1 == true:
print ("Well done he wasn't hungry. He is still alive (for now...)");
if feed1 == "yes" and aliveordeadlist1 == true:
print ("Well done he actually was hungry so he would have died if you didn't feed him.He is still alive (for now...)");
When I run this code in the shell and for example, type yes, it returns this error:
Traceback (most recent call last):
File "/Users/mac/Documents/hungrydoggame.py", line 16, in <module>
feed1 = input("Ok so here's your first choice. Are you going to feed your dog now or not?(he doesn't look very hungry...) type in yes or no.")
File "<string>", line 1, in <module>
NameError: name 'yes' is not defined
I am unsure why I am receiving this error and what I should do to fix it, does anyone have any suggestions?
First of all if you're doing python2.7 program as mentioned here the input method should be used as input_raw so it will return you the response as string and in line7 you do a random choice for if the dog is dead or alive but never save it in the variable in which you will be chekcing aliveordead = random.choice(aliveordeadlist1). So here's the proper code.
import random
print ("Welcome to the hungry dog game.")
print ("The aim of this game is to save the hungry dog. How long can you keep it alive for?")
true = True
false = False
aliveordeadlist1 = [true, false]
aliveordead = random.choice(aliveordeadlist1)
feed1 = raw_input("Ok so here's your first choice. Are you going to feed your dog now or not?(he doesn't look very hungry...) type in yes or no.")
if feed1 == "no" and aliveordead == false:
print ("Well you were wrong, he was hungry. Your dog died sorry. Better luck next time.")
if feed1 == "yes" and aliveordead == false:
print ("As I told you he wansn't hungry> You overfed him so hed died sorry. Better luck next time.");
if feed1 == "no" and aliveordead == true:
print ("Well done he wasn't hungry. He is still alive (for now...)");
if feed1 == "yes" and aliveordead == true:
print ("Well done he actually was hungry so he would have died if you didn't feed him.He is still alive (for now...)");
I don't get the error that you get, but you need to set the random.choice call to a variable, and then reference that in your if statements (and not aliveordeadlist1), otherwise you're comparing your list to the single word 'yes' or 'no' and that will always return False.
This code has some serious issues which I imagine may lead to unexpected behaviour in some versions of Python:
Indentation is relevant in Python. If you really have indented all the code after the first line I don't even understand why your code runs at all.
You define aliases for True and False. This may not be a problem, but I don't know whether true and false are reserved words.
There is also a logical issue:
You are not saving the random.choice return value anywhere. You are effectively checking whether [True, False] == True (and == False).
Other possible issues:
You haven't specified which interpreter of Python you are using. print is a function in Python 2, but not in Python 2. I know both assert(whatever) and assert whatever work in at least some versions of Python 2, but I'm not sure about print().
Semicolons are not used to separate statements in Python, newline is.

Trying to return a True variable from a nested chain of functions (in Python)...

I'm trying to write part of an adventure game program in Python, and though I have most of it down, I'm stuck at trying to return a value declared as "True" at the end of one branch in the function chain. Basically, this is a fight against a monster, which you can win if you choose the right options. If you win, you obtain the bow that he was guarding. Here is the code of the fight:
#The first line imports all the text displayed in the game, saved in gametext.py
#For purposes of clarity, all text has been saved to variables imported by the file.
#Any variable that is not "HaveBow", "why" or declared by a raw_input() is actually text.
from gametext import *
def BG_fight():
print BowGuardIntro
print InitOptions
BGfirstmove = raw_input('> ')
if BGfirstmove == "1":
spearfight()
elif BGfirstmove == "2":
dead(BGUnarmed1)
else:
dead(BGUnarmed2)
def spearfight():
print GotSpear
print SpearFight
spearact = raw_input("> ")
if spearact == "1":
blindfight()
elif spearact == "2":
dead(SeeChest)
elif spearact == "3":
dead(SeeArms)
else:
dead(NoUseSpear)
def blindfight():
print BlindFight
followblow = raw_input("> ")
if followblow == "1":
print Victory
HaveBow = True
return HaveBow
elif followblow == "2":
dead(BlindArms)
else:
dead(BlindNoKill)
def dead(why):
print why
exit(0)
BG_fight()
(If people are interested, I can also produce the contents of the gametext file, though I would rather not as it is lengthy and has nothing to do with the problem I'm having)
As you can see, only one branch there offers the winning condition (which would give the HaveBow = True value that I want to return), and it is nested two functions deep and part of an if-statement. What I want to know is how I return that "HaveBow = True" value back outside the function chain, so it can be used in other parts of the game? If I try to code:
HaveBow = blindfight()
print HaveBow
at the end of the code and try to run it, it just makes me repeat that part of the game twice, before declaring "True". Same goes if I try BG_fight() instead of blindfight(). But I don't want that; I just want the "True" for "HaveBow" so I can use the condition "HaveBow = True" in other parts of the game.
In short, my question is whether or not it's possible to return a value from a nested function chain without repeating the code of that chain, and if so, how?
Thanks.
You can only return a value, not a name and a value. In other words, you cannot "return HaveBow = True"; all you can do is return True. There's no way to return a value and at the same time assign it to a variable that exists outside the function. If you want to assign the value, you need to do it outside the function.
From what you say, it sounds like you want HaveBow to be a global variable that you can use anywhere in your program. In that case, you can change your code in blindfight to do:
if followblow == "1":
global HaveBow
print Victory
HaveBow = True
Note that in this case you do not need to return the True value -- you just directly assign it to a global variable.
Ultimately there are better ways to structure your code, but those issues are out of the scope of this question. For the moment, I would suggest that, if you have global state like HaveBow that you want to be able to use "anywhere else in the game", you should make those global variables using global as I showed in my example. As you progress learning more programming, you will gradually learn why using global variables is not usually the best idea, but for the purposes of this program it is the simplest solution.

Poker game in Python, making the turns

I'm writing a poker game and I'm having trouble creating a function for turns where one player can raise, then another player call then raise again, followed by another (etc). I'm not sure how to organize this. I have this so far:
def turn(playerBank,label):
#playerBank is just the player's balance (whoever's turn it is) and label is just tkinter text.
win.getMouse()
action = ent.getText()
if action == 'check':
pass
elif action == 'call':
playerBank = playerBank - cashMoney
pool = pool + cashMoney
elif action == 'raise':
cashMoney = cash.getText()
playerBank = playerBank - cashMoney
pool = pool + cashMoney
elif action == 'fold':
break
How would i make it two turns (one per player) but then, if a player raises, allow it to loop AGAIN so that the other player has the option to call or fold... etc.?
The first thing that comes to mind is to use booleans. Make a function that checks if the turn is completely over and make another boolean to check whether a player has raised or not.
Boolean playerRaise would be false until a player raises, and turns true only when all the players have responded to the raise. You can check that by using the number of players and measuring how many responses there were. This resets every time a player raises.
Function checkTurn would just check if playerRaise has become false because if its false then we know for sure the turn has been finished.
I'm just thinking out loud here, but it seems to be a plausible solution, what do you think?

Categories