import bge
import random


        
def bird(cont):
    own = cont.owner
    if 'inited' not in own:
        own.worldPosition = own['start'].worldPosition
        own['inited'] = True        
        act = cont.actuators['Steering']
        act.target = own['end']
        act.velocity = 2
        cont.activate(act)
        #print('doing bird')
    if own.getDistanceTo(own['end']) < 1:
        own.endObject()
        #print('kill bird') 

def main(cont, scene):

    def build_bird_list(scene,own):
        own['bird_list'] = []
        for x in scene.objects:
            if 'bird_target' in x.name:
                own['bird_list'].append(x)
                
    def do_birds(scene, own, cont):
        
        if own['life'] % 50 == 0:
            num = random.randint(0,2)
            if num == 1:
                #print('add bird')
                top = len(own['bird_list']) - 1
                start = random.randint(0, top)
                end = start
                while end == start:
                    end = random.randint(0, top)
                obj = scene.addObject('bird_cont', own['bird_list'][start], 0)                
                obj['start'] = own['bird_list'][start]
                obj['end'] = own['bird_list'][end]
                obj.worldPosition = obj['start'].worldPosition
                #print(obj['start'], obj['end'])
            
    def life(own):
        if 'life' in own:
            own['life'] += 1     
        else:
            own['life'] = 0    
        
  

    own = cont.owner
    if 'binited' not in own:
        build_bird_list(scene, own)            
        own['binited'] = True

    life(own)    
    do_birds(scene, own, cont)  
    #print('birding')    