Cocos2d: AttributeError: 'Director' object has no attribute '_window_virtual_width' - python

We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'

You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()

I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.

Related

Object not callable in python class in flask application

This is my first flask application and i tried my best to get it running. Nevertheless i stuck into one error.
I tried to create a python flask app but stuck into an error.
here is my code
flask.py
from test_displayclass import Bartender
class MyFlask:
bartender = Bartender()
def __init__(self):
#self.bartender = Bartender()
self.bartender.test()
from flask import Flask
app = Flask(__name__)
my_flask = MyFlask()
#app.route("/Test")
def Test():
return my_flask.test.APIfunction
if __name__ == "__main__":
app.run(debug=True,port=9999)
test_displayclass.py
import adafruit_ssd1306
import busio
from board import SCL, SDA
from PIL import Image, ImageDraw, ImageFont
class Display():
def __init__(self):
i2c = busio.I2C(SCL, SDA)
self.oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
self.oled.fill(0)
self.oled.show()
def drawImage(self, image):
self.oled(image)
self.oled.show()
class Bartender():
def __init__(self):
self.oled = Display()
def test(self):
image = Image.new("1", (20, 20))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 25)
self.len = len("e")
draw.text(
(0, 40 - 2 // 2),
"e",
font=font,
fill=255,
)
Error is:
Traceback (most recent call last):
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 13, in <module>
my_flask = MyFlask()
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 8, in __init__
self.bartender.test()
File "/home/pi/Smart-Bartender/test_displayclass.py", line 61, in test
self.oled.drawImage(image)
File "/home/pi/Smart-Bartender/test_displayclass.py", line 33, in drawImage
self.oled(image)
TypeError: 'SSD1306_I2C' object is not callable
Can you advice me how to do it the correct waY?
Need of taken the function self.oled.image(image)

Failing to load model using multiprocessing on windows

This program works on Unix and I'm trying to transition it to windows.
It uses multiprocessing and I understand it's an issue with being forced to use spawning on windows opposed to forking on linux for multiprocessing.
It's to do with the subprocess loading the models that I load on the main thread.
When Consumer() is called, during the init() it calls a function from another file that loads some tensorflow models.
Consumer()
import os
import time
import sys
from PIL import Image
import subprocess
from multiprocessing import Process, Queue
import t2identify
class Consumer:
def __init__(self, frameSource, layer):
self.directory = os.environ["directory"]
self.source = frameSource
self.task = layer
if layer == "screen":
self.layer = t2identify.identifyImage("apps")
elif layer == "detail":
self.layer = "detail"
self.imagesChecked = 0
self.errorsFound = 0
self.previousApp = "none"
self.appDetail = {
"mobile": t2identify.identifyImage("mobile"),
}
def start(self, state, queue):
self.state = state
consumer1 = Process(target=self.consumeImage, args=(queue,))
consumer1.start()
consumer2 = Process(target=self.consumeImage, args=(queue,))
consumer2.start()
consumer1.join()
consumer2.join()
t2identify.identifyImage() involves loading models.
t2identify.py
import matplotlib.pyplot as plt
import numpy as np
import os
from PIL import Image
class identifyImage():
def __init__(self, layer):
import tensorflow as tf
availableLayers = {
"apps":"C:/Users/PycharmProjects/NNs/tf/appModel",
}
self.selectedLayer = availableLayers[layer]
self.model = tf.saved_model.load(self.selectedLayer)
self.label = self.loadLabels(availableLayers[layer]+"/labels.txt")
self.img_height = 224
self.img_width = 224
...
I'm confident the issue is when the consumer subprocess starts, the models that are loaded here are loaded again, why it says they're not found I'm not sure.
main.py
import pathos
import multiprocessing
import os
import time
import shutil
from os import path
from producer import Producer
from consumer import Consumer
from controller import Controller
from tqdm import tqdm
import re
import sys
from env import environmentVariables as Environment
class Main:
def start(self, test):
self.createDirectories()
screenQueue = multiprocessing.Queue()
detailQueue = multiprocessing.Queue()
self.producer = Producer(["SavedFrames", "ScreenFrames", "DetailFrames", "VisualFrames"])
self.producerProcess = multiprocessing.Process(target=self.producer.start,
args=(self.producerEvent, self.producerFrameRate, self.state,
self.expected, self.iteration, self.testCaseNumber,
[screenQueue, detailQueue]))
self.screenConsumer = Consumer("ScreenFrames", "screen")
# MODELS ARE LOADED
self.detailConsumer = Consumer("DetailFrames", "detail")
self.screenConsumerProcess = multiprocessing.Process(target=self.screenConsumer.start,
args=(self.state, screenQueue))
self.detailConsumerProcess = multiprocessing.Process(target=self.detailConsumer.start,
args=(self.state, detailQueue))
try:
# Set the new thread to run the controller which performs the test cases
self.controllerStart = Controller(self.producerEvent, self.producerFrameRate, self.state, self.expected, self.iteration,
self.testCaseNumber, self.progress)
self.controllerProcess = multiprocessing.Process(target=self.controllerStart.start, args=(test,))
except:
print("ERROR")
return False
self.producerProcess.start()
# FAILS on starting screenConsumerProcess (see error)
self.screenConsumerProcess.start()
self.detailConsumerProcess.start()
self.controllerProcess.start()
self.producerProcess.join()
self.screenConsumerProcess.join()
self.detailConsumerProcess.join()
self.controllerProcess.join()
self.zipFiles()
self.sendLogs()
return True
...
if __name__ == "__main__":
testing = Main()
results = testing.start()
The error:
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
File "\venv\lib\site-packages\keras\saving\pickle_utils.py", line 48, in deserialize_model_from_bytecode
model = save_module.load_model(temp_dir)
File "\venv\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
Traceback (most recent call last):
File "C:/Users/PycharmProjects/project/src/main.py", line 353, in <module>
raise e.with_traceback(filtered_tb) from None
File "\venv\lib\site-packages\tensorflow\python\saved_model\load.py", line 978, in load_internal
results = testing.start(data)
File "/PycharmProjects/project/src/main.py", line 95, in start
self.screenConsumerProcess.start()
File "\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
str(err) + "\n You may be trying to load on a different device "
FileNotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram://4e4e1c18-ece9-4d99-88c3-5c2ee965c92a/variables/variables
You may be trying to load on a different device from the computational device. Consider setting the `experimental_io_device` option in `tf.saved_model.LoadOptions` to the io_device such as '/job:localhost'.
The models that are loaded aren't accessable by subprocesses. As ram://4e4e1c18-ece9-4d99-88c3-5c2ee965c92a/variables/variables is temp_dir in keras/pickle_utils.py model = save_module.load_model(temp_dir). Which is where the error occured.
Am I running out of ram? Or do I need to change some multiprocessing code now that I'm on windows.
EDIT:
I suspect it's most likely to do with windows reimporting everything once a new process starts (spawning). While doing this, the models are reloaded, and that's where the error occurs. I am still however unsure how to go about resolving this, apart from loading the models in main then passing the models into the subprocesses as parameters... which seems like a subpar solution.
EDIT2:
Now looking into using pathos which uses dill and not pickle. As I suspect the issue is with when I start the consumer process, the target is a class, which is not pickleable.
To avoid pickling of the tensorflow models, try moving the creation of these models to the process that uses them:
class Consumer:
def __init__(self, frameSource, layer):
self.directory = os.environ["directory"]
self.source = frameSource
self.task = layer
self._layer = layer
# The following code is moved to the consumeImage method:
"""
if layer == "screen":
self.layer = t2identify.identifyImage("apps")
elif layer == "detail":
self.layer = "detail"
"""
self.imagesChecked = 0
self.errorsFound = 0
self.previousApp = "none"
# The following code is moved to consumeImage:
"""
self.appDetail = {
"mobile": t2identify.identifyImage("mobile"),
}
"""
def start(self, state, queue):
self.state = state
consumer1 = Process(target=self.consumeImage, args=(queue,))
consumer1.start()
consumer2 = Process(target=self.consumeImage, args=(queue,))
consumer2.start()
consumer1.join()
consumer2.join()
def consumeImage(self, queue):
self.appDetail = {
"mobile": t2identify.identifyImage("mobile"),
}
if self._layer == "screen":
self.layer = t2identify.identifyImage("apps")
elif self._layer == "detail":
self.layer = "detail"
...

Reading higher frequency data in thread and plotting graph in real-time with Tkinter

In the last couple of weeks, I've been trying to make an application that can read EEG data from OpenBCI Cyton (#250Hz) and plot a graph in 'real-time'. What seems to work better here are threads. I applied the tips I found here 1 to communicate the thread with Tkinter, but the application still doesn't work (gives me the error RecursionError: maximum recursion depth exceeded while calling a Python object). Maybe I'm doing something wrong because I'm trying to use multiple .py files? See below the main parts of my code and a few more comments in context:
###FILE main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from AppWindow import *
window = AppWindow()
window.start()
###FILE AppWindow.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
import scroller as scrl
import logging
import requests
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import random
from pandas import DataFrame
import stream_lsl_eeg as leeg
#Definitions
H = 720
W = 1280
#Color palette>> https://www.color-hex.com/color-palette/92077
bg_color = "#c4ac93"
sc_color = "#bba58e"
tx_color = "#313843"
dt_color = "#987f62"
wn_color = "#6b553b"
class AppWindow:
#Other Functions
def plotGraph(self, x, y):
self.ax.clear()
self.ax.plot(x,y, color = tx_color)
plt.subplots_adjust(bottom=0.31, left=0.136, top=0.9, right=0.99)
plt.ylabel('Magnitude', fontsize = 9, color = tx_color)
plt.xlabel('Freq', fontsize = 9, color = tx_color)
self.figure.canvas.draw()
def __init__(self):
self.root = tk.Tk() #start of application
self.root.wm_title("Hybrid BCI - SSVEP and Eye Tracker")
#Other Graphical Elements
#Button that calls function
self.btn_ReceiveEEG = tk.Button(self.EEG_frame, text = "Receive EEG signal", bg = bg_color, fg = tx_color, state = tk.DISABLED, command = lambda: leeg.getEEGstream(self))
self.btn_ReceiveEEG.place(anchor = 'nw', relx = 0.52, rely = 0.5, width = 196, height = 40)
#Other Graphical Elements
def start(self):
self.root.mainloop() #end of application
### FILE stream_lsl_eeg.py
from pylsl import StreamInlet, resolve_stream
import tkinter as tk
import AppWindow as app
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import threading
import queue
import time
class myThread(threading.Thread):
def __init__(self, name, q, f):
threading.Thread.__init__(self)
self.name = name
self.q = q
self.f = f
def run(self):
print("Starting ", self.name)
pullSamples(self.q, self.f) #place where function is called
def getInlet(app): #this is triggered by another button and it's working fine
global inlet
app.logger.warn('Looking for an EEG strean...')
streams = resolve_stream('type', 'EEG')
inlet = StreamInlet(streams[0])
app.logger.warn('Connected')
app.btn_ReceiveEEG.config(state = tk.NORMAL)
def pullSamples(q):
i = 0
while i<1000:
sample, timestamp = inlet.pull_sample()
threadLock.acquire() #thread locks to put info in the queue
q.put([sample,timestamp]) #data is put in the queue for other threads to access
threadLock.release() #thread unlocks after info is in
i += 1
stopcollecting = 1
print("Exit flag on")
def plotSamples(app, kounter): #Outside Thread
if not stopcollecting: #testing if stream reception stopped
while dataqueue.qsize( ):
try:
kounter += 1
sample, timestamp = dataqueue.get(0)
samples.append(sample[0]) #getting just channel 1 (0)
timestamps.append(timestamp)
show_samples = samples[-250:]
show_timestamps = timestamps[-250:]
app.plotGraph(show_timestamps,show_samples)
print(counter) #this was just a control to count if the right amount of samples was coming out of the queue
except dataqueue.Empty:
pass #still not implemented, but will return to the main application
app.root.after(60, plotSamples(flag,app,kounter)) #60 chosen because plot should update every 15 samples (15/250 = 0,06s)
def getEEGstream(app): #function called by button
app.logger.warn('Starting thread...')
#
kounter = 0
start = time.perf_counter()
thread1.start()
##
plotSamples(flag, app, kounter)
##
thread1.join() #I don't know if I need this...
finish = time.perf_counter()
#
print(f'Sizes: Samples [{len(samples)}, {len(samples[0])}], {len(timestamps)} timestamps')
print(f'Sucessfully streamed in {round(finish-start,3)}s!')
###
threadLock = threading.Lock()
dataqueue = queue.Queue()
stopcollecting = 0
kounter = []
flag = queue.Queue() #secondary queue for flags not used at the moment
flag.put(0)
thread1 = myThread("Thread-1", dataqueue,flag)
samples,timestamps = [],[]
show_samples, show_timestamps = [],[]
As I found here 2, a function should not call itself, but it's basically what here 1 does. Also, I don't think I'm calling root.mainloop() multiple times like done in here 3.
After executing, python gives me the following error/output:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robotics\AppData\Local\Continuum\anaconda3\envs\psychopy\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\robotics\Documents\gitDocuments\SSVEP_EyeGaze_py\AppWindow.py", line 109, in <lambda>
self.btn_ReceiveEEG = tk.Button(self.EEG_frame, text = "Receive EEG signal", bg = bg_color, fg = tx_color, state = tk.DISABLED, command = lambda: leeg.getEEGstream(self))
File "C:\Users\robotics\Documents\gitDocuments\SSVEP_EyeGaze_py\stream_lsl_eeg.py", line 118, in getEEGstream
plotSamples(flag, app, kounter)
File "C:\Users\robotics\Documents\gitDocuments\SSVEP_EyeGaze_py\stream_lsl_eeg.py", line 104, in plotSamples
app.root.after(60, plotSamples(flag,app,kounter))
File "C:\Users\robotics\Documents\gitDocuments\SSVEP_EyeGaze_py\stream_lsl_eeg.py", line 104, in plotSamples
app.root.after(60, plotSamples(flag,app,kounter))
File "C:\Users\robotics\Documents\gitDocuments\SSVEP_EyeGaze_py\stream_lsl_eeg.py", line 104, in plotSamples
app.root.after(60, plotSamples(flag,app,kounter))
[Previous line repeated 986 more times]
File "C:\Users\robotics\Documents\gitDocuments\SSVEP_EyeGaze_py\stream_lsl_eeg.py", line 92, in plotSamples
while dataqueue.qsize( ): # if not dataqueue.empty():
File "C:\Users\robotics\AppData\Local\Continuum\anaconda3\envs\psychopy\lib\queue.py", line 87, in qsize
with self.mutex:
RecursionError: maximum recursion depth exceeded while calling a Python object
Exit flag on
This means the thread is being successfully executed, apparently, but the plotSamples() is crashing.
Any advice??
after() (similar to button's command= and bind()) needs function's name without () and without argument - it is called callback - and after sends it to mainloop and mainloop later uses () to run it.
You use function with ()
app.root.after(60, plotSamples(flag,app,kounter))
so it runs it at once (it doesn't send it to mainloop) and this function runs at once again the same function which runs at once the same function, etc. - so you create recursion.
It works like
result = plotSamples(flag,app,kounter) # run at once
app.root.after(60, result)
If you have to use function with arguments then you can do
app.root.after(60, plotSamples, flag, app, kounter)
Eventually you can use lambda to create function without argument
app.root.after(60, lambda:plotSamples(flag,app,kounter) )

Attribute Error. Can not access attributes in Class

I'm trying to call a class Pager in my main function in Python. When I run the program it gives me an error:
Traceback (most recent call last): File "lab4.py", line 113, in <module>
main() File "lab4.py", line 34, in main
demandPager.processRef(p, clock, rand) File "/Users/kiranbhimani/Desktop/OSLab4/Pager.py", line 16, in processRef
desiredPage = Pager.frameTable.findPageById(testId, process.getProcessId())
**AttributeError: class Pager has no attribute 'frameTable'**
How can I access frameTable? If I insert "self" as a parameter, I can't call the class. It says processRef requires 4 arguments but only 3 are given.
I'm not sure what is going on here. Thank you in advance!
class Pager:
def __init__(self, machineSize, pageSize):
self.machineSize = machineSize
self.pageSize = pageSize
self.frameTable = FrameTable(int(machineSize/pageSize))
#staticmethod
def processRef(process, clock, randreader):
ref = int(process.currentReference)
testId = int(ref / Page.size)
#print Pager.machineSize
desiredPage = Pager.frameTable.findPageById(testId, process.getProcessId())
if (isHit(desiredPage, process)):
desiredPage.addRefdWord(ref)
else:
if (not frameTable.isFull()):
frameTable.addPage(process, testId, ref)
else:
pageToEvict = findPageToReplace(replacementAlgo, randreader)
frameTable.evictPage(pageToEvict)
frameTable.addPage(process, testId, ref)
desiredPage = frameTable.lastPageAdded
desiredPage = frameTable.lastPageAdded
desiredPage.setIfLoaded(true)
process.incrNumPageFaults()
desiredPage.timeLastUsed = clock
frameTable.updateTimes()
This is the main function:
from Process import Process
from Page import Page as Page
from Pager import Pager
from FrameTable import FrameTable
import sys
runningProcesses = []
finishedProcesses = []
def main():
#read input
machineSize = int(sys.argv[1])
pageSize = int(sys.argv[2])
processSize = int(sys.argv[3])
jobMix = int(sys.argv[4])
numOfRefPerProcess = int(sys.argv[5])
replacementAlgo = (sys.argv[6])
demandPager = Pager(machineSize, pageSize)
Page.size = pageSize
Process.size = processSize
setProc(jobMix)
demandPager.replacementAlgo = replacementAlgo
index = 0
clock = 0
while(len(runningProcesses) > 0):
p = runningProcesses[index]
for i in range(3):
demandPager.processRef(p, clock, rand)
p.setCurrentReference(p.calcNextReference(rand))
p.incrRefsMade()
clock+=1
if (p.getRefsMade() == numRefPerProcess):
finishedProcesses.add(p)
runningProcesses.remove(p)
index-=1
break
if (index == numProcesses-1):
index = 0
else:
index+=1
print "printing....."
printOutput(args)
You tried to access a class property frameTable, but this class has no added properties at all. Objects of the class have properties of machineSize, FrameSize, and pageTable -- that's one of each for every object you instantiate.
For instance, there will be a demandPager.frameTable once you hit the creation command, but you haven't given any properties (other than the built-ins) to Pager as a class.
Perhaps you want to use self
desiredPage = self.frameTable.findPageById(testId, process.getProcessId())

Python + Pyglet Cocos2D: TypeError: 'class' object is not callable

I've been working on a tiled map renderer, and I've tried to make a seperate Class in another file. I get this error message:
Type Error: 'renderer' object is not callable
Here's the render.py file:
import pyglet, json
from pyglet.window import key
from pyglet.gl import *
from ConfigParser import SafeConfigParser
from cocos.layer import *
from cocos.batch import *
from cocos.sprite import Sprite
class renderer( Layer ):
def __init__(self, mapname):
super( renderer, self ).__init__()
parser = SafeConfigParser()
try:
world = parser.read('maps/'+mapname+'.txt')
print world
except IOError:
print("No world file!")
return
layer = json.loads(parser.get('layer1', 'map'))
tiletype = parser.get('type', 'tile')
print tiletype
tilesize = 64
for x in range(0, len(layer)):
for y in range(0, len(layer[x])):
self.spr = Sprite("image/tiles/"+tiletype+"/"+str(layer[x][y])+".png")
self.spr.position = ((x+1)*tilesize, (y+1)*tilesize)
self.add(self.spr)
And this is the piece of code I call it with:
from other.render import renderer
 
world = renderer('buildnew')
world()
File Structure:
game/main.py
game/other/render.py
What am I doing wrong?
world = renderer('buildnew')
world()
First you make an instance of the renderer class and store it to world.
But then you write world(), which is wrong cause this object is not callable.
If you want to make world a callable object, you should implement the __call__ method in the renderer class.

Categories