Method within Class not activating - python

Here is my code, my issue is as the title above states, the input text does not appear and neither does the print below. I am new to Python so sorry for a simple mistake
class Horse:
colour = ''
height = ''
speed = 0
def __init__(self):
self.speed = input("Enter an integer: ")
if(self.speed != 0):
self.gallop = (3 * self.speed)
print(self.gallop)

You need to make an instance of your object by initiating it. Here is the full program:
class Horse:
colour = ''
height = ''
speed = 0
def __init__(self):
self.speed = input("Enter an integer: ")
if(self.speed != 0):
self.gallop = (3 * self.speed)
print(self.gallop)
if __name__ == '__main__':
x = Horse()

You have to create an instance of the class... because so your code in the constructor is invoked
if __name__ == '__main__':
a = Horse()

You did not create an horse instance. Add the code below.
def create_horse():
new_horse = Horse() # this will ask for an integer
if __name__ == '__main__':
create_horse()

Related

Why is my count variable not incrementing for each new instance of my class?

My code:
class Lobby(Definition):
Lcount = 0
def __init__(self):
if Lobby.Lcount == 0:
self.description = "test1"
elif Lobby.Lcount > 0:
self.description = "test2"
else:
print("\nHmmm something went wrong...\n")
self.contents = ["Briefcase"]
self.doors = {"n": "terminal", "w": "hallway"}
Lobby.Lcount += 1
I want it to be where after an instance of the room has been created (i.e. you have visited it before), it will display a different description than it the original one. However, it keeps printing the same description. So what precisely am I doing wrong here?
edit: Here is what is in my definition class:
class Definition:
def __init__(self):
self.description = ""
self.contents = []
self.doors = {}
def get_desc(self):
print("{}".format(self.description))
def get_direction(self):
direction = input("Enter a direction or search the room: ").lower()
search = True
if direction == "q":
return direction
elif direction in self.doors:
location = self.doors[direction]
return location
elif direction == "s":
while search:
action = input("\nYou search for some items... Press 1 to continue or 2 to quit.\n")
if action == "1":
if len(location.contents) == 0:
print("\nYou find nothing of value in the room.\n")
else:
find = random.randrange(1, 3)
if find == 1:
found = random.randrange(len(location.contents))
item = location.contents.pop(found)
print("\nYou found a {}\n".format(item))
self.items.append(item)
self.check_items()
else:
print("\nNothing found yet\n")
elif action == "2":
search = False
break
else:
print("\nLocation reminder: ")
location.get_description()
else:
return "\nNot a valid entry\n"
Something in Definition is preventing this from working appropriately.
class FooClass(object):
foo = 0
def __init__(self):
print("Foo {} before".format(self.__class__.foo))
self.__class__.foo += 1
print("Foo {} after".format(self.__class__.foo))
# Works appropriately
>>> x = Foo()
Foo 0 before
Foo 1 after
>>> x = Foo()
Foo 1 before
Foo 2 after
However I'd recommend a different way to track this if it's just a binary "seen" variable. Restricting your ability to create multiple Lobby objects may mess you up in the future. Strongly consider creating a dictionary that houses all your objects, with a visit method that runs the logic your __init__ is doing now, and sets a flag that makes a following visit do something different.
class SomeRoom(Room):
# where Room is some superclass like Definition is now
def __init__(self, *args):
super().__init__(args) # or however
self.__visited = False
#property
def visited(self):
return self.__visited
def visit(self):
if self.visited:
print("Welcome back")
else:
print("Welcome!")
self.__visited = True

How to return values of variables from a function in Python 2.7?

