def JournaliseRingScans():
    cspace = Bubble().systems
    print('Extract Scans to fakejournal')

    cutoffdate = SpanshDateTime('2020-06-09 07:00:00+00') # When Tritium was implemented
    rings = list()
    ringmaster = list()
    for sys in cspace:
        for body in sys['bodies']:
            for ring in body.get('rings',[]):
                ringmaster.append([ring['name'], sys['name'],f"{ring['type']} - Pristine", body['distanceToArrival']])        
                signals = list()
                if 'signals' in ring and cutoffdate < SpanshDateTime(ring['signals']['updateTime']): ## Updated Date/Time is here to ignore pre-Trit values
                    for signal in ring['signals']['signals'].items(): # Is a Dict, convert to a list
                        signals.append({'Type':signal[0], 'Count':signal[1]})
                    print(ring['name'])
                    rings.append({'event': 'SAASignalsFound', 'BodyName': ring['name'], 'type': f"{ring['type']} - Pristine", 'Signals':signals})

    with open('data\\bubble_canonn_rings.csv','w', newline = '') as rfile:
        writer = csv.writer(rfile)
        writer.writerows(ringmaster)

    JournalDump(f'{JFOLDER}\\fakejournal.log',rings)    # Write to ED Journal Folder
    JournalDump(f'data\\fakejournal.log',rings)         # Write to Local
    return None
Exemple #2
0
def create_bubbles():# from here to...
    bubble_x = initial_bubble_position
    bubble_y = initial_bubble_position

    for rows in range(0, 3):
        for columns in range(0, 10):
            bubble = Bubble(bubble_x, bubble_y)
            bubble_group.add(bubble)
            bubble_x += bubble_spacing
        bubble_y += bubble_spacing
        bubble_x = initial_bubble_position
Exemple #3
0
def startScreen():

    intro = True
    bubble_sprites_list = pygame.sprite.Group()
    for i in range(0, 50):
        bubble_sprites_list.add(
            Bubble(WHITE, 5, [
                rand.randint(width / 4, 3 * width / 4),
                rand.randint(height / 4, 3 * height / 4)
            ], width, height))

    while (intro):
        screen.fill(BLACK)

        font = pygame.font.Font(None, 100)
        text = font.render("PONG", 1, WHITE)
        screen.blit(text, (250, 10))

        pygame.draw.rect(screen, BLACK, (225, 150, 250, 50))
        pygame.draw.rect(screen, BLACK, (225, 250, 250, 50))
        pygame.draw.rect(screen, BLACK, (225, 350, 250, 50))

        # Draw the rectangles which will hold the game options
        font = pygame.font.Font(None, 35)
        text = font.render("Player vs Computer", 1, WHITE)
        screen.blit(text, (235, 175, 250, 50))

        # Draw the rectangles which will hold the game options
        font = pygame.font.Font(None, 35)
        text = font.render("Player vs Player", 1, WHITE)
        screen.blit(text, (250, 264, 250, 50))

        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONUP:
                mouse_pos = pygame.mouse.get_pos()

                if (475 > mouse_pos[0] > 225 and 200 > mouse_pos[1] > 150):
                    isHumanPlaying = False
                    isComputerPlaying = True

                if (475 > mouse_pos[0] > 225 and 300 > mouse_pos[1] > 250):
                    isHumanPlaying = True
                    isComputerPlaying = False

                gameloop(isHumanPlaying, isComputerPlaying)
                break

        bubble_sprites_list.update()

        bubble_sprites_list.draw(screen)

        pygame.display.flip()

        clock.tick(15)
Exemple #4
0
def create_bubbles():
    bubble_x = initial_bubble_position
    bubble_y = initial_bubble_position
    for rows in range(0, 3):
        for columns in range(0, 10):
            bubble = Bubble(bubble_x - 30, bubble_y)
            bubble_group.add(bubble)
            bubble_x += bubble_spacing
            all_bubbles.append(bubble)
        bubble_y += bubble_spacing
        bubble_x = initial_bubble_position
from Map import Map
from Bubble import Bubble

if __name__ == "__main__":

    map = Map()
    bubble = Bubble()

    map.create_map("heat")
    map.create_map("marker")

    bubble.create_bubble()
