Reputation: 822
I was creating a text-based adventure game for practice with Python and here is my code.
#game.py
import time
import encounter
#Hp at start of game
hp = 100
#Function to display the current hp of the current player
def currenthp(hp):
if hp < 100:
print "Your hp is now at %d" % hp
elif hp <= 0:
dead()
else:
print "You are still healthy, good job!"
print "You start your regular trail."
print "It will be just a little different this time though ;)"
#Start of game
time.sleep(3)
print "You are walking along when suddenly."
time.sleep(1)
print "..."
time.sleep(2)
#Start of first encounter
print "Wild bear appears!."
print "What do you do?"
print "Stand your ground, Run away, be agressive in an attempt to scare the bear"
#first encounter
encounter.bear(hp)
I put all of my encounters in a separate script for neatness. This is the encounter script.
import time
#Bear encounter
def bear(hp):
import game
choice = raw_input("> ")
if "stand" in choice:
print "The bear walks off, and you continue on your way"
elif "run" in choice:
print "..."
time.sleep(2)
print "The bear chases you and your face gets mauled."
print "You barely make it out alive, however you have sustained serious damage"
hp = hp-60
game.currenthp(hp)
elif "agressive" in choice:
print "..."
time.sleep(2)
print "The bear sees you as a threat and attacks you."
print "The bear nearly kills you and you are almost dead"
hp = hp-90
game.currenthp(hp)
else:
print "Well do something!"
Well this all works handy-dandy, except for one thing. When my program gets to the part where it asks for an answer for what the player would like to do in response to the bear in the encounter script, the whole game script restarts. However, this time, the program will work normally. Is there a reason for this or will I just have to deal with it?
Upvotes: 3
Views: 4879
Reputation: 6606
Your code has circular dependencies: game
imports encounter
and encounter
imports game
. You also have a lot of logic in the module scope in game
; module level logic is evaluated the first time a module is imported -- however, a module isn't finished importing until all its code is evaluated, so if you end up importing the module again in the course of its module definition code, weird things happen.
Firstly, don't have module level code -- use if __name__ == "__main__":
blocks. This means your code won't run on import, only on direct execution.
See What does if __name__ == "__main__":
do?
Secondly, don't have circular imports -- if you need to share logic and can't justify keeping it in the imported module, create a third module imported by both. Here though, it looks like you can just move current_hp
to encounter
and remove the import game
from encounter
.
Upvotes: 5