Why does my module run twice in Python -
i creating text-based adventure game practice python , here code.
#game.py import time import encounter #hp @ start of game hp = 100 #function display current hp of current player def currenthp(hp): if hp < 100: print "your hp @ %d" % hp elif hp <= 0: dead() else: print "you still healthy, job!" print "you start regular trail." print "it little different time though ;)" #start of game time.sleep(3) print "you walking along when suddenly." time.sleep(1) print "..." time.sleep(2) #start of first encounter print "wild bear appears!." print "what do?" print "stand ground, run away, agressive in attempt scare bear" #first encounter encounter.bear(hp) i put of encounters in separate script neatness. encounter script.
import time #bear encounter def bear(hp): import game choice = raw_input("> ") if "stand" in choice: print "the bear walks off, , continue on way" elif "run" in choice: print "..." time.sleep(2) print "the bear chases , face gets mauled." print "you barely make out alive, have sustained serious damage" hp = hp-60 game.currenthp(hp) elif "agressive" in choice: print "..." time.sleep(2) print "the bear sees threat , attacks you." print "the bear kills , dead" hp = hp-90 game.currenthp(hp) else: print "well something!" well works handy-dandy, except 1 thing. when program gets part asks answer player in response bear in encounter script, whole game script restarts. however, time, program work normally. there reason or have deal it?
your code has circular dependencies: game imports encounter , encounter imports game. have lot of logic in module scope in game; module level logic evaluated first time module imported -- however, module isn't finished importing until code evaluated, if end importing module again in course of module definition code, weird things happen.
firstly, don't have module level code -- use if __name__ == "__main__": blocks. means code won't run on import, when want to.
see what if __name__ == "__main__": do?
secondly, don't have circular imports -- if need share logic , can't justify keeping in imported module, create third module imported both. here though, looks can move current_hp encounter , remove import game encounter.
Comments
Post a Comment