I have two files in a game I am currently making (not finished). They are the same directory. When I run either of the two files, the terminal in macos Serria is giving me this error (and yes, I did research, to no avail). BTW, thank you, StackOverFlow, for answering (and downvoting when needed) questions. It truly helped me.:
File "story.py", line 3, in <module>
from engine import *
File "SurvivalAdventureGame/Resources/engine.py", line 2, in <module>
from story import *
File "SurvivalAdventureGame/Resources/story.py", line 5, in <module>
class Start(Scene):
NameError: name 'Scene' is not defined
Here is story.py:
from sys import exit
from random import randint
from engine import *
class Start(Scene):
print """
You are flying to Brussels from Seattle. You *are* glad you received the bonus from work, you think to yourself.
\nUnfortunally, you were only able to put 100$ towards the vacation due to your bastard landlord.
\nYou muttered to yourself, "If this plane got League Pass, though. Warriors-Raptors would be lit."
\nYep, your 14-year old son says as he reads The New Jim Crow. Your 9-year old son is playing Minecraft.
\nThen the speakers boomed, as the crew said, "Hi. My name is Messlia and our pilot is temporarily incapacitated."
\nA strange mixture of curses, crying, yells of terror, and silence filled the cabin.
\n"We will land shortly on a grass clearing near trees."
\nMore panic.
\nYou cried as You told your panicking sons (and secretly myself) to do
"""
print "1. Bring only a blanket, some food and water, some clothing, and every medication needed."
print "2. Bring nothing"
print "3. Bring everything you possibly can."
action = raw_input("> ")
if action == "1":
print "You survived, crawling out the door with a painful leg injury."
print "\n Your older son, a safety-first guy, escaped without ANY injury AT ALL. Your other son, however, has a gaping hole in his wrists."
print "\n He sheds tears, clearly in pain, as you ponder your options."
print "1. Splash with water and cover it with a blanket"
print "2. Cover it with a towel."
print "3. Splash it with water only."
next = raw_input("> ")
if next == "1":
print "Your now have about 50 mL of water left. However, he has calmed down."
Day1()
elif next == "2":
print "You now have to tend to the boy at all times. However, at least he will not get sick, right?"
Day1()
elif next == "3":
print "You now only have 50 mL of water left. At least he calmed down a bit!"
Day1()
else:
Stupid()
elif actions =="2":
print "You survive with no injuries, however, you have nothing and your youngest son just suffered a major wrist injury."
Day1()
elif next == "3":
print "You, your sons, and 12 people die because of you delaying everyone else."
Death()
else:
Stupid()
class Death(Scene):
print "Either you, one or both of your sons or others died. You suck."
class Stupid(Scene):
print "ERROR: OVERWHELMING STUPIDITY."
print "You should enter the numbers without the period, without the words"
Here is engine.py:
from sys import exit
from story import *
class Scene(object):
def __init__(self):
start()
def start(self):
print "DOESNOTEXIST!"
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n--------"
next_scene_name = current_scene.start()
current_scene = self.scene_map.next_scene(next_scene_name)
class Map(object):
# Won't work now, Gotta finish writing the story!
scenes = {
"Start": Start(),
"Day1": Day1(),
"Day2": Day2(),
"Day3": Day3(),
"Day4": Day4(),
"Day5": Day5(),
"Day6": Day6(),
"Day7": Day7(),
"Day8": Day8(),
"Death": Death(),
"Stupid": Stupid(),
}
def __init__(self, start_scene):
self.start_scene = start_scene()
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
class play(object, Map):
def __init__(self, map):
the_map = Map('Start')
the_map = Engine(the_map)
a_game.play()
Looks like you have a circular dependency: in story you import * (everything) from engine and vice versa. This is not supported in Python.
Related
I am new to coding, so I've been creating simple programs. I'm currently trying to make a guess the number program. I'm currently having issues trying to make the program tell you whether you won or lost by detecting whether the number entered by the user is equal to the number that was generated. This is my code, and I am currently getting a syntax error on line 10, which I don't understand. Please help me!
import time
from time import sleep
import random
var1 = "Hello"
print(var1)
time.sleep(1)
print("I'm going to pick a number now!")
time.sleep(2)
value = (random.randint(1, 9)
print("Okay, now it's your turn!")
usernumber = input("""Pick a number, 1-9:
""")
time.sleep(1)
var2 = "I picked..."
print(var2)
time.sleep(1)
print(value)
if var3 == usernumber
print("You win!")
if var3 != usernumber
print("You lose. :(")
value = (random.randint(1, 9)
Note the missing parenthesis.
It should be
value = (random.randint(1, 9))
I am trying to implement a loop around the option of having the spear or not.
With the spear, the hero should kill the bear. Without the spear, he should be eaten.
Originally, I set spear to False, and then changed it to TRUE when the hero picked up the spear. However, when looping back to bear_room(), the value of spear is reset to FALSE.
Is there any way to get around this without having to nest 2 if functions?
if not is there a cleaner implementation of the second if loop?
I attempted using if "true" and "true" and "if true and false" to determine whether the spear is held by the hero or not. Right now this does not work. However, the code still runs as is.
Here is the code:
from sys import exit
def dead(why):
print why, "good Job!"
exit(0)
def bear_room():
print """In front of you is a big bear. It stares at you. You notice a door behind the bear. To the side of the bear you see a spear propped up against the wall. What do you do?"""
print"1. Fight the bear"
print"2. Pick up the spear"
print"3. try to run away"
bear = raw_input(">")
spear = False
if (bear == "1" and spear == True) :
print "You fight and kill the bear"
elif (bear == "1" and spear == False):
dead("the bear claws your face off")
elif (bear == "2" and spear == True):
print "You already have the spear"
bear_room()
elif (bear == "2" and spear == False):
print "you picked up the spear"
spear = True
print "Now do you want to fight the bear?"
print "1. Fight the bear with the spear"
print "2. Try to run away from the bear"
choice = raw_input(">")
if choice == "1":
print """You fought and killed the bear, you can now
go through the door"""
elif choice == "2":
dead("The bear eats you from behind")
else:
"""You drop the spear, and retreat back to the entrance of the room. """
bear_room()
elif (bear == "3"):
dead("The Bear catches you and rips your head off")
else:
print "Please choose what to do!"
bear_room()
bear_room()
declare bear_room with a parameter:
def bear_room(spear = False):
take out the initial spear = False and whenever you call recursively bear_room make sure you pass in bear_room(spear) to reflect if spear has been change.
Note that if you just call bear_room() with no parameters to pass in, spear will be reset to False
Change the signature of the function bear_room() to bear_room(spear_status=False)
initialize your spear variable with spear_status
and where ever you calling bear_room() call it as bear_room(spear)
You can also make use of objects. Here is an example.
from sys import exit
class Person:
def __init__(self, name):
self.name = name
self.items = []
def die(self,why):
print why, "good Job", self.name
exit(0)
def bear_room(person):
print """In front of you is a big bear. It stares at you. You notice a door behind the bear. To the side of the bear you see a spear propped up against the wall. What do you do?"""
print"1. Fight the bear"
has_spear = "Spear" in person.items
if not has_spear: print"2. Pick up the spear"
print "3. try to run away"
bear = raw_input(">")
if (bear == "1" and has_spear) :
print "You fight and kill the bear"
return True
elif (bear == "1" and not has_spear):
person.die("the bear claws your face off")
elif (bear == "2" and not has_spear):
print "you picked up the spear"
person.items.append("Spear")
return False
elif (bear == "3" and has_spear):
person.die("The Bear catches you and rips your head off")
elif (bear == "3" and not has_spear):
person.die("The Bear eats you from behind")
elif has_spear:
print "You drop the spear retreat back to the entrance of the room. "
return True
else:
print "Please choose what to do!"
return False
warrior = Person("Soldat")
while True:
if bear_room(warrior): break
Hi I am 11 yrs old and I am teaching myself how to code. I set myself a task to make a times table quiz that asks 10 questions and inputs random numbers. However, my code is not working and I do not know why. I am using python 2.7.5. This is my code:
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
import random
print random.randint(1,10)
print ("times")
import random
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"
I can not spot why it is not working but I have not put a for loop in yet so it only asks 1 question. When I run it else is highlighted in red but I do not know why.
Python works without brackets. It is replaced by "spaces or tabs". And we import ONCE, the beginning.
This should work
import random
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
print random.randint(1,10)
print ("times")
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"
I need to know how i can enter user input while this while loop counting time is running. I know my program is not efficient nor organized as I am new to python. A simple but longer fix is better than a short fix that I would not understand.
import time
print 'Welcome To the Speedy Type Game!'
time.sleep(1)
print "You're objective is to win the game by typing the specific word before the time runs out"
print "Don't forget to press 'enter' after typing the word!!!!"
print "For round 1 you will have 5 seconds"
null = raw_input('Press enter when you are ready to start')
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'GO'
C = 'poop'
x = 5
while C in ['poop']:
x = x - 1
time.sleep(1) #This is where my program comes to a halt.
C = raw_input("Print the word 'Calfornia': ") #I dont know how to make the program progress to here without stopping the timer above.
if x < 0:
print 'You have failed, game over!'
else:
print 'Good Job! let us move to the next round!'
There is no easy way to do this in Python - a single process is running at a time, so without e.g. threading (see https://stackoverflow.com/a/2933423/3001761) you can't overlap user input with counting. An easier approach might be:
def test(word, limit=5):
started = time.time()
while True:
result = raw_input("Type {0!r}: ".format(word))
finished = time.time()
if result == word and finished <= started + limit:
print 'Good Job! let us move to the next round!'
return True
elif finished > started + limit:
break
print 'Wrong, try again.'
print 'You have failed, game over!'
return False
Then call e.g.:
>>> test("California")
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly but quickly
Wrong, try again.
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly and slowly
You have failed, game over!
False
>>> test("California")
Type 'California': California # typed slowly
You have failed, game over!
False
I'm having an issue with this code:
import math
class Money(object):
def __init__(self, salary):
self.salary = salary
sal(self.salary)
def sal(self, x):
y = ( x - ( ( (x * 0.22) + 6534) ) - (1900.9408 + ( (x - 37568)*.077) ) )
print '-----------------------------------------------------------'
print 'monthly income before tax will be: ${0:.2f}' .format(x/12)
print 'bi-weekly income before tax will be: ${0:.2f}' .format(x/24)
print 'Hourly after tax: ${0:.2f}' .format(x/24/70)
print '-----------------------------------------------------------'
print 'Income after tax will be: ${0:.2f}' .format(y)
print 'Monthly after tax: ${0:.2f}' .format((y/12))
print 'bi-weekly after tax: ${0:.2f}' .format((y/24))
print 'Hourly after tax: ${0:.2f}' .format(y/24/70)
answer = raw_input('Do you want to do this again?\nType [Y] or [N]: ')
if( answer == 'Y'):
sal(x)
else:
print 'Thank you!'
return
def main():
x = input('Enter your taxable income: ')
salaryLister = Money(x)
main()
The traceback shows this:
Traceback (most recent call last):
File "taxableincome.py", line 35, in <module>
main()
File "taxableincome.py", line 33, in main
salaryLister = Money(x)
File "taxableincome.py", line 7, in __init__
sal(self.salary)
NameError: global name 'sal' is not defined
What does:
global name 'sal' is not defined mean?
Feel free to make comments about my design as well. I'd love to learn.
use self.sal, this is how you call instance methods of classes in python
How this works in python is, If you look at the method signature you have
def sal(self, salary)
basically, it needs the class reference as the first variable. And in python when you do self.sal it translates to
Money.sal(self, salary)
You can also call the method like this, but the recommended way is
self.sal(salary)
As per comments on your code, There definitely aren't any clear red flags. Though the last return statement in the sal function is not required. Its not a problem having it there, just something that caught my eye.
Also since you asked, I'd like to point this out. Please try to keep to a coding standard. let it be your own or someone else's. The important thing is consistency. But PEP-8 is generally the accepted style for python. You even have plugins for your editor which help you stick to it. You might want to read the style guide linked here.