Problem with variable assignment.

edited February 2018 in Python Mode

Hello Guys,

I ran into a Problem when i tried to convert a Program from JS to Python.

My Problem: I assign a variable count = 0 before the setup() In draw() i want to increase this variable by a given amount but i get a "local variable 'count' referenced before assignment" Error. Maybe i am blind to a Bug in my code.

Thanks for the help.

from branch import Branch

tree = []
leaves = []
count = 0

def setup():
    a = PVector(width/2, height)
    b = PVector(width/2, height - 100)
    global root
    root = Branch(a,b)

def draw():

    if (keyPressed == True):        
        for i in range(len(tree)):
            if (tree[i].finished == False):
            tree[i].finished = True
        count += 1

    # if (count == 6):
    #     for i in range(len(tree)):
    #         if (tree[i].finished == False):
    #             leaf = tree[i].end.copy()
    #             leaves.append(leaf)
    #     for i in range(len(leaves)):
    #         fill(255,0,100)
    #         ellipse(leafes[i].x,leafes[i].y, 8 ,8)

    for i in tree:

class Branch(object):
    def __init__(self, startpos,endpos):
        self.startpos = startpos
        self.endpos = endpos
        self.finished = False

    def show(self):
        line(self.startpos.x,self.startpos.y, self.endpos.x, self.endpos.y)

    def branchA(self):
        dir = PVector.sub(self.endpos, self.startpos)
        newEnd = PVector.add(self.endpos, dir)

        right = Branch(self.endpos, newEnd)
        return right

    def branchB(self):
        dir = PVector.sub(self.endpos, self.startpos)
        dir.rotate((PI/4) * (-1))
        newEnd = PVector.add(self.endpos, dir)

        left = Branch(self.endpos, newEnd)
        return left

Edit found the right way to format the codeblock


  • Answer ✓

    Not super up to date on the Python Mode myself, but I suspect that you need to mention global count in your draw() function to use the global count variable...?

  • Ah thanks a lot. That worked.

Sign In or Register to comment.