import random
import time
#universal variables
attack = 1
defend = 2
heal = 3
v = False
player_health = 0
player_damage = 0
player_heal = 0
player_block = 0
ai_health = 0
ai_damage = 0
ai_heal = 0
ai_block = 0
#player classes in the form of dictionaries
sniper = {}
sniper["health"] = 50
sniper["damage"] = random.randint(20,40)
sniper["heal"] = random.randint(2,10)
sniper["block"] = 5
tank = {}
tank["health"] = 200
tank["damage"] = random.randint(2,8)
tank["heal"] = random.randint(5,20)
tank["block"] = 20
def start():
print "lets play"
while clas():
pass
while game():
pass
win()
#get the class of the player
def clas():
while True:
Class = raw_input("choose a class:\nsniper = 1\ntank =2\n") #change as stats are added
try:
Class = int(Class)
if Class in (1,2): #change as stats are added
Class1 = random.randint(1,2)
#get the class' stats for the player
if Class == 1:
player_health = sniper["health"]
player_damage = sniper["damage"]
player_heal = sniper["heal"]
player_block = sniper["block"]
if Class == 2:
player_health = tank["health"]
player_damage = tank["damage"]
player_heal = tank["heal"]
player_block = tank["block"]
#get the class' stats for the ai
if Class1 == 1:
ai_health = sniper["health"]
ai_damage = sniper["damage"]
ai_heal = sniper["heal"]
ai_block = sniper["block"]
if Class1 == 2:
ai_health = tank["health"]
ai_damage = tank["damage"]
ai_heal = tank["heal"]
ai_block = tank["block"]
break
except ValueError:
pass
print "Oops! I didn't understand that. Please enter a valid number"
In the above code, there is a function called clas(). In that function, there are 8 variables about the player and ai stats. I want those variables to copy to the variables at lines 10-18, but I'm not sure how.
In general to copy value of any variable use copy.deepcopy function:
from copy import deepcopy
z = 1
x = {'a': {'z': 12}}
def copy_args(z, x):
copy_z = deepcopy(z)
copy_x = deepcopy(x)
return copy_z, copy_x
copy_z, copy_x = copy_args(z, x)
print(copy_z, copy_x)
See more on python-course deepcopy article and python copy module documentation
Good Luck

raw_input() equivalent in cocos2d for Python

I'm building a simple game in cocos2d-0.6.0, and can't figure out how to let the player enter text for a username or other preferences.
I've found only a few examples, like the one here, but it isn't quite what I'm looking for. My attempt is below; I used the handling_events.py to try update_text, but it just strings together a list of letters separated by commas.
The ultimate goal is to be able to use a label to pose a question ("What is your name?") and then have the user type a response that will get stored as a variable I can access later (to display on following scenes on a high-score list, for example). Let me know if I can clarify my question.
class Settings(cocos.layer.ColorLayer):
is_event_handler = True
def __init__(self):
super(Settings, self).__init__(0,0,0,255)
label = cocos.text.Label('Pick a name:',
font_name='Courier',
font_size=32,
anchor_x='center', anchor_y='center')
label.position = 320,650
self.add(label )
self.text = cocos.text.Label("", x=100, y=280)
self.keys_pressed = set()
self.update_text()
self.add(self.text)
Here is the problem. I don't want to just collect a list of letters and symbols like A,G,T,SEMICOLON.
def update_text(self):
key_names = [pyglet.window.key.symbol_string(k) for k in self.keys_pressed]
text = 'Keys: ' + ','.join(key_names)
# Update self.text
self.text.element.text = text
This is optional; it transitions the settings page onto the main gameplay page.
def on_key_press(self, k, m):
if k == key.ENTER:
director.replace(FadeTransition(
main_scene, 1))
else:
self.keys_pressed.add(k)
self.update_text()
if __name__ == "__main__":
cocos.director.director.init(height = 690, width = 640)
settings_scene = cocos.scene.Scene(settings)
cocos.director.director.run(settings_scene)
Perhaps you were looking for something like this. The only downside is that it's all caps right now:
import cocos
import pyglet
class Settings(cocos.layer.ColorLayer):
is_event_handler = True
def __init__(self):
super(Settings, self).__init__(0,0,0,255)
label = cocos.text.Label('Pick a name:',
font_name='Courier',
font_size=32,
anchor_x='center', anchor_y='center')
label.position = 320,650
self.add( label )
self.text = cocos.text.Label("", x=100, y=280)
self.keys_pressed = ""
self.update_text()
self.add(self.text)
def update_text(self):
# Update self.text
self.text.element.text = self.keys_pressed
def on_key_press(self, k, m):
if k == pyglet.window.key.ENTER:
print "You Entered: {}".format(self.keys_pressed)
# cocos.director.director.replace(FadeTransition(main_scene, 1)) # disabled for testing
cocos.director.director.scene.end() # added for testing
else:
kk = pyglet.window.key.symbol_string(k)
if kk == "SPACE":
kk = " "
if kk == "BACKSPACE":
self.keys_pressed = self.keys_pressed[:-1]
else:
# ignored_keys can obviously be expanded
ignored_keys = ("LSHIFT", "RSHIFT", "LCTRL", "RCTRL", "LCOMMAND",
"RCOMMAND", "LOPTION", "ROPTION")
if kk not in ignored_keys:
self.keys_pressed = self.keys_pressed + kk
self.update_text()
if __name__ == "__main__":
cocos.director.director.init(height = 690, width = 640)
settings_scene = cocos.scene.Scene(Settings())
cocos.director.director.run(settings_scene)

