Im Moment versuche ich ein kleines Spiel für meine Freunde zum Spaß zu machen in Python 3.3. Es lief alles gut, bis ich vergessen hatte, wie man bestimmte Variablen (in meinem Fall Gold, Schaden und XP) durch verschiedene Funktionen (Menü, Hügel) transportieren konnte.Wie deklariere ich globale Variablen korrekt in Python 3.3, damit sie in mehreren Funktionen arbeiten können?
Wenn jemand mir helfen könnte, diesen Code zu reparieren, damit die drei oben erwähnten Variablen zwischen meinen Funktionen unverändert übertragen werden können, wäre das erstaunlich. Hier ist mein Code.
import os
import random
import time
def Menu():
global damage
global xp
global gold
damage = 1
xp = 0
gold = 0
print("\nyour attack value is", damage,"\nyour xp level is", xp,"\nand you have", gold,"gold.\n")
sword = input("Old Joe Smith: Do you need a sword? ")
sword = sword.lower()
if sword == "yes":
damage = damage + 9
print("Old Joe Smith: *Gives you a sharp steel sword* Good luck on your travels!\n\nYour new attack value is",damage,"\n")
time.sleep(2)
Hills()
if sword == "yeah":
damage = damage + 9
print("Old Joe Smith: *Gives you a sharp steel sword* Good luck on your travels!\n\nYour new attack value is",damage,"\n")
time.sleep(2)
Hills()
elif sword == "no":
print("Old Joe Smith: Well, if you say so... ...good luck anyway!\n")
Hills()
else:
print("Old Joe Smith: I'm sorry, what?")
time.sleep(1)
Menu()
def Hills():
print("*You walk through the forest, when out of nowhere a minotaur appears!*")
fight = input("What will you do, run or fight? ")
fight = fight.lower()
if fight == "run":
print("You escape, barely.")
Cave()
if fight == "fight":
input("Press enter")
if damage > 5:
print("You win! you looted 10 gold and got 5 xp.")
gold = gold + 10
xp = xp + 5
Cave()
elif damage < 5:
print("You died. Game over.")
Menu()
else:
print("How the hell did you get exactly 5 damage?")
Menu()
else:
print("Your lack of a proper response makes the minotaur charge. It kills you instantly.")
Menu()
def Cave():
print("You stumble into a cave. there are two routes in the cave. which way do you want to go, left or right?")
print("Welcome to 'RPG Game', a role-playing game developed in Python 3.3.\nThis game was developed by bamf_mccree.\n")
print("Old Joe Smith: Hello, adventurer, and welcome to Dankhill, in the centre of Whitewood forest. \nThis was once a peaceful place, but the evil Lord Draktha has enslaved most of the civilians of our realm.")
time.sleep(4)
Menu()
Ich denke, das wurde bereits ein paar Mal beantwortet. Versuchen Sie diese Antwort: http://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – Ramalus
Ich weiß nicht, wie das auf meine Funktionen übertragen werden. –