Ask coding questions

← Back to all posts
Help! How do you add lives in code!
kirbyfire (1)

Right now, I am starting to work on a project, (no animations, all just text), Can someone tell me how I can make a life system so If you get an incorrect answer, you lose a life? This is in Python. Thanks!

Answered by ebest (590) [earned 5 cycles]
View Answer
Commentshotnewtop
mwilki7 (520)

Just stick it in a variable and check for correct answer:
Fill in "correct option" with whatever condition you think is the correct option

player_health = 5
...
...
y = input("....A) Good option B) Bad option C) Bad Option")
if y=="a":
    # good option!
    # do other stuff here I guess
else:
    # bad option!
    # decrease health by 1
    player_health = player_health - 1

if player_health == 0:
    # game over, health zero!
else:
    # still alive
kirbyfire (1)

@mwilki7 THANK YOU SO MUCH YOU ARE A GOD AND A LIFESAVER!!!!!!!!

ebest (590)

@mwilki7 Change that to (little change)

import sys
player_health = 5
...
...
y = input("....A) Good option B) Bad option C) Bad Option")
if y=="a":
    # good option!
    # do other stuff here I guess
    pass
else:
    # bad option!
    # decrease health by 1
    player_health -= 1

if player_health == 0:
    #Game over, health zero!
    print("Game over!")
    sys.exit()
else:
    # still alive
    pass
ebest (590)

Also, you really should add better option detection, like if a option is not valid, you say so.

And maybe you should add dictionaries. I used to love to do text adventures, then I realized dictionaries were simple combined with arrays.

kirbyfire (1)

@ebest, Also, how do you keep the lives consistent so that it doesn't always give you 3 lives at the beginning of a puzzle?

kirbyfire (1)

@ebest I tested it out, but if I get a wrong answer, (but then get one correct and move on) and then do the same thing again, Then instead of having only one life, I have 2. How do I fix this? (If you can't understand my question, try getting one wrong and then correct twice in a row, then get it wrong. Instead of ending it it gives another chance.)

kirbyfire (1)

@ebest and also, how do you give multiple correct answers that lead to different paths? I tried using the or function but it didn't work!

ebest (590)

@kirbyfire

if a in ["a", "A"]:
    pass

Also:
USE

player_health -= 1
ebest (590)

@kirbyfire What programming languages have you learned before?

kirbyfire (1)

@ebest A bit of Java, and Python

ebest (590)

@kirbyfire you can reset the input every time. Change it.