Exemple #6
0
class methods:
    def __init__(self, fps, clockObject, surface, font, bars, windowsize):
        self.fps = fps
        self.clock = clockObject
        self.surface = surface
        self.font = font
        self.bars = bars
        self.windowsize = windowsize

    def get_array(self, length, mode=0):
        arr = list(range(length))

        if not mode:
            random.shuffle(arr)
        elif mode == 2:
            arr = arr[::-1]
        elif mode == 3:
            for i in range(length - 1):
                if random.randint(0, 10) < 8:
                    tmp = random.randint(4, 15)
                    try:
                        arr[i], arr[i + tmp] = arr[i + tmp], arr[i]
                    except:
                        pass

        return arr

    def setup(self, length, mode=0):
        self.array = self.get_array(length, mode)

        self.display = Display(self.windowsize[0] / length, self.windowsize,
                               self.surface, self.font)
        self.accesses = 0
        self.comparisons = 0

        setattr(self.display, "bars", self.bars)

    bubble = lambda self: Bubble(self.array, self.display, self.clock, self.fps
                                 ).main()
    quicksort = lambda self: Quicksort(self.array, self.display, self.clock,
                                       self.fps).main()
    selection = lambda self: Selection(self.array, self.display, self.clock,
                                       self.fps).main()
    cocktail = lambda self: Cocktail(self.array, self.display, self.clock, self
                                     .fps).main()
    bogo = lambda self: Bogo(self.array, self.display, self.clock, self.fps
                             ).main()
    oddeven = lambda self: Oddeven(self.array, self.display, self.clock, self.
                                   fps).main()
    shell = lambda self: Shell(self.array, self.display, self.clock, self.fps
                               ).main()
    comb = lambda self: Comb(self.array, self.display, self.clock, self.fps
                             ).main()
    insertion = lambda self: Insertion(self.array, self.display, self.clock,
                                       self.fps).main()
    mergetd = lambda self: MergeTD(self.array, self.display, self.clock, self.
                                   fps).main()
    radixlsd = lambda self: RadixLSD(self.array, self.display, self.clock, self
                                     .fps).main()
    counting = lambda self: Counting(self.array, self.display, self.clock, self
                                     .fps).main()
    cycle = lambda self: Cycle(self.array, self.display, self.clock, self.fps
                               ).main()
    heap = lambda self: Heap(self.array, self.display, self.clock, self.fps
                             ).main()
    circle = lambda self: Circle(self.array, self.display, self.clock, self.fps
                                 ).main()
    gnome = lambda self: Gnome(self.array, self.display, self.clock, self.fps
                               ).main()
    binaryinsertion = lambda self: BinaryInsertion(
        self.array, self.display, self.clock, self.fps).main()
    pancake = lambda self: Pancake(self.array, self.display, self.clock, self.
                                   fps).main()
    permutation = lambda self: Permutation(self.array, self.display, self.
                                           clock, self.fps).main()
    strand = lambda self: Strand(self.array, self.display, self.clock, self.fps
                                 ).main()
    bucket = lambda self: Bucket(self.array, self.display, self.clock, self.fps
                                 ).main()
    minmax = lambda self: MinMax(self.array, self.display, self.clock, self.fps
                                 ).main()
    mergebu = lambda self: MergeBU(self.array, self.display, self.clock, self.
                                   fps).main()
    bitonic = lambda self: Bitonic(self.array, self.display, self.clock, self.
                                   fps).main()
    stooge = lambda self: Stooge(self.array, self.display, self.clock, self.fps
                                 ).main()
    smooth = lambda self: Smooth(self.array, self.display, self.clock, self.fps
                                 ).main()
    quick3 = lambda self: Quick3(self.array, self.display, self.clock, self.fps
                                 ).main()
