For simplicity I'm posting here only two modules (the other modules have "pass" in them). start.py module worked right up until I changed something in player.py module, in the class CreateNewPlayer and now what happens is this:
I start with start.py from my command line but instead of first showing my intro (splashcreen function) it jumps straight to CreateNewPlayer right away.
What did I do wrong?
This is the first file start.py:
import sys
import custom_error
import player
import handler
import prompt
import game
def splash_screen():
print chr(27) + "[2J"
print "*" * 80
print "***** Welcome to ZOMBIE ADVENTURE *****"
print "*" * 80
print "\nSelect option:"
print "1. Start a new game"
print "2. Load existing game"
print "3. Quit"
while True:
action = prompt.menu()
if action == 1:
create_player = player.CreateNewPlayer()
new_player = player.Player(create_player.name, create_player.age, create_player.male, create_player.inventory)
print "\nYour name is %s and you're %d old." % (new_player.name, new_player.age)
print "It is %s that you're a man." % new_player.male
print "\n1. Continue to game"
print "2. Back to main menu"
action = prompt.menu()
while True:
if action == 1:
game.Engine.launchgame()
elif action == 2:
exit(1)
else:
custom_error.error(1)
# a_game = game.Engine('Room1')
# a_game.LaunchGame(new_player)
elif action == 2:
handler.load()
elif action == 3:
exit(1)
else:
custom_error.errortype(0)
splash_screen()
Now second file called player.py:
import sys
import custom_error
import prompt
import game
class Player(object):
male = True
inventory = []
def __init__(self,name,age,male,inventory):
self.name = name
self.age = age
self.male = male
self.inventory = inventory
class CreateNewPlayer(object):
print chr(27) + "[2J"
print "-" * 80
print "Character creation"
print "-" * 80
name = raw_input("Type your character name > ")
age = int(raw_input("Put down your age in numbers > "))
male = True
sex = raw_input("Are you a male or female? M/F > ")
if sex.lower() == "m":
male = True
elif sex.lower() == "f":
male = False
else:
print "Please type either 'M' or 'F'"
pass
inventory = []
The attributes within CreatePlayerCharacter are class attributes; all of the code within that class definition runs when the class is created, i.e. when the file is imported, rather than when a class instance is created.
Looking at your code so far, you would probably be better defining a class method Player.create:
class Player(object):
...
#classmethod
def create(cls):
name = raw_input("Type your character name > ")
...
return cls(name, age, male, [])
This can be accessed:
new_player = Player.create()
and will return a Player instance directly.
You should also remove male and inventory class attributes from Player.
Related
I'm trying to import the Human object I created for my contact book program and im doing it in VS Studio Code but it gives me an error:
Import "Human" could not be resolved
I tried to make the program in pycharm instead and it imported just fine and I even finished the program. And while looking around for a solution for the VS Studio Code version, I found some stuff like adding
"python.autoComplete.extraPaths": ["./**"],
to my settings.json and I did and a few other things i found on google, but it nothing helped.
VS Studio Code:
from Human import Human
#from Contact_Book_Project.Human import Human # auto generated, Not sure how it is different but i do have these 2 classes in a folder called Contact_Book_Project
book = []
def main():
while (True):
choice = int(input("Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
def addPerson(person):
book.append(person)
if __name__ == "__main__":
main()
class Human:
def __init__(self, name, phone_Number, address):
self.Name = name
self.Phone_Number = phone_Number
self.Address = address
def getName(self):
return self.Name
def getPhoneNumber(self):
return self.Phone_Number
def getAddress(self):
return self.Address
PyCharm Code:
from Human import Human
book = []
def main():
while (True):
try:
choice = int(input(
"Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to "
"list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
elif (choice == 2):
name = input("Enter name of person to remove: ")
temp = 0
for i in book:
if i.getName() == name:
book.pop(temp)
print(i.getName() + " removed.")
break
temp += 1
# elif (choice == 3):
# name = input("Enter name of person to check if they are in your contact book and retrieve their "
# "information: ")
#
# if name in book:
# temp = book.__getitem__(name)
# print(
# "Name: " + temp.getName() + "\nPhone Number: " + temp.getPhoneNumber() + "\nAddress: " + temp.getAddress())
# else:
# print(name + " does not exist in your contact book.")
elif (choice == 4):
for p in book:
print(
"Name: " + p.getName() + "\nPhone Number: " + p.getPhoneNumber() + "\nAddress: " + p.getAddress() + "\n")
except ValueError:
print("\nInvalid input.\n")
def addPerson(person):
book.append(person)
if __name__ == '__main__':
main()
both are using the same Human class. How can I fix this? Why is it throwing an error in VS Studio but work in Pycharm?
Maybe try directing VS Code to the exact location of the Human module:
import sys
sys.path.append('file path to Human.py') # Add file path to 'Human.py' here
from Human import Human
I am creating a random name generator using OOP in python however i am very new to this concept which is why i am having so difficulties with accessing methods in other methods. I read a post on stack overflow which said to call a method inside another method in a class, you must add self.funcname(param) however i have already done this and it still does not work
class Rndm_nme_gen:
def __init__(self):
print("THE RANDOM NAME GENERATOR")
self.value = ""
self.range = 5
self.counter = 0
self.loop = True
self.names = []
self.loop2 = True
self.take_input()
def take_input(self):
while self.loop:
user_input = input("ENTER A NAME: ")
self.num_check(user_input)
if self.value == "true":
print("INVALID NAME")
loop = True
elif self.value == "false":
self.counter += 1
self.names.append(user_input)
if self.counter == 5:
self.loop = False
self.genname()
#i am trying to call this function but it is not working as i hoped it would
def num_check(self, string):
self.string = string
for char in self.string:
if char.isdigit():
self.value = "true"
else:
self.value = "false"
def genname(self):
while self.loop:
gen = input("TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT").strip().lower()
if gen == " " or gen == "":
num = random.randint(0, 5)
print("NAME : " + str(self.names[num]))
loop == True
elif gen == 'q':
quit()
else:
print("UNKNOWN COMMAND")
loop = True
user1 = Rndm_nme_gen()
In the initialisation method, i called the take_input function so it automatically runs and from that function, i attempted to run the code from the genname function however the program would simply end
If you would like to run the code to see how it works, feel free to do so
Expected output:
ENTER NAME FDSF
ENTER NAME dfsd
ENTER NAME sdfds
ENTER NAME sfdff
ENTER NAME sfdf
TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT
it does not say TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT when i run the program
Ok I going through LPTHW and writing a game. We are supposed to section the game up into different scripts to see how importing them works. I have 4 scripts: ex45.py executes the main code, Engine45.py is the engine, Locations45.py is the list of locations, and Maps45.py is what holds the map values and moves through locations.
The error I get when running is:
Traceback (most recent call last):
File "ex45.py", line 2, in
import Maps45
File "C:\Users\Raistlin\Python\Maps45.py", line 1, in
import Locations45
File "C:\Users\Raistlin\Python\Locations45.py", line 4, in
class Map(object):
File "C:\Users\Raistlin\Python\Locations45.py", line 6, in Map
'Gold_gym' : Gold_gym(),
NameError: name 'Gold_gym' is not defined
I don't understand why I am getting a Gold_gym is not defined when it is defined in Locations45.py.
Code blocks below:
ex45.py
import Engine45
import Maps45
import Locations45
a_map = Map('Gold_gym')
a_game = Engine(a_map)
a_game.run()
Engine45.py
class Engine(object):
def __init__(self, location_map):
print "Engine __init__ has location_map", location_map
self.location_map = location_map
def run(self):
current_location = self.location_map.opening_location()
print "Play's first scene", current_location
while True:
print "\n"('-' * 20)
next_location_name = current_location.use()
print "next location", next_location_name
current_location = self.location_map.next_location(next_location_name)
print "map returns new location", current_location
Locations45.py
from random import randint
from sys import exit
class Location(object):
def use(self):
print "This is not configured."
exit(1)
class Loser_gym(Location):
quips = [
'You are worthless, goodbye.'
'Thanks for trying noob.'
'Sex and candy, not today.'
]
def use(self):
print Loser_gym.quips[randint(0, len(self.quips)-1)]
exit(1)
class Gold_gym(Location):
def use(self):
print "Welcome to the Gold Gym. This gym will test your physical prowess."
print "Before you there is a large pool of water with a center platform."
print "On your person is a satchel, a whip, a hat, and a gun."
print "Your goal is to find the way out of the gym."
print "Acceptable inputs are satchel, whip, hat, or gun."
print "Good Luck."
action = raw_input("What do you do:> ")
if action == 'satchel':
print "You throw your satchel towards the center platform."
print "It does absolutely nothing. Try again."
return 'Gold_gym'
elif action == 'whip':
print "You use your whip somewhat akin to Indiana Jones."
print "You swing from a pipe and land squarely on the center platform."
print "You have survived this turmoil."
return 'Sapphire_gym'
elif action == 'hat':
print "You valiantly toss your hat toward the center platform."
print "Your hat is caught by a gust of wind and blows away."
print "You cannot survive without your hat."
return 'Loser_gym'
elif action == 'gun':
print "You shoot your about wildly in the air."
print "A ricochet hits you in the head and you die."
return 'Loser_gym'
else:
print "DOES NOT COMPUTE, TRY AGAIN."
return 'Gold_gym'
class Sapphire_gym(Location):
def use(self):
print "Welcome to the Sapphire gym, here your cognitive ability will be tested."
print "Just kidding there is no way to figure this out consistently."
print "Before you stands a door, the door has a small keypad on it."
print "Below the keypad is what appears to be a smart card reader."
print "On your way to the location you picked up two smartcards off the ground."
print "One is red and one is green."
print "Clearly you will need to use a smartcard and guess a code(3-digits)."
card = raw_input('Which card do you choose:> ')
if card == 'red':
print "A laser beam comes out of the door and cauterizes your brain."
return 'Loser_gym'
elif card == 'green':
code = '%d%d%d' % (randint(0,9), randint(0,9), randint(0,9))
guess = raw_input('What code do you enter:> ')
guesses = 0
while guess != code and guesses < 20 and guess != '123':
print "INCORRECT!"
guesses += 1
guess = raw_input('What code do you enter:> ')
if guess == code or guess == '123':
print "Nice guess noob! You may press onward."
return 'Cerulean_gym'
else:
print "WRONG! TOO MANY GUESSES! DIE INFERIOR BEING!"
return 'Loser_gym'
class Cerulean_gym(Location):
def use(self):
print "Welcome to the final gym, the Cerulean Gym!"
print "Before you is a 3x3 platform, your job is to cross the platform."
print "Be warned that each tile can trigger a trap."
print "Good luck!"
correct_square = ['3', '1', '2']
jump = raw_input("Square 1, 2, or 3?:> ")
jumps = 0
while jumps < 3:
if jump == correct_square:
print "Nice job! You picked the correct square!"
jump += 1
correct_square = correct_square[0+jump]
jump = raw_input("Square 1, 2, or 3?:> ")
jumps += 1
else:
print "YOU FAIL! Goodbye you puny infidel."
return 'Loser_gym'
print 'NICE JOB. YOU WIN ALL THE BASE!'
Maps45.py
import Locations45
class Map(object):
locations = {
'Gold_gym' : Gold_gym(),
'Sapphire_gym' : Sapphire_gym(),
'Cerulean_gym' : Cerulean_gym(),
'Loser_gym' : Loser_gym()
}
def __init__(self, start_location):
self.start_location = start_location
print "start_location in __init__", self.start_location
def next_location(self, location_name):
print "start_location in next_location"
val = Map.locations.get(location_name)
print "next_location returns", val
return val
def opening_location(self):
return self.next_location(self.start_location)
Help please?
When you:
import Locations45
that module is imported under the namespace Locations45
So when you call
Gold_gym()
It looks in Maps45 for that object, never knowing to look in Locations45.
Change the line to read:
locations = {
'Gold_gym' : Locations45.Gold_gym(),
'Sapphire_gym' : Locations45.Sapphire_gym(),
'Cerulean_gym' : Locations45.Cerulean_gym(),
'Loser_gym' : Locations45.Loser_gym()
If you just do import Locations45, it doesn't import each of the names - instead, it imports it as a group. You can refer to individual things within the group using a period:
'Gold_gym': Locations45.Gold_gym(),
'Sapphire_gym': Locations45.Sapphire_gym(),
'Cerulean_gym': Locations45.Cerulean_gym(),
'Loser_gym': Locations45.Loser_gym()
Alternatively, you could import all of the names specifically:
from Locations45 import Gold_gym, Sapphire_gym, Cerulean_gym, Loser_gym
which would make those names available without needing to use the prefix.
I am making a small text game, and one of my methods is behaving unexpectedly, and I can't figure out why. If I import the module and run the method in python, it works fine. Some parts of the game aren't complete, but that parts that I need run fine.
With the module pasted below, choose method is changing a list into a string, but only when the module is run. I'm running this on 2.7.3, on a mac.
Edit: I figured it out. The program execution had continued, and I was confused by the choose call in the match method. The options parameter sent in match was a string, instead of the list it should have been, but that was simple to figure out why.
import fighters
import weapons
from random import randint
from sys import exit
class Hero(object):
weapons = ["spikeglove", "shortsword"]
hp = {"actual":50, "base":50}
score = 0
def attack(self, weapon, method):
return None
class Scene(object):
# Returns one or more items from the provided choices
def choose(self, options, max_choices, prompt):
chosen = []
while len(chosen) < max_choices and len(options) > 0:
print
print prompt
print options, chosen
for o in options:
print "- {}".format(o)
print type(options)
choice = raw_input("> ")
if choice in options:
chosen.append(choice)
options.remove(choice)
print options, chosen
else:
print "That is not one of the options!"
if len(chosen) == 1:
return chosen[0]
else:
return chosen
class Death(Scene):
def enter(self):
print "You are now dead"
return "menu"
class Exit(Scene):
def enter(self):
print "Thanks for playing!"
return exit(1)
class Menu(Scene):
def enter(self):
menu_options = ["play", "train", "exit"]
choice = self.choose(menu_options, 1, "Welcome to the Arena!")
return choice
class Level(Scene):
def __init__(self):
self.prologue = "Welcome to {}".format(self.__class__.__name__)
next_scene = "level1"
# A match is the fight between the Hero and a particular Enemy
# A Hero must defeat each Enemy via a match to win the tournament/level
def match(self, hp, weapons, enemy):
hero_hp = hp
enemy_hp = enemy.stats["hp"]
last_attack = ""
while hero_hp and enemy_hp:
weapon_choice = self.choose(weapons, 1, "> ")
attack_choice = self.choose(weapon_choice.available_attacks(last_attack), 1, "> ")
last_attack = attack_choice
hero_attack = hero.attack(attack_choice)
enemy_attack = enemy.attack()
print "Hero: {} {}: {}".format(hero_hp, enemy, enemy_hp)
if hero_hp:
return "victory", hero_hp
else:
return "defeat"
# The game cycles through the enemies that our hero has to face
# passing the setup to the "match" function for the fighting
def enter(self):
print
print
print self.prologue
start_hp = hero.hp['actual']
weapons = self.choose(hero.weapons, 2, "Choose a weapon")
while self.enemies:
enemy = fighters.roster[self.enemies.pop()]
match_outcome, finish_hp = self.match(start_hp, weapons, enemy)
if match_outcome == "defeat":
hero.hp['actual'] = hero.hp['base']
return "death"
# The Hero enters the next match with the current HP obtained from the previous match
start_hp = finish_hp
# Add our Hero's victory points, and get them some medical attention
# before heading back to the Barracks
points_award = 5
hero.points += points_award
hero.hp['actual'] = hero.hp['base']
new_weapon = "shortsword"
hero.add_weapon(new_weapon)
epilogue = """Congratulations!
You have gained {} points for a total score of {}.\n
You have unlocked the \"{}\" """.format(
points_award, hero.points, new_weapon)
return next_scene
class Train(Scene):
pass
class Level1(Level):
enemies = ["boxer", "boxer"]
next_scene = "level2"
class Level2(Level):
pass
class Level3(Level):
pass
class Level4(Level):
pass
class Level5(Level):
pass
class Engine(object):
def __init__(self, start_scene):
self.start_scene = start_scene
scenes = {
"menu": Menu(),
"death": Death(),
"exit": Exit(),
"play": Level1(),
"level2": Level2(),
"level3": Level3(),
"level4": Level4(),
"level5": Level5(),
}
def next_scene(self, scene_name):
return self.scenes[scene_name]
def play(self):
current_scene = self.scenes[self.start_scene]
while True:
next_scene = current_scene.enter()
current_scene = self.scenes[next_scene]
if __name__ == "__main__":
hero = Hero()
game = Engine("menu")
game.play()
Terminal output:
$ python arena.py
Welcome to the Arena!
['play', 'train', 'exit'] []
- play
- train
- exit
<type 'list'>
> play
['train', 'exit'] ['play']
Welcome to Level1
Choose a weapon
['spikeglove'] []
- spikeglove
<type 'list'>
> spikeglove
[] ['spikeglove']
>
spikeglove []
- s
- p
- i
- k
- e
- g
- l
- o
- v
- e
<type 'str'>
Yet when I run in python:
>>> import arena
>>> s = arena.Level1()
>>> s.choose(['shortsword', 'spikeglove'], 2, "Choose a weapon")
Choose a weapon
['shortsword', 'spikeglove'] []
- shortsword
- spikeglove
<type 'list'>
> shortsword
['spikeglove'] ['shortsword']
Choose a weapon
['spikeglove'] ['shortsword']
- spikeglove
<type 'list'>
> spikeglove
[] ['shortsword', 'spikeglove']
['shortsword', 'spikeglove']
The if __name__ == "__main__": means that the portion of code indented after that if-statement will be executed only when the script is executed, not when it is imported.
While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]: