I'm currently working on a choose your own adventure game in python and I'm trying to set up a timer that after every 3-4 seconds your oxygen points deplete by 3, I will post the entire code for the game I would like help with which method of timer for it and where to put the timer. thank you for taking the time out of your day to help me
__Author__ = 'Mangle200/Tristan Lauzon'
import tkinter
from time import *
from random import *
import os,sys
def clear_screen():
os.system('cls' if os.name=='nt' else 'clear')
def title():
print("___ ___ \n| \/ | \n| . . | ___ ___ _ __ \n| |\/| |/ _ \ / _ \| '_ \ \n| | | | (_) | (_) | | | | \n\_| |_/\___/ \___/|_| |_| \n \n \n _ _ _ \n| | | (_) \n| | __ _ _ __ __| |_ _ __ __ _ \n| | / _` | '_ \ / _` | | '_ \ / _` | \n| |___| (_| | | | | (_| | | | | | (_| | \n\_____/\__,_|_| |_|\__,_|_|_| |_|\__, | \n __/ | \n |___/ \n _____ _ _ _ _ \n| ___| | (_) | (_) \n| |____ ___ __ ___ __| |_| |_ _ ___ _ __ \n| __\ \/ / '_ \ / _ \/ _` | | __| |/ _ \| '_ \ \n| |___> <| |_) | __/ (_| | | |_| | (_) | | | |\n\____/_/\_\ .__/ \___|\__,_|_|\__|_|\___/|_| |_|\n | | \n |_| \n")
def setup():
global name
global HP
global SP
global OP
while True:
name = input('What is your name ---> ')
isnum = False
for i in name:
if i.isnumeric():
isnum = True
break
if isnum:
print('Please type your name. ')
continue
break
HP = randint(17,20)
SP = randint(17,20)
OP = randint(90,100)
print('welcome ['+name+':]: to the moon landing expedition')
def villager():
global npcname
global response
responses = ['hello', 'who are you?', 'why are you here?', 'what are your intentions?']
npcnamechoice = ['Sarah', 'Bobby', 'Chris', 'Trent', 'Susan', 'Michelle', 'Mara']
shuffle(npcnamechoice)
print('\n['+npcname+':]Hello my name is'+npcname+'would you like to talk to me?\n')
shuffle(responses)
print('press y to talk to the villager')
if input().upper== 'Y':
print('['+npcname+':] '+responses[0])
else:
print('['+npcname+':] Goodbye')
def enemy():
global enemyHP
global enemyMP
global enemyname
enemyHP = randint(5,20)
enemyMP = randint(5,20)
enemyname = ['Space ogre', 'Space witch', 'Space bandit', 'Rick Astley in Space', 'Emminem In space']
shuffle(enemyname)
print('\nSuddenly you hear somthing in the woods and a'+enemyname[0]+'appears')
print('your enemy has'+' '+ str(enemyHP)+' '+'Health points')
print('your enemy has'+' '+ str(enemyMP)+' '+'magic points')
def north():
global gonorth
gonorth = 'you have decided to head north'
def east():
global goeast
goeast='you have decided to go east'
def west():
global gowest
gowest = 'you have decided to go west'
clear_screen()
title()
setup()
print('hello this game is created by ',__Author__)
print('your health is at ', HP, 'your stamina points are at', SP, 'your Oxygen levels at the start of Chapter one wil be ', OP)
print('<suspencful music activates>, Robotic voice:"hello and welcome to the',)
title()
input('press enter to continue')
print('you have been choosen out of fifty-million canidates for this once in a lifetime adventure your mission...\nis reconasance of planets near and far, my superiors have trust in you\nplease do your be..."<electrical static cuts out the automated voice>\n<emergency sirens are sounded>\nMan on Intercoms:"this is not a drill i repeat this is not a drill everyone you must evacuate imediat..."')
print('<the sound of gunshots can be heard all around you> *in mind:even though i fear for my life, i feel like aslong as i stay put i am safe*<a loud buzzer is heard>\nAutomated voice:"Initiating emergancy launch in T-minus ten')
print('nine')
print('eight')
print('seven')
print('six')
print('five')
print('four')
print('t-h-r-e-e-e-e-e')
print('t-t-t-t-w-o-o-o')
print('o-o-o-o-n-n-n-e-e')
print('i-i-i-g-n-i-i-i-s-i-o-n"')
print('<the sound of rocket thrusters are all you are able to hear as you watch the ground getting fartehr way>')
print('\n\n\n\n\n\n\n<five years have passed since the attack on the military space center>\n<your space craft has almost completly run out of fuel>\n<you are forced to make an emergancy landing on one of the moons of the planet nexus>')
input('press enter to start the first chapter of the game')
print(" _____ _ _ \n/ __ \ | | | \n| / \/ |__ __ _ _ __ | |_ ___ _ __ \n| | | '_ \ / _` | '_ \| __/ _ \ '__|\n| \__/\ | | | (_| | |_) | || __/ | \n \____/_| |_|\__,_| .__/ \__\___|_| \n | | \n |_| \n _____ \n| _ | \n| | | |_ __ ___ \n| | | | '_ \ / _ \ \n\ \_/ / | | | __/ \n \___/|_| |_|\___| \n \n \n _____ _ _ _ \n/ ___(_) | | | | \n\ `--. ___ _| |_| |__ \n `--. \ \ \/ / __| '_ \ \n/\__/ / |> <| |_| | | | \n\____/|_/_/\_\\__|_| |_| \n \n \n___ ___ \n| \/ | \n| . . | ___ ___ _ __ \n| |\/| |/ _ \ / _ \| '_ \ \n| | | | (_) | (_) | | | | \n\_| |_/\___/ \___/|_| |_| \n \n \n _____ __ \n| _ |/ _| \n| | | | |_ \n| | | | _| \n\ \_/ / | \n \___/|_| \n \n \n _ _ \n| \ | | \n| \| | _____ ___ _ ___ \n| . ` |/ _ \ \/ / | | / __| \n| |\ | __/> <| |_| \__ \ \n\_| \_/\___/_/\_\\__,_|___/ \n \n ")
input('press enter to continue')
print(name+']:"Ok so i am here on one of the moons on an unknown planet with absolutly no way of contacting for help i have no fuel and my power reserves are failing,\n soon i will have no oxygen left,\n fortunatly there are solar panels on the side of the rocket so once the sun hits the panels the oxygen production systems will kick in,\ni just hope i can survive long enough for a search party comes to find me."')
print('the sixth moon of nexus is the biggest source of metal in the universe, (dont wory about oxygen for the time being ')
I would consolidate all input together and do it there. Essentially, after every action, print the stats along with the input.
Separately, this would work better as a class. That way you can share data without using globals.
If you want to get really fancy, you can use a status bar and progress bars for player levels from Enlighten.
Edit: Here is a possible implementation using classes. Here oxygen is a property, so it is calculated every time it is called. You may want to delay setting the start time for oxygen until the intro is done, or pad that number by adding 5 - 10 seconds. It's also rounding to an int, but you may want to use a float so you can have 3.6 vs rounding to 4.
You may also want to divide this up and make seperate classes for the main player, villagers, enemies, etc.
__Author__ = 'Mangle200/Tristan Lauzon'
import os
import random
import time
class MoonLandingExpedition:
def __init__(self):
self.health = 0
self.stamina = 0
self._oxygen_start = (0, 0.0)
self.name = None
self.direction = None
#property
def oxygen(self):
oxygen_per_sec = 0.33
initial_level, initial_time = self._oxygen_start
time_delta = time.time() - initial_time
current_level = max(0, initial_level - time_delta * oxygen_per_sec)
return round(current_level)
def clear_screen(self):
os.system('cls' if os.name == 'nt' else 'clear')
def encounter_enemy(self):
e_name = random.choice(('Space ogre', 'Space witch', 'Space bandit',
'Rick Astley in Space', 'Emminem In space'))
e_health = random.randint(5, 20)
e_magic = random.randint(5, 20)
print('\nSuddenly you hear somthing in the woods and a {e_name} appears')
print('your enemy has {e_health} Health points')
print('your enemy has {e_magic} magic points')
def encounter_villager(self):
v_name = random.choice(('Sarah', 'Bobby', 'Chris', 'Trent', 'Susan', 'Michelle', 'Mara'))
responses = ('Hello!', 'Who are you?', 'Why are you here?', 'What are your intentions?')
print(f'\n[{v_name}:] Hello my name is {v_name} would you like to talk to me?\n')
if self.get_input('Press y to talk to the villager').upper == 'Y':
print(f'[{v_name}:] {random.choice(responses)}')
else:
print(f'[{v_name}:] Goodbye')
def get_name(self):
while True:
name = input('What is your name? ---> ')
if any(char.isdigit() for char in name):
print('Please type your name. ')
else:
break
return name
def get_input(self, message):
self.print_status()
return input(message)
def intro(self):
print("You have been chosen...")
print("Moon of Nexus")
self.get_input('press enter to continue')
def print_status(self):
print(f'Health: {self.health} Stamina: {self.stamina} Oxygen: {self.oxygen}')
def run(self):
self.clear_screen()
self.title()
self.setup()
print('hello this game is created by ',__Author__)
self.print_status()
print('<suspenseful music activates>, Robotic voice:"hello and welcome to the',)
self.title()
input('press enter to continue')
self.intro()
def setup(self):
self.health = random.randint(17, 20)
self.stamina = random.randint(17, 20)
self._oxygen_start = (random.randint(17, 20), time.time())
self.name = self.get_name()
print(f'Welcome [{self.name}:]: to the moon landing expedition')
def title(self):
print("Moon Landing Expedition")
if __name__ == "__main__":
game = MoonLandingExpedition()
game.run()
Related
import random
print("""
___ ___ _ ___ ____ _
| \/ | | | | \/ (_) | |
| . . | __ _ ___| |_ ___ _ __| . . |_ _ __ __| |
| |\/| |/ _` / __| __/ _ \ '__| |\/| | | '_ \ / _` |
| | | | (_| \__ \ || __/ | | | | | | | | | (_| |
\_| |_/\__,_|___/\__\___|_| \_| |_/_|_| |_|\__,_|
""")
meno = input("""
Ahoj nový hráč.
Pre pokračovanie zadaj svoje meno: """)
print("""
Ahoj {}
Pravidlá sú následovné. ja si myslím číslo a ty budeš hádať.
Ak chceš ukončiť hru, napíš 'KONIEC'.
Na konci hry uvidíš svoje skóre.""".format(meno))
print("\nMyslím si číslo")
random = random.randint(1,11)
guess = -1
good = 0
bad = 0
alltry = 0
while True:
guess = input("Tvoj typ: ").strip().lower()
alltry += 1
if guess == "koniec":
alltry -= 1
print("\n+{:=^30}+".format("KONIEC"))
print("|{:^15}|{:^14}|".format("Správne", good))
print("|{:^15}|{:^14}|".format("Nesprávne", bad))
print("|{:^15}|{:^14}|".format("Spolu", alltry))
print("+{:=^30}+".format(""))
print("\nĎakujem za hru {}\n".format(meno))
break
if guess == "":
print("NEZADAL SI CISLO!")
elif int(guess) == random:
good += 1
print("Máš to!!!")
random = random.randint(1,11)
guess = -1
elif int(guess) < 1 or int(guess) > 10:
print("ZADÁVAJ ČÍSLA IBA Z INTERVALU OD 1 PO 10!")
elif guess != random:
print("NESPRÁVNE!\nHádaj znovu.")
guess = -1
bad += 1
Hi I have problem with this code. It is game MasterMind. If guess number, program return problem.
Traceback (most recent call last): File "mastermind.py", line 47, in <module> random = random.randint(1,11). AttributeError: 'int' object has no attribute 'randint'
Thanks for all help.
random = random.randint(1,11)
This statement rebinds the random name, which currently refers to the imported module (it was set when you did import random), to an integer returned from randint(). The next time you execute this statement, random will no longer be the module, it will be an integer.
That's why it's complaining about trying to access a non-existent attribute of an int object.
The following transcript shows what's happening:
>>> import random
>>> type(random)
<class 'module'>
>>> random = random.randint(1,7)
>>> type(random)
<class 'int'>
>>> random = random.randint(1,7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'randint'
To fix, simply use a different name for the random value, such as randNum, so that random continues to be bound to the module.
You can not use random as a variable name since that is a module you are using, simply change the variable name and it should fix the issue.
Here I changed it to random_int instead and it works just fine.
import random
print("""
___ ___ _ ___ ____ _
| \/ | | | | \/ (_) | |
| . . | __ _ ___| |_ ___ _ __| . . |_ _ __ __| |
| |\/| |/ _` / __| __/ _ \ '__| |\/| | | '_ \ / _` |
| | | | (_| \__ \ || __/ | | | | | | | | | (_| |
\_| |_/\__,_|___/\__\___|_| \_| |_/_|_| |_|\__,_|
""")
meno = input("""
Ahoj nový hráč.
Pre pokračovanie zadaj svoje meno: """)
print("""
Ahoj {}
Pravidlá sú následovné. ja si myslím číslo a ty budeš hádať.
Ak chceš ukončiť hru, napíš 'KONIEC'.
Na konci hry uvidíš svoje skóre.""".format(meno))
print("\nMyslím si číslo")
random_int = random.randint(1,11)
guess = -1
good = 0
bad = 0
alltry = 0
while True:
guess = input("Tvoj typ: ").strip().lower()
alltry += 1
if guess == "koniec":
alltry -= 1
print("\n+{:=^30}+".format("KONIEC"))
print("|{:^15}|{:^14}|".format("Správne", good))
print("|{:^15}|{:^14}|".format("Nesprávne", bad))
print("|{:^15}|{:^14}|".format("Spolu", alltry))
print("+{:=^30}+".format(""))
print("\nĎakujem za hru {}\n".format(meno))
break
if guess == "":
print("NEZADAL SI CISLO!")
elif int(guess) == random_int:
good += 1
print("Máš to!!!")
random_int = random.randint(1,11)
guess = -1
elif int(guess) < 1 or int(guess) > 10:
print("ZADÁVAJ ČÍSLA IBA Z INTERVALU OD 1 PO 10!")
elif guess != random_int:
print("NESPRÁVNE!\nHádaj znovu.")
guess = -1
bad += 1
I'm working on a small dictionary hash cracker.
I know I need multiprocessing, but I'm just testing it as of now.
My problem is not that I get an error; its that passwords (or keywords) in my dictionary file are not hashed correctly.
import hashlib
print(" _ _ _ ")
print("| | | | | | ")
print("| |__ __ _ ___| |__ ___ _ __ __ _ ___| | _____ _ __ ")
print("| '_ \ / _` / __| '_ \ / __| '__/ _` |/ __| |/ / _ \ '__|")
print("| | | | (_| \__ \ | | | | (__| | | (_| | (__| < __/ | ")
print("|_| |_|\__,_|___/_| |_| \___|_| \__,_|\___|_|\_\___|_| ")
print("")
print("Made By IronKey | python 3.7 ")
hashed = input("ENTER YOUR PASSWORD TO RECOVER: ")
wordlist = input("enter your dictionary: ")
print("")
with open(wordlist) as passList:
for i in passList:
hash1 = hashlib.md5(i.encode())
hash1.hexdigest()
print(hash1.hexdigest())
if str(hash1.hexdigest()) == str(hashed):
print("password is cracked: " + i)
break
print("")
input("press enter to leave")
example input: b81e70651fb13d7d7051cc1684c0f91e (the hash for Password234)
example output (if Passowrd234 is in the dictionary file): password is cracked: Password234
actual output: hash for Password234 is completely different and it returns its comparison as wrong!
I am having an issue with a Text Based Game I am making for my AP Computer Science principals project. What's supposed to happen is this line of code:
def pI(options):
#PI stands for Player Input
playerInput = (input("==> "))
if playerInput not in options or commands:
print(playerInput + " is not a possible option")
print("Do /options for a list of acceptable options")
playerInput = (input("==> "))
if playerInput == "/commands":
print(commands)
elif playerInput == "/options":
print("Acceptable inouts are" + options)
elif playerInput == "/help":
gHelp()
return(playerInput)
is supposed to check if the player's input is one that can be done. However, with this system, the interpreter does not even check the playerInput. I don't get any errors, but it's not working the way i want it to. The logic makes sense to me, but not the interpreter. Does anyone know why this is? Here is the rest of my code so far for the game if that helps:
#Made by -----------------------------------------------------------#
import sys
import os
import time
import random
os.system("mode con: cols=45 lines=80")
#Commands-----------------------------------------------------------#
commands = ["/options, /Help"]
#Functions----------------------------------------------------------#
def save():
print("This is supposed to save, but it doesn't work yet")
def clear():
os.system('cls')
def back():
pCS
def pI(options):
#PI stands for Player Input
playerInput = (input("==> "))
if playerInput not in options or commands:
print(playerInput + " is not a possible option")
print("Do /options for a list of acceptable options")
playerInput = (input("==> "))
if playerInput == "/commands":
print(commands)
elif playerInput == "/options":
print("Acceptable inouts are" + options)
elif playerInput == "/help":
gHelp()
return(playerInput)
#Graphics-----------------------------------------------------------#
#All Graphic functions start with "g" so that i don't take any
#names I might need later
def gLine():
#Function Draws lines
ps2("******************************************************************************************************************")
def gHeader():
gLine()
ps2("""
___________.__ __ __ __ .__ _____ __________ .__
\__ ___/| |__ ____ / \ / \___________ _/ |_| |__ _____/ ____\ \____ /____ | | ____ ____
| | | | \_/ __ \ \ \/\/ |_ __ \__ \\ __\ | \ / _ \ __\ / /\__ \ | | / ___\ / _ \
| | | Y \ ___/ \ / | | \// __ \| | | Y \ ( <_> ) | / /_ / __ \| |_/ /_/ > <_> )
|____| |___| /\___ > \__/\ / |__| (____ /__| |___| / \____/|__| /_______ (____ /____|___ / \____/
\/ \/ \/ \/ \/ \/ \/ /_____/ """)
gLine()
def gExit():
clear()
save()
gLine()
ps2("""
___________ .__ __ .__
\_ _____/__ __|__|/ |_|__| ____ ____
| __)_\ \/ / \ __\ |/ \ / ___\
| \> <| || | | | | \/ /_/ >
/_______ /__/\_ \__||__| |__|___| /\___ / /\ /\ /\ /\ /\ /\ /\
\/ \/ \//_____/ \/ \/ \/ \/ \/ \/ \/""")
gLine()
sys.exit
def gHelp():
clear()
gLine()
p2("""
___ ___ .__ _____
/ | \ ____ | | ______ / \ ____ ____ __ __
/ ~ \/ __ \| | \____ \ / \ / \_/ __ \ / \| | \
\ Y | ___/| |_| |_> > / Y \ ___/| | \ | /
\___|_ / \___ >____/ __/ \____|__ /\___ >___| /____/
\/ \/ |__| \/ \/ \/ """)
gLine()
print("Welcome to the help menu!")
print("1. Go Back")
options = ["1"]
PI()
if PI == 1:
(back())
def gNorthernLights():
gLine()
ps2(""" ` : | | | |: || : ` : | |+|: | : : :| . `
` : | :| || |: : ` | | :| : | : |: | . :
.' ': || |: | ' ` || | : | |: : | . ` . :.
`' || | ' | * ` : | | :| |*| : : :|
* * ` | : : | . ` ' :| | :| . : : * :.||
.` | | | : .:| ` | || | : |: | | ||
' . + ` | : .: . '| | : :| : . |:| ||
. . ` *| || : ` | | :| | : |:| |
. . . || |.: * | || : : :|||
. . . * . . ` |||. + + '| ||| . ||`
. * . +:`|! . |||| :.||`
+ . ..!|* . | :`||+ |||`
. + : |||` .| :| | | |.| ||` .
* + ' + :|| |` :.+. || || | |:`|| `
. .||` . ..|| | |: '` `| | |` +
. +++ || !|!: ` :| |
+ . . | . `|||.: .|| . . `
' `|. . `:||| + ||' `
__ + * `' `'|. `:
"' `---''''----....____,..^---`^``----.,.___ `. `. . ____,.,-
___,--''''`---'' ^ ^ ^ ^ """'---,..___ __,..---'''
"' ^ ``--..,__ """)
gLine()
#Text Functions-----------------------------------------------------#
def ps(string):
#This function allows the game to type like a real person
#PS is short for "Print Slow"
typing_speed = 70
count = 0
space = False
#This aspect of the function works with the autotext wrap
#To make sure that it only wraps after full words, not
#midway through
for letter in string:
if letter == " " or letter == "":
space = True
else:
space = False
if count >= 50 and space == True:
print('\n')
count = 0
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print('')
def ps2(str):
#This function is the same as PS1 but without the Text Wrapping
typing_speed = 600
#Ask Mr. Ortiz how to make previous function based of line len.
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print('')
#Mechanics----------------------------------------------------------#
#Game Loop----------------------------------------------------------#
def titleScreen():
gHeader()
ps("1. Start")
ps("2. Load")
ps("3. Exit")
ps("4. Help")
options = ["1","2","3","4"]
pI(options)
if pI == 1:
dream0()
pCS = dream0()
if pI == 2:
load
if PI == 3:
gExit()
if PI == 4:
gHelp()
def dream0():
clear()
gNorthernLights()
ps("[???] Your name my son..what do the mortals use to summon you?")
pName = str(input("==> "))
ps(pName + "? I'm just as amused by the lower realm's creativity, as their ability to destroy themselves.")
ps("The void..she calls to you" + pName + "She favors you, just as her divinity does to me. You..shall be my avatar. It is time. Her prophecy shall be fullfilled. Awaken, my child!")
time.sleep(3)
clear()
#dream0()
titleScreen()
#Player Data--------------------------------------------------------#
pName = "Yorick"
pTrueName = "kliros"
pCS = titleScreen()
#pCS stands for Player Current Scene
There are several issues here:
if playerInput not in options or commands:
This will activate if playerInput is not in options, or if commands is defined. You meant to say that it should activate if playerInput is not in options AND playerInput is not in commands.
pI(options)
if pI == 1:
dream0()
pCS = dream0()
if pI == 2:
load
if PI == 3:
gExit()
if PI == 4:
gHelp()
Here, you expect pI(options) to return some value, but you never save it. When you check pI == 1, you are checking if the function is equal to 1, which is nonsense. Additionally, pI returns a string, not a number. Instead, you should have the following:
playerInput = pI(options)
if playerInput == "1":
dream0()
pCS = dream0()
if playerInput == "2":
load
if playerInput == "3":
gExit()
if playerInput == "4":
gHelp()
My wish is to make every character or line or whatever you think might look best for an ASCII to look. Basically I have tried colorama and it was only based on one color. What is the best method?
What I have is
print("""
_____ _ _ __ _
/ ____| | | | / _| |
| (___ | |_ __ _ ___| | _______ _____ _ __| |_| | _____ __
\___ \| __/ _` |/ __| |/ / _ \ \ / / _ \ '__| _| |/ _ \ \ /\ / /
____) | || (_| | (__| < (_) \ V / __/ | | | | | (_) \ V V /
|_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_| |_| |_|\___/ \_/\_/
""")
and that is pretty much it. Let me know your thoughts through this!
The valid foreground colors provided by colorama are variables on colorama.Fore. We can retrieve them using vars(colorama.Fore).values(). We can random select a foreground color by using random.choice, feeding it the foreground colors as obtained by vars.
Then we simply apply a randomly-chosen color to each character:
text = """
_____ _ _ __ _
/ ____| | | | / _| |
| (___ | |_ __ _ ___| | _______ _____ _ __| |_| | _____ __
\___ \| __/ _` |/ __| |/ / _ \ \ / / _ \ '__| _| |/ _ \ \ /\ / /
____) | || (_| | (__| < (_) \ V / __/ | | | | | (_) \ V V /
|_____/ \__\__,_|\___|_|\_\___/ \_/ \___|_| |_| |_|\___/ \_/\_/
"""
import colorama
import random
colors = list(vars(colorama.Fore).values())
colored_chars = [random.choice(colors) + char for char in text]
print(''.join(colored_chars))
This will print every character in a different color:
If you want colored lines instead, it's a simple change:
colored_lines = [random.choice(colors) + line for line in text.split('\n')]
print('\n'.join(colored_lines))
You can tailor the list of colors to your needs. For instance, if you want to remove colors which may be similar to your terminal background (black, white, etc.) you can write:
bad_colors = ['BLACK', 'WHITE', 'LIGHTBLACK_EX', 'RESET']
codes = vars(colorama.Fore)
colors = [codes[color] for color in codes if color not in bad_colors]
colored_chars = [random.choice(colors) + char for char in text]
print(''.join(colored_chars))
Which gives:
I have been learning python and getting different things off the internet and putting them all into this game I am making: "You wake up..." It's a text based assci RPG (Roll playing game). It worked until I got this error:
Traceback (most recent call last):
File "C:\Users\William\Desktop\Programming\Programs\You wake up\main.py", line 16, in <module>
import helper
File "C:\Users\William\Desktop\Programming\Programs\You wake up\helper.py", line 13, in <module>
import main
File "C:\Users\William\Desktop\Programming\Programs\You wake up\main.py", line 103, in <module>
init()
File "C:\Users\William\Desktop\Programming\Programs\You wake up\main.py", line 41, in init
game_text()
File "C:\Users\William\Desktop\Programming\Programs\You wake up\main.py", line 77, in game_text
helper.way_out_quest()
AttributeError: 'module' object has no attribute 'way_out_quest'
This is the main file (main.py):
#-------------------------------------------------------------------------------
# Name: main.py
# Purpose: An RPG (Roll playing game) where you wake up in a room and have
# to figure out text based puzzles to escape.
# The whole game will be done in a terminal (Shell) and will be
# completely text and assci code. This will be the main file.
#
# Author: William
#
# Created: 15/12/2013
# Copyright: (c) William 2013
#-------------------------------------------------------------------------------
import time
import assci
import helper
#Non-maluable variables:
__name__ = '__main__'
#Maluable variables:
#Error message if main.py is called from a different file
if __name__ != '__main__':
print("[ERROR]: main.py is the main file and should not be called by any other file.")
time.sleep(3)
exit()
#The function that starts/restarts the game
def init():
"""
Calls all the functions to start the game/ restart the game
"""
#Display a cool banner
assci.ywu_banner(2)
START_INPUT = input("Press ENTER/RETURN on your keyboard to start the game")
time.sleep(0.7)
assci.clear()
#Game text.
game_text()
#The text which is the main story line after the banner which gives the player
#A sense of what the setting is about
def game_text():
"""
Prints out a bit of text 2 lines down and clears the screen every 4 or so
seconds.
"""
time.sleep(5)
print("\n\nYour eyes gradually open")
time.sleep(4)
assci.clear()
time.sleep(2)
print("\n\nAfter waking up, you slowly gather your senses and sit up...")
time.sleep(4.5)
assci.clear()
time.sleep(2)
print("\n\nYou look around the room, and unexpectidly, you realise your in some sort of a prison cell!")
time.sleep(4)
assci.clear()
time.sleep(2)
print("\n\nIt's a sqaure room made of iron.")
time.sleep(4)
assci.clear()
time.sleep(2)
print("\n\nHow did I get here? -You think to yourself")
time.sleep(4)
assci.clear()
time.sleep(2)
helper.way_out_quest()
assci.clear()
time.sleep(2)
print("\n\nYou see a wooden door with 5 buttons and a handel... " + assci.WOODEN_DOOR)
time.sleep(6)
assci.clear()
time.sleep(2)
print("\n\nWhat was that? ...you think to your self.")
time.sleep(4)
assci.clear()
time.sleep(2)
print("\n\nWhat was that? ...you think to your self.")
time.sleep(4)
assci.clear()
time.sleep(2)
print("\n\nYou look around the room and walk slowly towards the iron door..")
time.sleep(4)
assci.clear()
time.sleep(2)
#Call init() function to start the game (init = initiate)
init()
helper.py:
#-------------------------------------------------------------------------------
# Name: helper
# Purpose: To contain helper functions for the game "Yoy wake up..."
#
# Author: William
#
# Created: 17/12/2013
# Copyright: (c) William 2013
#-------------------------------------------------------------------------------
import time
import assci
import main
#Error message if user executes the wrong file.
if __name__ == '__main__':
print("[ERROR]: Do not run this file. Run main.py - this file should not be executed!")
time.sleep(4)
exit()
#Function for the first quest: do you want to find a way out?
def way_out_quest():
"""
If the question is not answered, then the player can't move on. If they say
yes, then they continue through the script. If they say no, then the init
function is called from main.py
"""
way_out_answered = False
while way_out_answered == False:
WAY_OUT_INPUT = input("Quest: Do you want to find a way out? ")
if WAY_OUT_INPUT in ["yes", "Yes", "YES"]:
way_out_answered = True
elif WAY_OUT_INPUT in ["no", "No", "NO"]:
way_out_answered = True
time.sleep(2)
assci.clear()
print("GAME\nOVER!")
time.sleep (5)
assci.clear()
main.init()
else:
print("Type yes or no. ")
time.sleep(4)
This is the assci file with all the art/clear and text functions and stuff (assci.py):
#-------------------------------------------------------------------------------
# Name: assci
# Purpose: To create all the assci art and graphic tools for the game:
# "you wake up..."
#
# Author: William Bryant
#
# Created: 15/12/2013
# Copyright: (c) William 2013
#-------------------------------------------------------------------------------
import time
import os
WOODEN_DOOR = """ ______________________________
/_____/_____/_____/_____/_____/
._. ._.
| | | |
|_| ______ ______ |_|
|-| /_____/ /_____/ |-|
| | | |
|_| |_|
._. ._.
| | | |
|_| ______ |_|
|-| /_____/ |-|
| | /\ | |
|_| \/ |_|
._. ._.
| | | |
|_| ______ ______ |_|
|-| /_____/ /_____/ |-|
| | | |
|_| |_|
______ ______ ______ ______ ______ ______ ______ ______
/_____/ /_____/ /_____/ /_____/ /_____/ /_____/ /_____/ /_____/
/_____/ /_____/ /_____/ /_____/ /_____/ /_____/ /_____/ /_____/"""
#Error message if user executes the wrong file.
if __name__ == '__main__':
print("[ERROR]: Do not run this file. Run main.py - this file should not be executed!")
time.sleep(4)
exit()
#Clear function
def clear():
"""
Clears the console screen using the built in commands on a operating
system (here linux and windows)
"""
os.system(['clear','cls', "^L"][os.name == 'nt'])
#"Wake up..." title/banner at the start
def ywu_banner(num_of_times):
"""
Prints You wake up...(the game name) in ascii code big letters into a
console and clears the screen using the clear function above and reprints
the message to make the dots at the end appear to be moving.
"""
print("__ __ _")
time.sleep(0.25)
print("\ \ / / | |")
time.sleep(0.25)
print(" \ \_/ /__ _ _ __ ____ _| | _____ _ _ _ __")
time.sleep(0.25)
print(" \ / _ \| | | | \ \ /\ / / _` | |/ / _ \ | | | | '_ \ ")
time.sleep(0.25)
print(" | | (_) | |_| | \ V V / (_| | < __/ | |_| | |_) | _ _ ")
time.sleep(0.25)
print(" |_|\___/ \__,_| \_/\_/ \__,_|_|\_\___| \__,_| .__(_|_|_)")
time.sleep(0.25)
print(" | | ")
time.sleep(0.25)
print(" |_| ")
time.sleep(0.25)
clear()
for foo in range(num_of_times):
print("__ __ _")
print("\ \ / / | |")
print(" \ \_/ /__ _ _ __ ____ _| | _____ _ _ _ __")
print(" \ / _ \| | | | \ \ /\ / / _` | |/ / _ \ | | | | '_ \ ")
print(" | | (_) | |_| | \ V V / (_| | < __/ | |_| | |_) | _ ")
print(" |_|\___/ \__,_| \_/\_/ \__,_|_|\_\___| \__,_| .__(_|_)")
print(" | | ")
print(" |_| ")
time.sleep(0.7)
clear()
print("__ __ _")
print("\ \ / / | |")
print(" \ \_/ /__ _ _ __ ____ _| | _____ _ _ _ __")
print(" \ / _ \| | | | \ \ /\ / / _` | |/ / _ \ | | | | '_ \ ")
print(" | | (_) | |_| | \ V V / (_| | < __/ | |_| | |_) | ")
print(" |_|\___/ \__,_| \_/\_/ \__,_|_|\_\___| \__,_| .__(_)")
print(" | | ")
print(" |_| ")
time.sleep(0.7)
clear()
print("__ __ _")
print("\ \ / / | |")
print(" \ \_/ /__ _ _ __ ____ _| | _____ _ _ _ __")
print(" \ / _ \| | | | \ \ /\ / / _` | |/ / _ \ | | | | '_ \ ")
print(" | | (_) | |_| | \ V V / (_| | < __/ | |_| | |_) | ")
print(" |_|\___/ \__,_| \_/\_/ \__,_|_|\_\___| \__,_| .___/")
print(" | | ")
print(" |_| ")
time.sleep(0.7)
clear()
print("__ __ _")
print("\ \ / / | |")
print(" \ \_/ /__ _ _ __ ____ _| | _____ _ _ _ __")
print(" \ / _ \| | | | \ \ /\ / / _` | |/ / _ \ | | | | '_ \ ")
print(" | | (_) | |_| | \ V V / (_| | < __/ | |_| | |_) | _ _ ")
print(" |_|\___/ \__,_| \_/\_/ \__,_|_|\_\___| \__,_| .__(_|_|_)")
print(" | | ")
print(" |_| ")
time.sleep(0.7)
clear()
START = input("Press ENTER/RETURN on your keyboard to start the game")
time.sleep(0.7)
clear()
Your init() call in main.py needs to be in an if __name__ == '__main__': block, and you should not set __name__ yourself - Python will do that automatically.
Otherwise your circular imports will cause helper to not be imported properly before init() is called. The sequence as it stands is going like this:
You run main.py, which starts main.py being evaluated.
The import helper line in main.py starts helper.py being evaluated.
The import main line in helper.py starts another evaluation of main.py because the main module has not been previously imported.
The import helper line in the second evaluation of main.py imports the existing helper object that was created when #2 started helper being imported, so this doesn't create an infinite loop - but the existing helper object hasn't fully loaded yet; it's still waiting for the main import to resolve.
The second evaluation of main hits the init() call at the bottom of main.py, which tries to run init() - but helper still isn't done loading, and thus the way_out_quest function in helper.py hasn't been evaluated yet and thus is not defined.
In general, it's best to avoid circular imports in the first place - then you don't have to worry about problems like this.