def tela_jogo(screen):
    objetos=pygame.sprite.Group()
    grid = pygame.sprite.Group()
    player=Bubble(STARTX,STARTY,-1,-1)
    flecha=Arrow()
    objetos.add(flecha)
    objetos.add(player)
    #Cria o Score
    score=0
    fonte_score=pygame.font.Font('assets/font/PressStart2P.ttf', 20)
    bolha_b = pygame.mixer.Sound(path.join(SND_DIR, 'bolha.ogg'))
    fontev =pygame.font.Font('assets/font/FonteV.ttf',40)

    bolinhas = []
    #Cria grid das bolinhas
    for i in range(LINHAS):
        linha = []
        for j in range(COL):
            bolha=Bubble(BUBBLEHEIGHT*j+BUBBLEHEIGHT//2,BUBBLEWIDTH*i+BUBBLEWIDTH//2, i, j)
            objetos.add(bolha)
            grid.add(bolha)
            linha.append(bolha)
        bolinhas.append(linha)

    #Iníico do jogo
    game = True
    while game:
        for event in pygame.event.get():
            mouse=pygame.mouse.get_pos()
            flecha.mousex = mouse[0]
            flecha.mousey = mouse[1]
            if event.type == pygame.QUIT or event.type ==pygame.KEYUP:
                game = False
            if event.type==pygame.MOUSEBUTTONDOWN:
                player.tiro()
                player.dx=mouse[0]-player.rect.centerx
                player.dy=mouse[1]-player.rect.centery
                
        #Contato entre as bolinhas e a bolinha lançada  
        hits = pygame.sprite.spritecollide(player, grid, False,pygame.sprite.collide_circle)
        if len(hits) > 0:

            player.speed = 0
            for bolha1 in hits:
                if player.cor == bolha1.cor:
                    bolha_b.play()
                    vizinhos = [bolha1]
                    conta=1
                    while len(vizinhos) > 0:
                        vizinho = vizinhos.pop()
                        if vizinho.alive():
                            l = vizinho.linha
                            c = vizinho.coluna
                            
                            if l > 0 and bolinhas[l-1][c] is not None and bolinhas[l-1][c].cor == player.cor:
                                vizinhos.append(bolinhas[l-1][c])
                            if l < LINHAS - 1 and bolinhas[l+1][c] is not None and bolinhas[l+1][c].cor == player.cor:
                                vizinhos.append(bolinhas[l+1][c])
                            if c > 0 and bolinhas[l][c-1] is not None and bolinhas[l][c-1].cor == player.cor:
                                vizinhos.append(bolinhas[l][c-1])
                            if c < COL and bolinhas[l][c+1] is not None and bolinhas[l][c+1].cor == player.cor:
                                vizinhos.append(bolinhas[l][c+1])
                            conta+=1
                            vizinho.kill()
                            bolinhas[l][c] = None
                            
                    #Destrói bolinha sobrando 
                    for bolinha in grid:
                        l = bolinha.linha
                        c = bolinha.coluna
                        if l > 0:
                            cima = bolinhas[l - 1][c]
                            if l+1 < len(bolinhas):
                                baixo = bolinhas[l+1][c]
                            else:
                                baixo = None
                            if c > 0:
                                esquerda = bolinhas[l][c-1]
                            else:
                                esquerda = None
                            if c+1 < len(bolinhas[l]):
                                direita = bolinhas[l][c+1]
                            else:
                                direita = None
                            if cima is None and baixo is None and esquerda is None and direita is None:
                                bolinha.kill()
                                grid.remove(bolinha)
                                bolinhas[l][c] = None

                    player.kill()
                    bolha1.kill()
                    grid.remove(bolha1)
                    score+=conta*500
                # Cria nova linha para as bolinhas lançadas  
                else:
                    player.linha = bolha1.linha + 1
                    player.coluna = bolha1.coluna
                    if player.linha >= LINHAS:
                        linha = []
                        for j in range(COL):
                            linha.append(None)
                        bolinhas.append(linha)
                    bolinhas[player.linha][player.coluna] = player
                    player.rect.x = player.coluna * BUBBLEWIDTH
                    player.rect.y = player.linha * BUBBLEHEIGHT
                    
                    grid.add(player)
            #Termina caso tenha mais de 11 na mesma coluna
            if player.rect.y > 400:
                state = OVER
                game = False
                return state
            player = Bubble(STARTX, STARTY, -1, -1)
            objetos.add(player)

        objetos.update()
        grid.update() 

        screen.fill(LIGHT_BLUE)
        #Gerando fonte 
        text_surface = fonte_score.render("Objetivo:20000", True, (0, 0, 0))
        text_surface2 = fonte_score.render("Score:{}".format(score), True, (0, 0, 0))
        text_rect = text_surface.get_rect()
        text_rect2 = text_surface2.get_rect()
        text_rect.midleft = (20, 600)
        text_rect2.midleft = (20, 620)
        screen.fill(LIGHT_BLUE)
        
        #Finalizar a tela quando a pessoa ganha
        ganhou = fontev.render("Parabens, voce ganhou", True, (0, 0, 0))
        ganhou_rect =ganhou.get_rect()
        ganhou_rect.midtop=(425, 300)
        
        if score>=20000:
            screen.fill(random.choice(LIGHT))
            screen.blit(ganhou, ganhou_rect)
            pygame.display.update()
            pygame.time.delay(5000)
            state=INIT
            game=False
            return state
            
        #Define a linha limite
        pygame.draw.line(screen, RED, [0, 440], [850, 440], 3)
        pygame.draw.rect(screen, LIGHT_RED, [0, 440, 850, 250])
        objetos.draw(screen)
        screen.blit(text_surface, text_rect)
        screen.blit(text_surface2, text_rect2)
        #Atualiza o display
        pygame.display.update()
moveing_bubble = pygame.sprite.Group()

#Defineing all my objects in a loop.
#Got the idea from Cade

#fish loop
for j in range(10):
    tempFish = Fish(RED, 80, 60, random.randint(50, 100))
    tempFish.rect.x = random.randint(100, 700)
    tempFish.rect.y = random.randint(100, 700)
    moveing_fish.add(tempFish)
    all_sprites_list.add(tempFish)

#bubble loop
for i in range(15):
    tempBubble = Bubble(BUBBLE, random.randint(10, 50), random.randint(10, 50))
    tempBubble.rect.x = random.randint(0, 700)
    tempBubble.rect.y = random.randint(0, 700)
    moveing_bubble.add(tempBubble)
    all_sprites_list.add(tempBubble)

#clock stuff
carryOn = True
clock = pygame.time.Clock()

#---------Main Program Loop----------
while carryOn:
    # --- Main event loop ---
    for event in pygame.event.get():  # Player did something
        if event.type == pygame.QUIT:  # Player clicked close button
            carryOn = False
def load_Bubble():
	global next_bubble, last_bubble
	if next_bubble == None:
		last_bubble = None
		next_bubble = Bubble(tk_canvas)
 

from Bubble_Tkinter import TKPICTURE
from Bubble_Line_Shooter import LineShooter 
from Bubble import Bubble



tk_canvas = TKPICTURE(600, 600)
tk_canvas.score = 0
line_shoot = LineShooter(tk_canvas)
next_bubble = Bubble(tk_canvas)
last_bubble = None 
stuck_balls = set([])
list_of_grids = next_bubble.make_grid()



# event_handler function
def update_line_vel_right_press(event): 
	line_shoot.update_vel_right_press(line_shoot.firing_angle_vel_inc)



# event handler function 
def update_line_vel_left_press(event):
	line_shoot.update_vel_left_press(line_shoot.firing_angle_vel_inc)



# event_handler function
def Misson_Gen(argv=''):

    # print(argv)
    if "/?" in argv:
        print("Canonn System Numberwang:")
        print(" /new = Force all new data")
        print(" /safe = Do not post results to Google")
        print(" /wait = Pause console at end to review output")
        print(" /schedule = Run according to Patrol Schedule")

        quit

    # check if any action is scheduled and apply the specified argument, exit if no action scheduled
    if "/schedule" in argv:
        schedule = CSNSchedule()
        if schedule:
            argv += [f"/{schedule}"]
        else:
            print('No Schedule')
            return None

    bubble = Bubble.Bubble()
    faction_systems = bubble.localspace
    factionnames = bubble.factionnames
    orides = list

    if LOCAL_OVERRIDE:
        # Local Overrides
        oridefile = f'data\\{factionnames[0]}Overrides.csv'
        if os.path.isfile(oridefile):
            with open(oridefile, newline='') as io:
                reader = csv.reader(io, delimiter='\t')
                orides = list(reader)
            for x in orides[1:]:  # Yeah, can probably be done in 1 statement
                x[1] = int(x[1])
    elif '/safe' in argv:
        # Google Sheet Via Read
        orides = CSNOverRideReadSafe()
    else:
        # Google Sheet via API
        orides = CSNOverRideRead()

    try:
        with open(f'data\\{factionnames[0]}Message.json', 'r') as io:
            oldmessage = json.load(io)
    except:
        oldmessage = []

    try:
        with open(f'data\\{factionnames[0]}Invaders.json', 'r') as io:
            invaders = json.load(io)
    except:
        invaders = []

    messages = []
    active_states = []
    pending_states = []
    recovering_states = []
    ootsystems = []
    detected_retreats = []

    dIcons = {
        "war": '<:EliteEagle:231083794700959744> ',
        "election": ':ballot_box: ',
        "civilwar": '<:EliteEagle:231083794700959744> ',
        "override": '<:canonn:231835416548999168> ',
        "push": '<:Salute2:500679418692501506> ',
        "data": ':eyes: ',
        "infgap": ':dagger: ',
        "mininf": ':chart_with_downwards_trend: ',
        "info": ':information_source: ',
        "end": ':clap: ',
        "FC": ':anchor: '
    }

    print(f'CSN Missions:')
    # Create a single Message for each faction system
    faction_systems = dict(filter(lambda x: x[1], faction_systems.items()))
    for i, key in enumerate(faction_systems):
        update_progress(i / len(faction_systems), key)
        sys = faction_systems[key]
        if sys:
            sys['factions'].sort(key=lambda x: x['influence'], reverse=True)
            factions = sys['factions']
            empire = sys['empire']
            happytext = empire['faction_details']['faction_presence'][
                'happiness']
            happy = 'Elated' if happytext == '$faction_happinessband1;' else 'Happy' if happytext == '$faction_happinessband2;' else 'Pieved'

            conflict = None

            if len(factions) > 1:
                gap = factions[0]["influence"] - factions[1]["influence"]
                gapfromtop = factions[0]["influence"] - (empire['influence'])
            else:
                gap = 100
                gapfromtop = 0

            updated = Bubble.EliteBGSDateTime(sys["updated_at"])
            age = datetime.now() - updated
            oride = list(filter(lambda x: x[0] == sys["system_name"], orides))
            faction_systems[key][
                'override'] = oride[0][4] if oride else 'Natural'

            if sys['name'] == 'DEBUG':
                print(f'Debug')

            # Single Message per sysme for Patrol
            if faction_systems[key]['override'] != 'Natural':  # OVERRIDE!
                for newmessage in oride:
                    messages.append(
                        amessage(
                            sys, newmessage[1], newmessage[2].format(
                                gap=gap, inf=empire['influence'], happy=happy)
                            + '*', dIcons['override']
                            if newmessage[3] == '' else dIcons[newmessage[3]]))

            if faction_systems[key]['override'] != 'Override':
                # Conflict Active
                if len(
                        list(
                            filter(
                                lambda x: x['state'] in
                                {'war', 'election', 'civilwar'},
                                empire['active_states']))) > 0:
                    conflict = empire["conflicts"][0]
                    messages.append(
                        amessage(
                            sys,
                            2,
                            '{3} against {0} ({1} v {2})'.format(
                                conflict["opponent_name"],
                                conflict["days_won"],
                                bubble.dayswon(sys["system_name"],
                                               conflict["opponent_name"]),
                                conflict["type"].title()),
                            dIcons[conflict["type"]],
                        ))
                # Conflict Pending
                elif len(
                        list(
                            filter(
                                lambda x: x['state'] in
                                {'war', 'election', 'civilwar'},
                                empire['pending_states']))) > 0:
                    conflict = empire["conflicts"][0]
                    messages.append(
                        amessage(
                            sys,
                            2,
                            '{1} Pending with {0}. No action required while Pending, but you can prepare'
                            .format(conflict["opponent_name"],
                                    conflict["type"].title()),
                            dIcons[conflict["type"]],
                        ))

                if (not conflict) and faction_systems[key]['override'] in {
                        'Addition', 'Natural'
                }:
                    # Not yet in control
                    if factions[0]['name'] not in factionnames:
                        messages.append(
                            amessage(
                                sys, 3,
                                f'Urgent: {sys["empire"]["name"]} {availableactions(faction_systems[key],factionnames)} to gain system control (gap {gapfromtop:4.3}%)',
                                dIcons['push']))
                    # Gap to 2nd place is low
                    elif gap < M_INFGAP:
                        messages.append(
                            amessage(
                                sys, 4,
                                f'Required: {sys["empire"]["name"]} {availableactions(faction_systems[key],factionnames)} ({factions[1]["name"]} is threatening, gap is only {gap:4.3}%)',
                                dIcons['infgap']))

            # Multi Messages
            # Data out of date
            if age.days > (factions[0]['influence'] / 10):
                messages.append(
                    amessage(
                        sys, 11,
                        f'Scan System to update data {int(age.days)} days old',
                        dIcons['data']))

            # Pending Tritium Refinary Low Price
            if (len(
                    list(
                        filter(
                            lambda x: x[
                                'state'] in {'drought', 'blight', 'terrorism'},
                            empire['pending_states']))) > 0) and sys.get(
                                'sellsTritium', False):
                messages.append(
                    amessage(sys, 25, f'Tritium Opportunity Warning',
                             dIcons['data']))

            # Active Tritium Refinary Low Price
            if (len(
                    list(
                        filter(
                            lambda x: x[
                                'state'] in {'drought', 'blight', 'terrorism'},
                            empire['active_states']))) > 0) and sys.get(
                                'sellsTritium', False):
                messages.append(
                    amessage(sys, 24, f'Tritium Opportunity Active',
                             dIcons['data']))

            # GOLDRUSH
            if next(
                (x for x in empire['active_states'] + empire['pending_states']
                 if x['state'] in {'infrastructurefailure'}), None):
                if next((x for x in sys['stations']
                         if x['economy'] in {'$economy_extraction;'}), None):
                    messages.append(
                        amessage(
                            sys, 24, "Super " if next(
                                (x for x in empire['active_states'] +
                                 empire['pending_states']
                                 if x['state'] in {'civil liberty'}), None)
                            else "" + f"Gold Rush Active or Pending",
                            dIcons['data']))

            # Conflict Complete Info - Additional Message, not for Patrol, but for Discord
            if len(
                    list(
                        filter(
                            lambda x: x['state'
                                        ] in {'war', 'election', 'civilwar'},
                            empire['recovering_states']))) > 0:
                conflict = empire["conflicts"][0]
                if conflict["days_won"] == bubble.dayswon(
                        sys["system_name"], conflict["opponent_name"]):
                    # Draw
                    asset = ''
                elif conflict["days_won"] > bubble.dayswon(
                        sys["system_name"], conflict["opponent_name"]):
                    # Won
                    asset = bubble.assetatrisk(sys["system_name"],
                                               conflict["opponent_name"])
                    if asset != '':
                        asset = 'Gained ' + asset
                else:
                    # Lost
                    asset = conflict["stake"]
                    if asset != '':
                        asset = 'Lost ' + asset

                messages.append(
                    amessage(
                        sys, 21,
                        '{3} against {0} Complete ({1} v {2}) {4}'.format(
                            conflict["opponent_name"], conflict["days_won"],
                            bubble.dayswon(sys["system_name"],
                                           conflict["opponent_name"]),
                            conflict["type"].title(), asset), dIcons["info"]))

            # Record All States for Usefull Summary Information
            for x in empire['active_states']:
                active_states.append([sys["system_name"], x["state"]])
            for x in empire['pending_states']:
                pending_states.append([sys["system_name"], x["state"]])
            for x in empire['recovering_states']:
                recovering_states.append([sys["system_name"], x["state"]])

            # Look for active Retreats
            for faction in sys['factions']:
                if next((x for x in faction['active_states']
                         if x['state'] == 'retreat'),
                        None) and sys['name'] not in detected_retreats:
                    detected_retreats.append(sys['name'])

    update_progress(1)

    # Add Detected Retreats
    if detected_retreats:
        print('')
        messages.append(
            amessage('Retreats Detected in', 25, ', '.join(detected_retreats),
                     dIcons['data']))

    # All Canonn Systems Processed
    # Messages for External Systems
    for ex in orides[1:]:
        if sum(faction_systems[x]["system_name"] == ex[0]
               for x in faction_systems) == 0:
            #exsys = bubble.findsystem(ex[0])
            exsys = api.getsystem(ex[0])
            if exsys:
                ex[2] = ex[2].replace(
                    '{inf}', f"{round(exsys['factions'][0]['influence'],1)}")
                messages.append(
                    amessage(
                        exsys, ex[1], ex[2] + '*',
                        dIcons['override'] if ex[3] == '' else dIcons[ex[3]],
                        'None'))
            else:
                print(f'!Override Ignored : {ex[0]} {ex[2]}')

    # Invasion Alert
    if '/new' in argv:  # Only worth processing once per day after the EDDB Data Dump at about 06:00
        invaders = InvasionAlert(factionnames[0])
    for sys in invaders:
        sys["system_name"] = sys["name"]
        # trim spurious data that was giving circular reference errors when trying to save
        sys['minor_faction_presences'] = list()
        sys['xcube'] = list()
        if sys['controlling_minor_faction'] in sys[
                'pf']:  # Policy is we allow NPC to arrive so they fill the system and block PC factions
            messages.append(
                amessage(
                    sys, 10,
                    f"{sys['controlling_minor_faction']} are targeting {sys['invading']} within {sys['cycles']} cycles : We should do something about this ({round(sys['influence'],1)}%)",
                    dIcons['data']))

    # Lowest Gaps for PUSH message
    l = list(
        filter(
            lambda x: faction_systems[x]['override'] == 'Addition' or
            not hasmessage(messages, faction_systems[x]['system_name']),
            faction_systems))

    l.sort(key=lambda s: faction_systems[s]['factions'][0]['influence'] -
           faction_systems[s]['factions'][1]['influence']
           if len(faction_systems[s]['factions']) > 1 else 100)

    for x in l[:3]:
        sys = faction_systems[x]
        if sys["factions"][0]["influence"] - sys["factions"][1][
                "influence"] < 35:  # At a 35% Gap, it becomes spam
            messages.append(
                amessage(
                    sys, 5,
                    f'Suggestion: {sys["empire"]["name"]} {availableactions(sys,factionnames)} (gap to {sys["factions"][1]["name"]} is {sys["factions"][0]["influence"]-sys["factions"][1]["influence"]:4.3}%)',
                    dIcons['mininf']))

    messages.sort()

    # Fleet Carrier Locations
    carriers = CSNFleetCarrierRead()
    for carrier in carriers:
        currentsystem = None
        if carrier['id'][0] != '!':
            try:
                thiscarrier = api.getfleetcarrier(carrier['id'])
                currentsystem = api.eddbSystem(thiscarrier['current_system'])
                messages.append(
                    amessage(currentsystem, 9,
                             f'{carrier["name"]} ({carrier["role"]})',
                             dIcons['FC'], 'Canonn'))
            except:
                pass
            if not currentsystem:
                print(f'!!! Fleet Carrier {carrier["id"]} Failed !!!')

    # Looks for changes in Discord suitable Messages since last run for WebHook
    messagechanges = []
    for x in messages:
        if (x not in oldmessage) or ('/new' in argv):
            messagechanges.append(x)
    # Looks to see what systems no longer have a message of any type
    for x in oldmessage:
        s = list(
            filter(
                lambda y: y[1] == x[1] and y[8] not in
                [dIcons['FC'], dIcons['info']], messages))
        if len(s) == 0 and x[8] not in [dIcons['FC'], dIcons['info']]:
            messagechanges.append(x)
            messagechanges[len(messagechanges) - 1][7] = '~~' + \
                messagechanges[len(messagechanges) - 1][7] + \
                '~~ : Mission Complete'
            messagechanges[len(messagechanges) - 1][8] = dIcons['end']

    for m in messages:
        print(f'{m[1]} : {m[7]}')

    # Write Orders various formats
    with open(f'data\\{factionnames[0]}Patrol.Csv',
              'w') as io:  # CSV for Humans
        io.writelines(f'System,X,Y,Z,Priority,Message\n')
        io.writelines(f'{x[1]},{x[2]},{x[3]},{x[4]},{x[5]},{x[7]}\n'
                      for x in messages)
    with open(f'data\\{factionnames[0]}DiscordPatrol.txt',
              'w') as io:  # Text Version for Discord
        io.writelines(f'Canonn System Numberwang\n')
        io.writelines(
            f'{x[8]}{x[1]} : {x[7]}\n'
            for x in filter(lambda x: x[0] < 11 or x[0] > 20, messages))
    with open(f'data\\{factionnames[0]}DiscordWebhook.txt',
              'w') as io:  # Webhook Text Version for Discord
        io.writelines(
            f'{x[8]}{x[1]} : {x[7]}\n'
            for x in filter(lambda x: x[0] < 11 or x[0] > 20, messagechanges))
    with open(f'data\\{factionnames[0]}Message.json',
              'w') as io:  # Dump to file for comparison next run
        json.dump(messages, io, indent=4)
    with open(f'data\\{factionnames[0]}Invaders.json',
              'w') as io:  # Dump to file for comparison next run
        json.dump(invaders, io, indent=4)

    # Discord Webhook
    if CSNSettings.wh_id and len(
            list(filter(lambda x: x[0] < 11 or x[0] > 20,
                        messagechanges))) > 0:
        wh_text = ''
        wh = Webhook.partial(CSNSettings.wh_id,
                             CSNSettings.wh_token,
                             adapter=RequestsWebhookAdapter())
        for x in filter(lambda x: x[0] < 11 or x[0] > 20, messagechanges):
            wh_text += f'{x[8]}{x[1]} : {x[7]}\n'
        if wh_text != '':
            wh.send(
                f'{"**Full Report**" if ("/new" in argv) else "Latest News"} <:canonn:231835416548999168> \n{wh_text}'
            )

    # Patrol to send to Google
    patrol = []
    for x in filter(lambda x: x[0] <= 20, messages):
        patrol.append(x[1:9])
    if not ('/safe' in argv):
        CSNPatrolWrite(patrol)

    if '/new' in argv:
        CSNAttractions(faction_systems)

    print('*** Missions Generated : Consuming {0} requests ***'.format(
        api.NREQ))
    if ('/wait') in argv:
        input("Press Enter to continue...")
Exemple #12
0
    def test_bubble_chain_delete(self):

        bubble_1 = Bubble(fake_tk_picture, color="blue")
        bubble_2 = Bubble(fake_tk_picture, color="blue")
        bubble_3 = Bubble(fake_tk_picture, color="blue")
        bubble_4 = Bubble(fake_tk_picture, color="red")
        bubble_5 = Bubble(fake_tk_picture, color="red")

        bubble_1.Bubble_last_pos = [100, 100]
        bubble_2.Bubble_last_pos = [100, 130]
        bubble_3.Bubble_last_pos = [130, 130]
        bubble_4.Bubble_last_pos = [130, 100]
        bubble_5.Bubble_last_pos = [130, 160]

        get_stuck = set([])
        bubble_1.adj_dict = bubble_1.build_adj_dict(get_stuck)
        # print "bubble_1_dict_1", bubble_1.adj_dict

        get_stuck_1 = set([bubble_1])
        bubble_2.adj_dict = bubble_2.build_adj_dict(get_stuck_1)
        # print "bubble_1_dict_2", bubble_2.adj_dict
        # print "bubble_2_dict", bubble_2.adj_dict

        get_stuck_2 = set([bubble_1, bubble_2])
        bubble_3.adj_dict = bubble_3.build_adj_dict(get_stuck_2)
        # print "bubble_3_dict", bubble_3.adj_dict

        get_stuck_3 = set([bubble_1, bubble_2, bubble_3])
        bubble_4.adj_dict = bubble_4.build_adj_dict(get_stuck_3)
        # print "bubble_4_dict", bubble_4.adj_dict

        get_stuck_4 = set([bubble_1, bubble_2, bubble_3, bubble_4])
        bubble_5.adj_dict = bubble_5.build_adj_dict(get_stuck_4)
        # print "bubble_4_dict", bubble_5.adj_dict

        same_color_chain_list = []
        bubble_3.get_bubble_chain(same_color_chain_list)

        expected = {'blue': [bubble_2], 'red': [bubble_4, bubble_5]}

        print "expected", expected
        print "bubble_3.adj_dict", bubble_3.adj_dict

        self.assertEqual(expected['blue'][0], bubble_3.adj_dict['blue'][0])

        self.assertEqual(len(expected['red']), len(bubble_3.adj_dict['red']))

        self.assertTrue(bubble_4 in bubble_3.adj_dict['red'])
        self.assertTrue(bubble_5 in bubble_3.adj_dict['red'])