Saving objects to a list python; List not updating for some reason?

Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.

update_idletasks difficulty in python tkinter

I'm having trouble calling .update_idletasks() to redraw my canvas ( at the end of the .set_up() Class-method ).
If I use self.canv.update_idletasks( self ), the canvas draws the objects I want but gives the error
TypeError: update_idletasks() takes exactly 1 argument (2 given)
If I use self.canv.update_idletasks(), the canvas remains blank but doesn't produce any errors.
from Tkinter import *
class Animation(Frame):
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.pack()
self.generation = 1
self.epoch = 1
self.set_up()
def set_up(self):
greeting_text = 'Generation ' + str(self.generation) + ', Epoch ' + str(self.epoch)
header = Label(self,text=greeting_text)
header.pack()
anframe = Frame(self,relief=SUNKEN)
anframe.pack(side='left',padx=10,pady=10)
self.canv = Canvas(anframe,width=800, height=800, bg='white') # 0,0 is top left corner
self.canv.pack(expand=YES, fill=BOTH,side='left')
buframe = Frame(self,relief=RAISED)
buframe.pack(side='right',fill=X,padx=10,pady=5)
start = Button(buframe,text='START',width=10,command=self.animate)
start.pack(expand=YES,fill=BOTH,side='top')
back = Button(buframe,text='Back',width=10)
back.pack(expand=YES,fill=BOTH,side='bottom')
nextgo= Button(buframe,text='Next',width=10)
nextgo.pack(expand=YES,fill=BOTH,side='bottom')
path = 'C:/Desktop/LearnNet/' + str(self.generation) + '_' + str(self.epoch) + '.txt'
data = open(path,'r')
lines = data.readlines()
food,moves = [],[]
for item in lines:
if item.strip() == 'f':
dat_type = 1
continue
elif item.strip() == 'a':
dat_type = 2
continue
if dat_type == 1:
temp = item.strip()
temp = item.split()
food.append([int(temp[0]),int(temp[1])])
if dat_type == 2:
temp = item.strip()
temp = item.split()
moves.append([int(temp[0]),int(temp[1]),int(temp[2])])
photos = []
for i in xrange(len(food)):
temp=PhotoImage(file='C:/Desktop/LearnNet/Food.gif')
photos.append(temp)
self.canv.create_image(food[i][0]*20,food[i][1]*20,image=photos[i],anchor=NW)
start_pos = moves[0]
picpath = self.orientation(start_pos[2])
animal = PhotoImage(file=picpath)
self.canv.create_image(moves[0][0]*20,moves[0][1]*20,image=animal,anchor=NW)
self.canv.update_idletasks(self)
def animate(self):
return 1
def orientation(self,angle):
if angle == 0:
picpath = 'C:/Desktop/LearnNet/PEast.gif'
elif angle == 90:
picpath = 'C:/Desktop/LearnNet/PNorth.gif'
elif angle == 180:
picpath = 'C:/Desktop/LearnNet/PWest.gif'
else:
picpath = 'C:/Desktop/LearnNet/PSouth.gif'
return picpath
if __name__ == '__main__': Animation().mainloop()
self in python is actually syntactic sugar.
In other words, when you say self.animate(), python translates it to Animation.animate(self). That's why you define the class methods with that "self" argument -- it's passed implicitly.
self.canv.update_idletasks(self) is evaluating to something like Canvas.update_idletasks(self.canv, self).
I found a solution by looking at some similar code. self.canv.get_tk_widgets().update_idletasks() does the trick, thought I am not quite sure WHY this works, If anyone could explain or point me to some reading. Thanks

Categories

Resources