This is really a twofold question, since I know there are two errors with the same couple blocks of code.
I'm essentially making an interactive story that changes based on "rolling a d20." For instance, the player is presented with a scenario, and prompted to roll a d20. The computer generates a number between 1 and 20, and, depending on the roll, the story will pan out a certain way. The roadblock I'm having is that I've defined a function, "RollD20()," that stores the value of variable "n" as a random integer between 1 and 20 and then prints the value rolled. When I call the function, it crashes with an error saying "n is not defined."
The other part to this question, in the same block of code, is that I'm trying to get to a point where the game will ask the user essentially, do you want to play? and if the answer constitutes a yes, then the rest of it plays out. If not, the process ends. But thus far, regardless of what key I press, y or yes, n or no, or even enter, it doesn't end the process like it's supposed to, it just moves forward. Is there an easy way to fix this?
Thanks, and the code is below.
import sys
import random
while True:
def NewGame():
print(input("Hello! Would you like to go on an adventure? y/n >> "))
if input == "y" or "yes":
print("Great! Roll the dice.")
print(input("Press R to roll the D20."))
print("You rolled a " + RollD20(n) + "!")
else:
print(input("Okay, bye! Press any key to exit."))
sys.exit()
def RollD20():
n = random.randint(1, 20)
print(n)
NewGame()
Traceback (most recent call last):
\venv\main.py", line 22, in <module>
NewGame()
\venv\main.py", line 11, in NewGame
print("You rolled a " + RollD20(n) + "!")
NameError: name 'n' is not defined
Process finished with exit code 1
Aucun commentaire:
Enregistrer un commentaire