I have 2 classes that do extremely similar things. The only differences are that they draw using different colors, and that one draws in the back.
The classes NeuronOutput
and NeuronReciever
are very similar.
class NeuronOutput():
"""The place where a Neuron outputs its signal"""
def __init__(self,neuron):
self.neuron=neuron
width=self.neuron.width*0.5
offset=width/2
distance=self.neuron.width*0.4
self.pos=[self.neuron.x+math.sin(self.neuron.angle)*distance,self.neuron.y-math.cos(self.neuron.angle)*distance]
self.drawRect=[self.pos[0]-offset,self.pos[1]-offset,width,width]
def draw(self,surf):
pygame.draw.ellipse(surf,[200,150,200],self.drawRect)
class NeuronReciever():
"""Where a Neuron recieves input"""
def __init__(self,neuron):
self.neuron=neuron
width=self.neuron.width*0.5
offset=width/2
distance=self.neuron.width*0.4
self.pos=[self.neuron.x-math.sin(self.neuron.angle)*distance,self.neuron.y+math.cos(self.neuron.angle)*distance]
self.drawRect=[self.pos[0]-offset,self.pos[1]-offset,width,width]
def draw(self,surf):
pygame.draw.ellipse(surf,[200,255,200],self.drawRect)
There is also a class Neuron
that uses instances of the two above classes as properties. It is also fairly similar to them, however it is a bit different in the way it initializes and draws.
class Neuron():
"""A single neuron with Synapses that connect to others"""
def __init__(self,x,y):
self.x=x
self.y=y
self.pos=[x,y]
self.width=30
self.drawOffset=self.width/2;
self.connections=[]
self.angle=math.radians(random.randint(0,360))
self.drawRect=[self.x-self.drawOffset,self.y-self.drawOffset,self.width,self.width]
self.output=NeuronOutput(self)
self.input=NeuronReciever(self)
def draw(self,surf):
pygame.draw.ellipse(surf,[200,150,50],self.drawRect)
self.output.draw(surf)
self.input.draw(surf)
self.syn.draw(surf)
(The code is the beginning of a neuron simulation.)
I want to keep all these as separate classes for the sake of readability and ease of use. How can I reduce the repetitiveness of this code, while still keeping it readable?