Example #1
0
def show_scan_results():
    network_menu_contents = []
    networks = wpa_cli.get_scan_results()
    for network in networks:
        network_menu_contents.append([network['ssid'], lambda x=network: network_info_menu(x)])
    network_menu = Menu(network_menu_contents, i, o, "Wireless network menu")
    network_menu.activate()
Example #2
0
    def activate(self, activator=None):
        if CountUpTile.activate(self,activator):
            xu = self.map.size.x//4
            yu = self.map.size.y//4
            b = Menu( Position(xu,yu), Position(xu*2,yu*2), title="Trap Control" )
            b.add('1',"View traps")
            b.add('2',"%s traps" %(TrapConsole.traps_on and 'Disable' or 'Enable'))
            b.add('3',"Set off traps")
            b.add('x',"Exit")

            c = b.get_key()
            del b

            traps = self.map.find_all(Trap,Tile)

            if c == '1':
                for t in traps:
                    t.visible_to_player = True
                self.map.player.handle_keys()

            elif c == '2':
                for trap in traps:
                    trap.enabled = TrapConsole.traps_on

                TrapConsole.traps_on = not TrapConsole.traps_on

            elif c == '3':
                for trap in traps:
                    trap.trip()

            return True
        return False
Example #3
0
def wireless_status():
    w_status = wpa_cli.connection_status()
    state = w_status['wpa_state']
    status_menu_contents = [[["state:", state]]] #State is an element that's always there, let's see possible states
    if state == 'COMPLETED':
        #We have bssid, ssid and key_mgmt at least
        status_menu_contents.append(['SSID: '+w_status['ssid']])
        status_menu_contents.append(['BSSID: '+w_status['bssid']])
        key_mgmt = w_status['key_mgmt']
        status_menu_contents.append([['Security:', key_mgmt]])
        #If we have WPA in key_mgmt, we also have pairwise_cipher and group_cipher set to something other than NONE so we can show them
        if key_mgmt != 'NONE':
            try: #What if?
                group = w_status['group_cipher']
                pairwise = w_status['pairwise_cipher']
                status_menu_contents.append([['Group/Pairwise:', group+"/"+pairwise]])
            except:
                pass
    elif state in ['AUTHENTICATING', 'SCANNING', 'ASSOCIATING']:
        pass #These states don't have much information
    #In any case, we might or might not have IP address info
    status_menu_contents.append([['IP address:',w_status['ip_address'] if 'ip_address' in w_status else 'None']])
    #We also always have WiFi MAC address as 'address'
    status_menu_contents.append(['MAC: '+w_status['address']])
    status_menu = Menu(status_menu_contents, i, o, "Wireless status menu", entry_height=2)
    status_menu.activate()
Example #4
0
def change_interface():
    #This function builds a menu out of all the interface names, each having a callback to show_if_function with interface name as argument
    menu_contents = []
    interfaces = wpa_cli.get_interfaces()
    for interface in interfaces:
        menu_contents.append([interface, lambda x=interface: change_current_interface(x)])
    interface_menu = Menu(menu_contents, i, o, "Interface change menu")
    interface_menu.activate()
Example #5
0
def network_info_menu(network_info):
    network_info_contents = [
    ["Connect", lambda x=network_info: connect_to_network(x)],
    ["BSSID", lambda x=network_info['bssid']: Printer(x, i, o, 5, skippable=True)],
    ["Frequency", lambda x=network_info['frequency']: Printer(x, i, o, 5, skippable=True)],
    ["Open" if wpa_cli.is_open_network(network_info) else "Secured", lambda x=network_info['flags']: Printer(x, i, o, 5, skippable=True)]]
    network_info_menu = Menu(network_info_contents, i, o, "Wireless network info", catch_exit=False)
    network_info_menu.activate()
Example #6
0
File: main.py Project: psyrax/pyLCI
def show_ifc_data(ifc_name, ifc_data):
    ifd_menu_contents = [
    ["state: "+str(ifc_data['state'])],
    ["IP: "+str(ifc_data['addr'])],
    ["IP6: "+str(ifc_data['addr6'])],
    ["MAC: "+str(ifc_data['ph_addr'])]
    ]
    ifd_menu = Menu(ifd_menu_contents, i, o, "{} interface data menu".format(ifc_name), entry_height=2)
    ifd_menu.activate()
Example #7
0
def manage_networks():
    global saved_networks
    saved_networks = wpa_cli.list_configured_networks()
    network_menu_contents = []
    #As of wpa_supplicant 2.3-1, header elements are ['network id', 'ssid', 'bssid', 'flags']
    for num, network in enumerate(saved_networks):
        network_menu_contents.append(["{0[network id]}: {0[ssid]}".format(network), lambda x=num: saved_network_menu(saved_networks[x])])
    network_menu = Menu(network_menu_contents, i, o, "Saved network menu", catch_exit=False)
    network_menu.activate()
Example #8
0
def main():
        # Initialise screen
        pygame.init()
        screen = pygame.display.set_mode((800, 600))
        pygame.display.set_caption('Basic Pygame program')

        # Fill background
        background = pygame.Surface(screen.get_size())
        background = background.convert()
        background.fill((0, 0, 0))

        # Display some text

        font = pygame.font.Font('petme/PetMe128.ttf', 12)
        text = font.render("Hello There", 1, (250, 250, 250))
        
        textpos = text.get_rect()
        textpos.centerx = background.get_rect().centerx
        background.blit(text, textpos)

        # Blit everything to the screen
        screen.blit(background, (0, 0))
        pygame.display.flip()
        
        menuItems = ['Attack','Wait','Special One', 'Special Two']
        myMenu = Menu("Action:", menuItems, font, 50, 50, 200, 200)
        tilesize=32

        DeathImageSet=sprites.load_sliced_sprites(64,64,'images/skeleton_death.png')

        SuitImageSet = sprites.load_sliced_sprites(64, 64, 'images/Suit/Suit_walk.png')
        SuitAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/Suit/Suit_attack.png')
        SuitSprite = Actor((14-.5)*tilesize, (4-1)*tilesize, SuitImageSet[0], SuitImageSet[1], SuitImageSet[2], SuitImageSet[3], \
        DeathImageSet[0], SuitAttackImageSet[0], SuitAttackImageSet[1], SuitAttackImageSet[2], SuitAttackImageSet[3], \
        "Tommy Lee Jones", 'Friendly' ,8, 0, 3, 6, 8)
        #PrincessImageSet = sprites.load_sliced_sprites(64,64,'images/princess.png')
        #PrincessSprite = Actor((23-.5)*tilesize, (21-1)*tilesize,PrincessImageSet[1], PrincessImageSet[0], PrincessImageSet[2], PrincessImageSet[3], "Peach", 3, 2, 2, 6, 60)

        suitInfo = CharacterInfo(SuitSprite, font, 600)
        # Event loop
        while 1:
                for event in pygame.event.get():
                        if event.type == QUIT:
                                return
                        action = myMenu.input(event)

                        if action is not None:
                                print action
                screen.blit(background, (0, 0))
                screen.blit(myMenu.surface, myMenu.rect)                
                screen.blit(suitInfo.surface, suitInfo.rect)
                pygame.display.flip()
Example #9
0
def show_ifc_data(ifc_name, ifc_data):
    ip, mask = str(ifc_data['addr']).rsplit('/', 1)
    ip_header = "IP: "
    mask_str = "/{}".format(mask)
    ip_header_str = ip_header + mask_str.rjust(o.cols-len(ip_header)) #Magic to make it beautiful
    print(ip_header_str)
    ifd_menu_contents = [
    ["state: "+str(ifc_data['state'])],
    [[ip_header_str, ip]],
    ["IP6: "+str(ifc_data['addr6']), lambda: Printer(str(ifc_data['addr6']), i, o, 3)],
    ["MAC: "+str(ifc_data['ph_addr'])]
    ]
    ifd_menu = Menu(ifd_menu_contents, i, o, "{} interface data menu".format(ifc_name), entry_height=2)
    ifd_menu.activate()
Example #10
0
    def activate(self, activator=None):
        if CountUpTile.activate(self,activator):
            xu = self.map.size.x//4
            yu = self.map.size.y//4
            b = Menu( Position(xu,yu), Position(xu*2,yu*2), title="Camera Control" )
            b.add('1',"View cameras")
            b.add('2',"Switch %s cameras" %(CameraConsole.cameras_on and 'off' or 'on'))
            b.add('x',"Exit")

            c = b.get_key()
            del b

            cams = self.map.find_all(StaticCamera,Monster)

            if c == '1':
                for cam in cams:
                    self.map.prepare_fov(cam.pos,reset=False)
                self.map.player.handle_keys()

            elif c == '2':
                if CameraConsole.cameras_on:
                    for cam in cams:
                        cam.add_effect(StatusEffect.BLIND)
                else:
                    for cam in cams:
                        cam.remove_effect(StatusEffect.BLIND)

                CameraConsole.cameras_on = not CameraConsole.cameras_on

            return True
        return False
Example #11
0
def launch():
    try:
       systemctl.list_units()
    except OSError as e:
       if e.errno == 2:
           Printer(["Do you use", "systemctl?"], i, o, 3, skippable=True)
           return
       else:
           raise e
    main_menu_contents = [
    ["Units (filtered)", filtered_units],
    ["All units", all_units],
    ["Change filters", change_filters]]
    main_menu = Menu(main_menu_contents, i, o, "systemctl main menu")
    main_menu.activate()
Example #12
0
def saved_network_menu(network_info):
    global saved_networks
    id = network_info['network id']
    bssid = network_info['bssid']
    network_status = network_info["flags"] if network_info["flags"] else "[ENABLED]"
    network_info_contents = [
    [network_status],
    ["Select", lambda x=id: select_network(x)],
    ["Enable", lambda x=id: enable_network(x)],
    ["Disable", lambda x=id: disable_network(x)],
    ["Remove", lambda x=id: remove_network(x)],
    ["Set password", lambda x=id: set_password(x)],
    ["BSSID", lambda x=bssid: Printer(x, i, o, 5, skippable=True)]]
    network_info_menu = Menu(network_info_contents, i, o, "Wireless network info", catch_exit=False)
    network_info_menu.activate() 
    #After menu exits, we'll request the status again and update the 
    saved_networks = wpa_cli.list_configured_networks()
Example #13
0
    def pickup(self,i):
        """returns True if i picked up successfully"""
        # TODO: move all this into HasInventory interface
        assert isinstance(i,Item), "Can't pick up a %s"%i

        if isinstance(i,Evidence):
            self.evidence.append(i)
            if not i.pos is None: # found it in a locker
                self.map.remove(i)
            return Player.ITEM_PICKUP_COST

        item_index = None
        items      = self.items
        if isinstance(i,SlotItem):
            items  = [self.slot_items[i.valid_slot]]
        if not None in items:
            # prompt to drop something; drop it

            xu = self.map.size.x//4
            yu = self.map.size.y//4
            b = Menu( Position(xu,yu), Position(xu*2,yu*2), title="Pick Up" )
            b.add('x',str(i))
            b.add_spacer()
            for idx in range(len(items)):
                v = items[idx]
                b.add('%d'%(idx+1),str(v))
            c = b.get_key()

            if isinstance(c,str) and c.isnumeric():
                item_index = int(c) - 1
            self.redraw_screen()
            del b
            if item_index is None or item_index >= len(items):
                return 0.0
            items[item_index].drop_at(self.pos)
            self.map.add(items[item_index])
        else:
            item_index = items.index(None)

        if isinstance(i,SlotItem):
            self.slot_items[i.valid_slot] = i
        else:
            self.items[item_index] = i

        if not i.pos is None: # if taken from locker or other bonus
            self.map.remove(i)
        i.take_by(self)
        return Player.ITEM_PICKUP_COST
Example #14
0
def main_pygame(file_name):
    pygame.init()

    #print(" x/c/v = move/wait/cancel, wasd=camera movement, '+/-' control the volume of the background music")

    myfont = pygame.font.Font("press-start-2p/PressStart2P.ttf", 11)
    
    worldMap = tiledtmxloader.tmxreader.TileMapParser().parse_decode(file_name)
    assert worldMap.orientation == "orthogonal"
    screen_width = min(1024, worldMap.pixel_width)
    screen_height = min(768, worldMap.pixel_height)
    screen = pygame.display.set_mode((screen_width, screen_height))
    Characters = pygame.sprite.RenderUpdates()
    
    GameBoard = Board(worldMap, Characters, tileSize, screen)
    pygame.display.set_caption("Ancient Juan")

    #UI sprite container
    menuItems = ["Attack", "Move" ,"Wait", "Cancel"]#thse will be changed later
    myMenu = Menu("Action:", menuItems, myfont, 50, 150, 200, 200)
  
    #CHARACTERS!

    DeathImageSet=sprites.load_sliced_sprites(64,64,'images/skeleton/skeleton_death.png')

    KnightDeathImageSet = sprites.load_sliced_sprites(64, 64, 'images/knight/knight_death.png')
    KnightImageSet = sprites.load_sliced_sprites(64, 64, 'images/knight/knight_walk.png')
    KnightAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/knight/knight_attack.png')
    KnightSprite = Actor((14-.5)*tileSize, (4-1)*tileSize, KnightImageSet[0], KnightImageSet[1], KnightImageSet[2], KnightImageSet[3], \
        KnightDeathImageSet[0], KnightAttackImageSet[0], KnightAttackImageSet[1], KnightAttackImageSet[2], KnightAttackImageSet[3], \
        "Buster", FRIENDLY ,8, 8, 4, 6, 20)#movement is usually 6
    KnightSprite.RegisterAction(ATTACK, 'The character makes a powerful slash against  an --adjacent target.',[],[])
    KnightSprite.RegisterAction(WHIRLWIND, 'the character spins in a flurry hitting all enemies up to two tiles away.', [],[])
    Characters.add(KnightSprite)
    

    ArcherDeathImageSet=sprites.load_sliced_sprites(64,64,'images/archer/archer_death.png')    
    ArcherImageSet = sprites.load_sliced_sprites(64, 64, 'images/archer/archer_walk.png')
    ArcherAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/archer/archer_attack.png')
    ArcherSprite = Actor((15-.5)*tileSize, (4-1)*tileSize, ArcherImageSet[0], ArcherImageSet[1], ArcherImageSet[2], ArcherImageSet[3], \
        DeathImageSet[0], ArcherAttackImageSet[0], ArcherAttackImageSet[1], ArcherAttackImageSet[2], ArcherAttackImageSet[3], \
        "Archie", FRIENDLY ,5, 6, 5, 5, 17)#movement is usually 5
    ArcherSprite.RegisterAction(RANGED, 'The character fires an arrow!', [],[])
    ArcherSprite.RegisterAction(CRIPPLESTRIKE, 'The character aims for a sensitive area, postponing the targets next turn.', [],[])
    Characters.add(ArcherSprite)
    
    ForestMageDeathImageSet=sprites.load_sliced_sprites(64,64,'images/forestmage/forestmage_death.png')
    ForestMageImageSet = sprites.load_sliced_sprites(64, 64, 'images/forestmage/forestmage_walk.png')
    ForestMageAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/forestmage/forestmage_spell.png')
    ForestMageSprite = Actor((16-.5)*tileSize, (4-1)*tileSize, ForestMageImageSet[0], ForestMageImageSet[1], ForestMageImageSet[2], ForestMageImageSet[3], \
        ForestMageDeathImageSet[0], ForestMageAttackImageSet[0], ForestMageAttackImageSet[1], ForestMageAttackImageSet[2], ForestMageAttackImageSet[3], \
        "Terra", FRIENDLY ,5, 4, 4, 5, 15)
    ForestMageSprite.RegisterAction(AOE, 'The character conjures Feline Flames!', [],[])
    ForestMageSprite.RegisterAction(HEAL, 'Restores the health of yourself or an ally.', [], [])
    Characters.add(ForestMageSprite)

    # mainloop variables for gameplay
    frames_per_sec = 60.0
    clock = pygame.time.Clock()
    running = True
    paused=True #start the game paused
    grid=False #Debugging boolean to draw a grid

    #these are triggers for text in the game
    gameStart=True
    scriptCounter=0
    AlignmentCounter={}
    AlignmentCounter[FRIENDLY]=0
    AlignmentCounter[HOSTILE]=0
    gameOver=False
    AncientAwoken=False

    #Game Turns Controller
    PlayTurn=Turn(GameBoard)
    mode=PlayTurn.Mode()#used to detect when the mode changes for updating purposes

    #the Bad gusys
    
    PlayTurn.SpawnSkeleton(16,9,1)
    
    PlayTurn.SpawnSkeleton(22,13,1)
    PlayTurn.SpawnSkeleton(21,12, 1)
    PlayTurn.SpawnMage(15,16,1)
    PlayTurn.SpawnMage(17,20,1)
    PlayTurn.SpawnPig(12,19,1)
    PlayTurn.SpawnPig(13,18,1)
    PlayTurn.SpawnSkeleton(4,6,2)
    
    PlayTurn.SpawnMage(5,6,1)
    PlayTurn.SpawnMage(22,31,2)
    PlayTurn.SpawnPig(26,24,1)
    PlayTurn.SpawnPig(20,37,2)
    PlayTurn.SpawnPig(20,39,2)
    
    PlayTurn.SpawnPortal(2,6, 1)
    PlayTurn.SpawnPortal(7,18, 1)
    PlayTurn.SpawnPortal(28,25, 1)
    PlayTurn.SpawnPortal(34,38, 1)
    PlayTurn.SpawnPortal(18,47, 1)
    PlayTurn.SpawnPortal(9,42, 1)
    
    #PlayTurn.SpawnPortal(17,3,1)
    
    #PlayTurn.SpawnSpecial(18,38,level=5)
    
    #Picks the first character
    CurrentSprite=PlayTurn.Next()
    CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height)
    myMenu = Menu("Turn:"+PlayTurn.CurrentSprite().Name(), PlayTurn.CurrentActions(), myfont, 50, 150, 200, 220, ActionItems = PlayTurn.CurrentSprite().GetActions())
    starttext="ARCHIE, BUSTER and TERRA have been following a disturbance in arcane energies to the edge of a deep fissure in the earth."+ \
                       "Just beyond the fissure they find what appears to be a green portal.  Before they can investigate they are ambushed by dark agents!"

    pausetext = ["Control the players using the mouse.", "WASD keys move the camera." , "+/- control the volume of the background music."]
    
    triggerText   = ["These portals must be how the creatures are passing to this realm!", "We must destroy all of the portals!", "There is another one in the graveyard!", "Up ahead is a strange altar!"] 
    PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(starttext)/3), text=starttext)

    #Music
    BGvolume=.15#.05 #this is a number between 0 and 1
    BackgroundMusic =pygame.mixer.Sound("sound/wandering_around.wav")
    BackgroundMusic.play(loops=-1)
    BackgroundMusic.set_volume(BGvolume)
    LevelUpMusic = pygame.mixer.Sound("sound/levelup.wav")

    ##The Main Game Loop 
    while running:
        clock.tick(frames_per_sec)
        time = pygame.time.get_ticks()

        mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos() #mouse coordinates
        tile_x, tile_y = mouse_pos_x// tileSize, mouse_pos_y // tileSize #note the board translates coordinates depending on the location of the camera

        #used these if you want to be able to hold down the mouse/keys
        pressedKeys=pygame.key.get_pressed() #actions that come from the keyboard This is for holding down
        pressedMouse = pygame.mouse.get_pressed() # mouse pressed event 3 booleans [button1, button2, button3]

        #counts the number of actors of each alignment
        AlignmentCounter[FRIENDLY]=0
        AlignmentCounter[HOSTILE]=0   
        for actor in Characters:
            AlignmentCounter[actor.Alignment()] +=1
   
        #checks for levelups,
        if PlayTurn.Mode()==LEVELUP and paused==False:# we are between turns

            if PlayTurn.CurrentSprite().LevelUp():#this is redundant
                #print 'levelup!'
                paused=True
                LevelUpMusic.play(loops=0)
                CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height)

                LevelUpWindow = Menu(PlayTurn.CurrentSprite().Name()+' levels up!', PlayTurn.LevelUpActions() ,myfont, 100,100,200,200, ActionItems= PlayTurn.CurrentSprite().GetActions(), text="Choose a skill to improve.")
                continue

        #update the UI
        if (CurrentSprite != PlayTurn.CurrentSprite() or mode != PlayTurn.Mode() ) and PlayTurn.CurrentSprite !=[] and paused==False:
            CurrentSprite = PlayTurn.CurrentSprite()
            mode= PlayTurn.Mode()
            myMenu = Menu("Turn:"+PlayTurn.CurrentSprite().Name(), PlayTurn.CurrentActions(), myfont, 50, 150, 200, 220, ActionItems = PlayTurn.CurrentSprite().GetActions())
            #CurrentActions is a list removing unavailable actions
            CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height)
        #Move the camera manually with "wasd"

        ###Special Script section!!
        if scriptCounter==0 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_y>13 and PlayTurn._moves==[] and GameBoard.Animating()==False:
            paused=True
            
            currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter]
            PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)
            GameBoard.PanCamera((25 + GameBoard._screenTileOffset_x)*GameBoard._tileSize, \
                (22+ GameBoard._screenTileOffset_y)*GameBoard._tileSize) 
            scriptCounter+=1
            
        elif scriptCounter==1 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_y>17 and GameBoard.Animating()==False:
            paused=True
            
            currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter]
            PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)
            scriptCounter+=1
            if GameBoard.getTile(28,24,tiled=True)[0]!="Collision":
                PortalMusic =pygame.mixer.Sound("sound/portal.wav")
                PortalMusic.play(loops=0)
                PlayTurn.SpawnSkeleton(28,24,2)

        elif scriptCounter==2 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_x<10 and GameBoard.Animating()==False:
            paused=True
            
            currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter]
            PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)
            scriptCounter+=1

        elif scriptCounter==3 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_y>29 and GameBoard.Animating()==False:
            paused=True
            
            currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter]
            PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)
            scriptCounter+=1

        elif AlignmentCounter[HOSTILE]==0 and gameOver==False and AncientAwoken==False:
            AncientAwoken=True
            paused=True
            currentText="You have disturbed an ancient villain, behold the ANCIENT ONE!!!!"
            PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)
            PlayTurn.SpawnSpecial(18,38,4)
            #print("won the game")

        elif AlignmentCounter[HOSTILE]==0 and gameOver==False and AncientAwoken==True:
            gameOver=True
            paused=True
            currentText="Congratulations on completing the abbreviated version of DEFEAT OF THE ANCIENT ONE.  Someday we'll actually add in more to the game.  Thank you for playing!!!!"
            PauseWindow = Menu("Defeat of the Ancient One", [RESTART, QUITGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)
            #print("won the game")

        elif AlignmentCounter[FRIENDLY]==0 and gameOver==False:
            gameOver=True
            paused=True
            currentText="Your party has been defeated.  Without you to prevent the return of the Ancient One, the world was destroyed!!"
            PauseWindow = Menu("Defeat of the Ancient One", [RESTART, QUITGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText)

            
            
        for event in pygame.event.get():       
 
            if event.type == QUIT or event.type == pygame.QUIT or (pressedKeys[K_w] and pressedKeys[K_LMETA]):
                running = False
                pygame.quit()
                sys.exit()
                
            if PlayTurn.Mode()==LEVELUP and paused:
                action = LevelUpWindow.input(event)
            elif paused:
                action = PauseWindow.input(event)
            else:
                
                action = myMenu.input(event) #actions that come from the menu
            if not (hasattr(event, 'key') or event.type==KEYDOWN or hasattr(event, 'button') or event.type==MOUSEBUTTONUP): continue
            #print(action)
            
            #UI or turn events
            if (action == CONTINUEGAME or pressedKeys[K_ESCAPE]):
                if gameStart==True:
                    PauseWindow = Menu("Defeat of the Ancient One", pausetext+[CONTINUEGAME], myfont, 100,100, 600,100, text="This game can be paused at any time, bringing up this window by pressing ESC.")
                    gameStart=False
                else:
                    paused= not paused
 
     
                    PauseWindow = Menu("Defeat of the Ancient One", pausetext+[CONTINUEGAME], myfont, 100,100, 600,100, text="")
                GameBoard.PanCamera((PlayTurn.CurrentSprite().tile_x + GameBoard._screenTileOffset_x)*GameBoard._tileSize, \
                    (PlayTurn.CurrentSprite().tile_y + GameBoard._screenTileOffset_y)*GameBoard._tileSize)
                
            elif action == QUITGAME:
                running = False
                pygame.quit()
                sys.exit()
            elif action == RESTART:
                #print("restart called")
                restart_program()

            #the level up parts
            elif PlayTurn.Mode()==LEVELUP and (action in actionList):
                CurrentSprite.LevelUpAction(action)
                PlayTurn._currentSprite=[]
                PlayTurn._mode=[]
                PlayTurn.Next()
                paused=False

                
            elif paused==False and (action == MOVE or pressedKeys[K_x]) and PlayTurn.Mode()==[] and PlayTurn.CurrentSprite().Alignment() != HOSTILE :
                PlayTurn.MoveMode()

            elif paused==False and (action == WAIT or pressedKeys[K_c]) and PlayTurn.CurrentSprite().Alignment() != HOSTILE: #note right now this overrides whatever mode you were in, a back button might be nice 
                PlayTurn.EndTurn()
            elif paused==False and (action == CANCEL or pressedKeys[K_v]) and PlayTurn.CurrentSprite().Alignment() != HOSTILE:
                PlayTurn.CancelMode()
            elif paused==False and (action in actionList or pressedKeys[K_z]) and PlayTurn.Mode()==[] and PlayTurn.CurrentSprite().Alignment() != HOSTILE:#right now it brings up a target list
                #print("Entering Mode", action)
                PlayTurn.ActionMode(action)




            '''
            #single keystroke type inputs
            if event.key ==K_RIGHT: pygame.mouse.set_pos([mouse_pos_x+tileSize, mouse_pos_y])
            elif event.key == K_LEFT: pygame.mouse.set_pos([mouse_pos_x-tileSize, mouse_pos_y])
            elif event.key == K_UP: pygame.mouse.set_pos([mouse_pos_x, mouse_pos_y-tileSize])
            elif event.key == K_DOWN: pygame.mouse.set_pos([mouse_pos_x, mouse_pos_y+tileSize])
            '''
            #Debug
            if pressedKeys[K_g]: grid= not grid #DEBUG: this toggles the grid
            
        if pressedKeys[K_d]: GameBoard.MoveCamera(tileSize,0, relative=True) #right
        elif pressedKeys[K_a]: GameBoard.MoveCamera(-tileSize,0, relative=True)#left
        elif pressedKeys[K_w]: GameBoard.MoveCamera(0,-tileSize, relative=True) #up
        elif pressedKeys[K_s]: GameBoard.MoveCamera(0,tileSize, relative=True) #down

        elif pressedKeys[K_PLUS] or pressedKeys[K_EQUALS]:
            if BGvolume<1:
                BGvolume+=.05
        elif pressedKeys[K_MINUS] or pressedKeys[K_UNDERSCORE]:
            if BGvolume>0:
                BGvolume-=.05
        BackgroundMusic.set_volume(BGvolume)

        
        if pressedMouse[0]:
            myMenu = Menu("Turn:"+PlayTurn.CurrentSprite().Name(), PlayTurn.CurrentActions(), myfont, 50, 150, 200, 220, ActionItems = PlayTurn.CurrentSprite().GetActions())
            #print(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2])
            
            #Seed what you clicked on and what turn mode you are in, then determins what to do
            if (PlayTurn.Mode()==ATTACK or PlayTurn.Mode()==RANGED or PlayTurn.Mode()==CRIPPLESTRIKE) and GameBoard.getTile(mouse_pos_x, mouse_pos_y)[0]=="Actor":
                PlayTurn.Attack(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[1])
                CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height)
                
            elif PlayTurn.Mode()==MOVE: #asks the game controller if the CurrentSprite can move there
                PlayTurn.Move(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][0],GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][1] )
            elif PlayTurn.Mode()==AOE:
                PlayTurn.AOEAttack(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][0],GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][1])
                CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height)
            elif PlayTurn.Mode()==HEAL: #and GameBoard.getTile(mouse_pos_x, mouse_pos_y)[0]=="Actor":
                #print("heal called")
                PlayTurn.HealAction(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][0],GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][1])
                CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height)



        Characters.update(time)  
        GameBoard.update(time)
        if GameBoard.Animating() or paused:
            #print('Gameboard is animating or paused! Please be patient!', GameBoard.Animating(), paused)
            pass
        else:
            PlayTurn.update(time)

        #DEBUGGING: Grid
        if grid:#on a press of "g" the grid will be toggled
            for i in range(GameBoard._tileWidth):#draw vertical lines
                pygame.draw.line(screen, (0,0,0), (i*tileSize,0),(i*tileSize,GameBoard._width))
            for j in range(GameBoard._tileHeight):#draw horizontal lines
                pygame.draw.line(screen, (20,0,20), (0,j*tileSize),(GameBoard._height,j*tileSize))

        #moves the menu to the right if the camera is to the far left.
        if GameBoard.camTile()[0] < (myMenu.rect[2])// tileSize:
            myMenu.rect[0]=screen_width-myMenu.rect[2]-50
            CurrentSpriteInfo.rect[0]=screen_width-CurrentSpriteInfo.rect[2]
        else:
            myMenu.rect[0]=50
            CurrentSpriteInfo.rect[0]=0

        #brings up info for a sprite you are hovering over
        if GameBoard.getTile(mouse_pos_x, mouse_pos_y)[0]=="Actor" and paused==False:
                actor = GameBoard.getTile(mouse_pos_x, mouse_pos_y)[1]
                HoverWindow = CharacterInfo(actor, myfont, screen_height-150)
                screen.blit(HoverWindow.surface, HoverWindow.rect)
        screen.blit(CurrentSpriteInfo.surface, CurrentSpriteInfo.rect)
            
        if PlayTurn.CurrentSprite().Alignment()==FRIENDLY and paused==False:
            screen.blit(myMenu.surface, myMenu.rect)
        elif paused and PlayTurn.Mode()==LEVELUP:
            #print("Level up window for", CurrentSprite.Name())
            screen.blit(LevelUpWindow.surface, LevelUpWindow.rect)
        elif paused:
            screen.blit(PauseWindow.surface, PauseWindow.rect)

        pygame.display.flip()
Example #15
0
def callback():
    Menu([], i, o, "Menu update test menu",
         contents_hook=construct_contents).activate()
Example #16
0
    hash_ = input("Enter the hash [rand]: ")
    if not hash_:
        size = state.get().config["kademlia"]["keysize"] // 8
        hash_ = Hash(os.urandom(size))
    else:
        hash_ = Hash(base64.b64decode(bytes(hash_, "UTF-8")))
    s = state.get()
    s.kademlia.init_search(hash_)


# TODO: cmd arg for config path
if __name__ == "__main__":
    s = state.get()
    # Our own contact is always in the buckets
    if len(s.kademlia.buckets) > 1:
        s.kademlia.init_search(s.contact.hash)
        s.kademlia.init_search(Hash(os.urandom(s.bitsize // 8)))

    main_menu = Menu(
        [
            MenuOption("Client Status", print_status),
            MenuOption("Bucket Status", print_buckets),
            MenuOption("Shorty Status", print_shortlists),
            MenuOption("Add Contact", add_contact),
            MenuOption("Search for Contact", search_contact),
            MenuOption("Print Contacts", print_contacts),
        ]
    )

    main_menu.display()
Example #17
0
def callback():
    Menu([], i, o, "TOTP app main menu",
         contents_hook=contents_hook).activate()
class Game:
    def __init__(self,
                 width,
                 height,
                 tile_size,
                 width_aspect_ratio: float = 1.0,
                 grid_layers: int = 3,
                 flip_x: bool = False,
                 flip_y: bool = False):
        """
        Initialise our game
        :param width: The width in pixels of our game world
        :param height: The height in pixels of our game world
        :param tile_size: Our world is divided into a grid tiles, how large are the tiles in pixels
        :param width_aspect_ratio: Do we need to apply an aspect ratio to our horinzontal pixel sizes, assumed to be 1:1
        :param grid_layers: How many layers are there in our grid? First layer is assumed to have the collision tiles
        :param flip_x: Do we want to flip the position of x pixels, default 0 is left increasing towards the right
        :param flip_y: Do we want to flip the position of y pixels, default 0 is the top increasing towards the bottom
        """
        self.is_running: bool = False
        self.exit: bool = False
        self.debug: bool = True
        self.level = 1
        self.width: int = width
        self.height: int = height
        self.tile_size: float = tile_size
        self.grid_layers: int = grid_layers
        self.flip_x: bool = flip_x
        self.flip_y: bool = flip_y

        self.player: MovableEntity = None
        self.rabbit: MovableEntity = None
        self.npcs: List[MovableEntity] = []
        self.items: List[Entity] = []
        self.walls: List[Entity] = []
        self.timers = {}
        self.score: int = 0
        self.held_carrots: int = 0
        self.game_message: str = ""
        self.debug_message: str = ""

        self.grid: Grid = None

        MovableEntity.width_aspect_ratio = width_aspect_ratio

        self.menu: Menu = None
        self.setup_menu()

        self.load_level()

    def setup_menu(self):
        self.menu = Menu(text_lines=[
            "You must herd the the rabbit to the exit in the maze. ",
            "The rabbit will try to keep it's distance from you, ",
            "so you'll have herd the rabbit where you want it to go!",
            "",
            "Rabbits love carrots and will run towards them.",
            "Pickup a carrot before the rabbit you can place the",
            "carrots to encourage the rabbit through the maze.",
            "Blue sweets will make both yourself or the rabbit ",
            "move faster. The red potions will slow down movement."
            "",
            "",
            "    ↑ ↓ ← → to move/select",
            "    SPACE to place a carrot",
            "    ESCAPE to bring up this menu",
            "    ENTER to start",
        ],
                         is_modal=True,
                         width=self.width - 200,
                         height=self.height - 200)

        self.menu.add_button("Restart", None, self.menu_reset_game)
        self.menu.add_button("Quit", None, self.quit)

    def reset_game(self):
        """
        Restart the game and reset the game level
        :return:
        """
        self.is_running = False
        self.player = None
        self.rabbit = None
        self.npcs = []
        self.items = []
        self.walls = []
        for timer in self.timers:
            self.timers[timer].cancel()
        self.timers = {}
        self.score = 0
        self.held_carrots = 0
        self.game_message = ""
        self.debug_message = ""

        # reset and reassign the grid
        x_max = (self.width // self.tile_size) + 1
        y_max = (self.height // self.tile_size) + 1

        self.grid = Grid(x_max, y_max, self.tile_size, self.grid_layers,
                         self.flip_x, self.flip_y)
        Entity.grid = self.grid

    def menu_reset_game(self, button):
        """
        Handle the reset menu button press
        :param button:
        :return:
        """
        self.menu.close_menu(button)
        self.load_level()

    def quit(self, button):
        self.exit = True

    def update_game(self, delta_time):
        """
        Update the game state based on the elapsed time
        :param delta_time:
        :return:
        """
        if not self.is_running:
            return False

        if self.menu and self.menu.is_visible and self.menu.is_modal:
            return False

        items = self.items.copy()
        for item in items:
            item.think(delta_time)

        del items

        npcs = self.npcs.copy()
        for npc in npcs:
            npc.think(delta_time)
        del npcs

        self.player.think(delta_time)

        return True

    def load_level(self):
        """
        Load the level
        :return:
        """
        self.reset_game()

        with open(f"resources/level/{self.level:02}/layout.txt") as f:
            wall_lines = f.readlines()

        for row_index, row_value in enumerate(wall_lines):
            for col_index, col_value in enumerate(row_value):
                if col_value == "#":
                    self.add_wall(row_index, col_index)
                elif col_value == "@":
                    self.add_player(row_index, col_index)
                elif col_value == "&":
                    self.add_rabbit(row_index, col_index)
                elif col_value == ".":
                    self.add_speed_down(row_index, col_index)
                elif col_value == "*":
                    self.add_speed_up(row_index, col_index)
                elif col_value == "~":
                    self.add_carrot(row_index, col_index)
                elif col_value == "X":
                    self.add_end(row_index, col_index)

        self.start_rabbit()
        self.is_running = True

    def add_player(self, row, column):
        """
        Add the player to game map
        :param row:
        :param column:
        :return:
        """
        x, y = self.grid.get_pixel_center(row, column)

        self.player = MovableEntity(x,
                                    y,
                                    int(self.tile_size - 2),
                                    int(self.tile_size - 2),
                                    Colour.GREEN,
                                    0.10,
                                    is_solid=True,
                                    parent_collection=None,
                                    grid_layer=Layer.PLAYER.value,
                                    entity_type_id=EntityType.PLAYER.value)

        self.player.movement_type = MovementType.CONTROLLED
        self.player.base_speed = 5
        self.player.max_acceleration = 10
        self.player.acceleration_rate = 0.25
        self.player.load_shape_sprite("player", 3)

    def add_rabbit(self, row, column):
        """
        Add the rabbit to the game map
        :param row:
        :param column:
        :return:
        """
        x, y = self.grid.get_pixel_center(row, column)

        self.rabbit = ScoutingEntity(
            x,
            y,
            int(self.tile_size - 2),
            int(self.tile_size - 2),
            Colour.WHITE,
            0.10,
            False,
            self.npcs,
            target=self.player.id,
            target_offset=self.tile_size * 2,
            grid_layer=Layer.NPC.value,
            entity_type_id=EntityType.RABBIT.value,
            movement_type=MovementType.CHASE,
            search_for_entity_types=[EntityType.CARROT.value],
            search_tile_range=3)
        self.rabbit.base_speed = 4
        self.rabbit.max_acceleration = 8
        self.rabbit.movement_speed = 4
        self.rabbit.acceleration_rate = 0.5
        self.rabbit.load_shape_sprite("rabbit", 3)

    def remove_item(self, item):
        """
        Remove an item from the game map
        :param item:
        :return:
        """
        self.grid - item.id
        if item in self.items:
            self.items.remove(item)

    def add_speed_down(self, row, column):
        """
        Add a speed down item to the game map
        :param row:
        :param column:
        :return:
        """
        x, y = self.grid.get_pixel_center(row, column)
        item = Entity(x,
                      y,
                      int(self.tile_size - 2),
                      int(self.tile_size - 2),
                      Colour.RED,
                      5,
                      False,
                      self.items,
                      grid_layer=Layer.ITEMS.value)
        item.on_collide = self.apply_speed_down
        item.load_shape_sprite("speed_down", 3)

    def apply_speed_down(self, apply_from, apply_to):
        """
        On an entity `apply_to` colliding with `apply_from` apply a speed down to `apply_to` and remove `apply_from`
        from the game map
        :param apply_from:
        :param apply_to:
        :return:
        """
        try:
            acceleration_modifier = apply_to.acceleration_rate / 2
            apply_to.acceleration_rate -= acceleration_modifier
        except AttributeError:
            print("tried to apply speed down wrong thing?", apply_to,
                  type(apply_to))
            return
        self.remove_item(apply_from)

    def add_speed_up(self, row, column):
        """
        Add a speed up item to the game map
        :param row:
        :param column:
        :return:
        """
        x, y = self.grid.get_pixel_center(row, column)
        item = Entity(x,
                      y,
                      int(self.tile_size - 2),
                      int(self.tile_size - 2),
                      Colour.BLUE_LIGHT,
                      5,
                      False,
                      self.items,
                      grid_layer=Layer.ITEMS.value)
        item.on_collide = self.apply_speed_up
        item.load_shape_sprite("speed_up", 2)

    def apply_speed_up(self, apply_from, apply_to):
        """
        On an entity `apply_to` colliding with `apply_from` apply a speed up to `apply_to` and remove `apply_from`
        from the game map
        :param apply_from:
        :param apply_to:
        :return:
        """
        try:
            acceleration_modifier = apply_to.acceleration_rate / 2
            apply_to.acceleration_rate += acceleration_modifier
        except AttributeError:
            print("tried to apply speed up wrong thing?", apply_to,
                  type(apply_to))
            return
        self.remove_item(apply_from)

    def add_carrot(self, row, column):
        """
        Add a carrot to the game map
        :param row:
        :param column:
        :return:
        """
        x, y = self.grid.get_pixel_center(row, column)
        carrot = self.place_carrot(x, y)
        carrot.player_placed = False

    def place_carrot(self, x, y):
        """
        Place a carrot at a given x,y position
        :param x:
        :param y:
        :return:
        """
        item = Entity(x,
                      y,
                      int(self.tile_size - 2),
                      int(self.tile_size - 2),
                      Colour.ORANGE,
                      5,
                      False,
                      self.items,
                      grid_layer=Layer.ITEMS.value,
                      entity_type_id=EntityType.CARROT.value)
        item.on_collide = self.eat_carrot
        item.load_shape_sprite("carrot", 3)
        return item

    def player_drop_carrot(self):
        """
        Place a carrot at the players position
        :return:
        """
        if self.held_carrots > 0:
            self.held_carrots -= 1
            x, y = self.player.grid_pixels
            carrot = self.place_carrot(x, y)
            carrot.player_placed = True

    def eat_carrot(self, carrot, eater):
        """
        If `eater` is our rabbit, then remove carrot from the game map and increase the score
        :param carrot:
        :param eater:
        :return:
        """
        if eater.id not in [self.rabbit.id, self.player.id]:
            return

        if eater.id == self.rabbit.id:
            self.score += 1
        elif eater.id == self.player.id:
            if carrot.player_placed:
                return
            self.held_carrots += 1

        self.remove_item(carrot)

    def add_end(self, row, column):
        """
        Add the end/goal to the game map
        :param row:
        :param column:
        :return:
        """
        x, y = self.grid.get_pixel_center(row, column)
        item = Entity(x, y, int(self.tile_size), int(self.tile_size),
                      Colour.GREY, 5, False, self.items, Layer.WORLD.value)
        item.on_collide = self.check_end
        item.load_shape_sprite("exit", 3)

    def check_end(self, goal, other):
        """
        If something collides with the goal check if it's the rabbit
        If it is the rabbit then we've completed the level
        :param goal:
        :param other:
        :return:
        """
        if other.id != self.rabbit.id:
            return

        self.game_message = "Next Level!"
        self.rabbit.movement_type = MovementType.NONE
        self.rabbit.target = None

        if "change_level" not in self.timers:
            self.timers["change_level"] = Timer(2.0, self.change_level)
            self.timers["change_level"].start()

    def change_level(self):
        """
        Change to the next level
        :return:
        """
        self.timers["change_level"].cancel()
        self.is_running = False
        self.level += 1
        self.load_level()

    def start_rabbit(self):
        """
        Make the rabbit follow the player, set the rabbits target to be the player and set it's `target_offset`
        :return:
        """
        self.rabbit.movement_speed = 3

    def add_wall(self, row, column):
        """
        Add a wall to the game world
        :param row:
        :param column:
        :return:
        """
        # add_at_grid_position
        x, y = self.grid.get_pixel_center(row, column)
        Entity(x,
               y,
               int(self.tile_size),
               int(self.tile_size),
               Colour.BROWN,
               5,
               True,
               self.walls,
               grid_layer=Layer.WORLD.value)

    def get_grid_data(self, x, y):
        """
        Get the data in our grid at a given x,y pixel position
        :param x:
        :param y:
        :return:
        """
        return self.grid[x, y]

    def debug_x_y(self, x, y):
        """
        Print out debug information our grid at a given x,y pixel position
        :param x:
        :param y:
        :return:
        """
        print("id:", self.get_grid_data(x, y), "x:", x, "y:", y)
        print(
            "nearby:",
            self.grid.query(x, y, k=8,
                            distance_upper_bound=self.tile_size * 2))

        self.game_message = str(self.rabbit.destination)

    def reset_level(self):
        """
        Reset the current level
        :return:
        """
        self.load_level()

    def on_key_press(self, key):
        """
        Respond to key press

        :param key:
        :return:
        """
        if not self.is_running:
            return

        player = self.player
        rabbit = self.rabbit

        if not self.menu.is_visible:
            if key == Keys.LEFT:
                player.set_direction(MovementDirection.WEST)
            elif key == Keys.RIGHT:
                player.set_direction(MovementDirection.EAST)
            elif key == Keys.UP:
                player.set_direction(MovementDirection.NORTH)
            elif key == Keys.DOWN:
                player.set_direction(MovementDirection.SOUTH)
            elif key == Keys.R:
                self.reset_level()

        if self.debug:
            # debug stuffs
            if key == Keys.PERIOD:
                player.tick_rate -= 1
            elif key == Keys.COMMA:
                player.tick_rate += 1
            elif key == Keys.W:
                rabbit.movement_type = MovementType.NONE
                rabbit.target = None
                rabbit.move_up()
            elif key == Keys.A:
                rabbit.movement_type = MovementType.NONE
                rabbit.target = None
                rabbit.move_left()
            elif key == Keys.D:
                rabbit.movement_type = MovementType.NONE
                rabbit.target = None
                rabbit.move_right()
            elif key == Keys.S:
                rabbit.movement_type = MovementType.NONE
                rabbit.target = None
                rabbit.move_down()
            elif key == Keys.X:
                self.start_rabbit()

    def on_key_release(self, key):
        """
        Respond to key release
        :param key:
        :return:
        """
        player: MovableEntity = self.player
        menu: Menu = self.menu

        if not self.menu.is_visible:
            if key == Keys.LEFT:
                if player.movement_direction == MovementDirection.WEST:
                    player.set_direction(MovementDirection.NONE)
            elif key == Keys.RIGHT:
                if player.movement_direction == MovementDirection.EAST:
                    player.set_direction(MovementDirection.NONE)
            elif key == Keys.UP:
                if player.movement_direction == MovementDirection.NORTH:
                    player.set_direction(MovementDirection.NONE)
            elif key == Keys.DOWN:
                if player.movement_direction == MovementDirection.SOUTH:
                    player.set_direction(MovementDirection.NONE)
            elif key == Keys.SPACE:
                self.player_drop_carrot()
        else:
            if key == Keys.UP:
                menu.decrement_selected_button()
            elif key == Keys.DOWN:
                menu.increment_selected_button()
            elif key == Keys.RETURN:
                menu.click_selected_button()

        if key == Keys.ESCAPE:
            # resetting the back button text to override the value set at the start
            self.menu.button_list[0].text = "Back"
            self.menu.is_visible = not self.menu.is_visible
Example #19
0
def callback():
    main_menu_contents = [
      ["Hardware version", hw_version_ui],
      ["Flash GSM modem", flash_image_ui],
      ["Settings", change_settings]]
    Menu(main_menu_contents, i, o, "ZP hardware setup menu").activate()
Example #20
0
 def idle_loop(self):
     Menu.idle_loop(self)
     self.check_character_state()
Example #21
0
 def set_keymap(self):
     Menu.set_keymap(self)
     self.i.set_streaming(self.on_key_pressed)
Example #22
0
 def on_start(self):
     mc = [["WiFi country", self.change_wifi_country]]
     Menu(mc, self.i, self.o, name="WiFi settings app main menu").activate()
Example #23
0
 def before_activate(self):
     Menu.before_activate(self)
     self.last_input_time = -self.input_delay
 def __init__(self):
     self.ui = Menu()
class Main:
    def __init__(self):
        self.ui = Menu()

    def run(self):
        self.ui.main_menu()
Example #26
0
def callback():
    Menu(main_menu_contents, i, o, "USB app menu").activate()
Example #27
0
    def __init__(self, client, game):

        self.client = client
        self.game = game

        self.username = None
        self.opponent = None

        self.version = TextBox((100, 60), (50, 1700),
                               font=Font.f(30),
                               text_color=C.GREY,
                               text=str(Spec.JSON_DATA['version']))

        pages = [(Spec.PAGE_MENU, Menu(client)),
                 (Spec.PAGE_CONN, Connection(client)),
                 (Spec.PAGE_FRIENDS, Friends(client)),
                 (Spec.PAGE_EDITOR, Editor(client)),
                 (Spec.PAGE_PROFIL, Profil(client)),
                 (Spec.PAGE_OFFLINE, Offline(client))]

        super().__init__(pages)

        self.add_frame_function(
            self.look_friends,
            active_pages=[Spec.PAGE_MENU, Spec.PAGE_FRIENDS])
        self.add_frame_function(
            self.look_demand_friends,
            active_pages=[Spec.PAGE_MENU, Spec.PAGE_FRIENDS])
        self.add_frame_function(
            self.look_game_demands,
            active_pages=[Spec.PAGE_MENU, Spec.PAGE_FRIENDS])
        self.add_frame_function(
            self.manage_notif,
            active_pages=[Spec.PAGE_MENU, Spec.PAGE_FRIENDS])
        self.add_frame_function(self.look_comm_login,
                                active_pages=Spec.PAGE_CONN)
        self.add_frame_function(self.look_general_chat_msg,
                                active_pages=Spec.PAGE_MENU)
        self.add_frame_function(
            self.look_private_chat_msg,
            active_pages=[Spec.PAGE_MENU, Spec.PAGE_FRIENDS, Spec.PAGE_PROFIL])
        self.add_frame_function(
            self.look_rdfr, active_pages=[Spec.PAGE_FRIENDS, Spec.PAGE_PROFIL])
        self.add_frame_function(self.look_rdg,
                                active_pages=[Spec.PAGE_FRIENDS])
        self.add_frame_function(self.look_game_notif, active_pages=None)
        self.add_frame_function(self.look_profil_infos,
                                active_pages=Spec.PAGE_FRIENDS)
        self.add_frame_function(self.manage_updater,
                                active_pages=Spec.PAGE_MENU)

        # set log out logic
        page_menu = self.get_page(Spec.PAGE_MENU)
        page_menu.add_button_logic('b logout', self.logic_logout)

        # set game reference in offline page
        self.get_page(Spec.PAGE_OFFLINE).game = self.game

        # set up updater - start download
        self.updater = self.get_page(Spec.PAGE_MENU).get_component('updater')
        self.updater.load_server_data()
Example #28
0
 def deactivate(self):
     Menu.deactivate(self)
     self.i.remove_streaming()
Example #29
0
def settings():
    c = [["Update ZPUI", update]]
    Menu(c, i, o, "Global settings menu").activate()
Example #30
0
 def process_contents(self):
     Menu.process_contents(self)
     if self.prepend_numbers:
         self.prepend_entry_text()
Example #31
0
def settings_menu():
    mc = [["Manage contents", manage_contents],
          ["App open entries", app_open_entries]]
    #      ["Set ordering", set_ordering]]
    Menu(mc, i, o, name="ZeroMenu settings menu").activate()
Example #32
0
def change_settings():
    menu_contents = [
      ["Set mtkdownload path", set_mtkdownload_path],
      ["Set firmware path", set_sim_firmware_path, set_default_sim_firmware_path]]
    Menu(menu_contents, i, o, "ZP hardware setup settings menu").activate()
Example #33
0
def init_app(input, output):
    global if_menu, callback, i, o
    i = input; o = output
    if_menu = Menu([], i, o, "Interface selection menu")
    if_menu.activate = activate_wrapper(if_menu.activate) #Decorating around the menu.activate module so that every time menu is activated interface data is refreshed
    callback = if_menu.activate
Example #34
0
def filtered_units():
    menu_contents = []
    units = systemctl.list_units("unit_type", config["allowed_types"])
    for unit in units:
        menu_contents.append([unit["name"], lambda x=unit: unit_menu(x)])
    Menu(menu_contents, i, o, "Systemctl: filtered unit list menu").activate()
Example #35
0
def change_settings():
    settings = [["Scan range", change_range]]
    Menu(settings, i, o, "I2C tools app settings menu").activate()
Example #36
0
class Canvas:
    def __init__(self, size, **kwargs):
        self.objects = {}
        self.nextObjectId = 0

        self.animations = {}
        self.nextAnimationId = 0

        self.size = size
        self.backgroundColor = kwargs.get("backgroundColor",
                                          colors.background_color)
        self.defaultColor = kwargs.get("defaultColor", colors.default_color)

        self.ratio = kwargs.get("ratio", 1.0)
        self.center = ensureArray(
            kwargs.get("center", [self.size[0] / 2, self.size[1] / 2]))

        self.backend = kwargs.get("backend", PygameBackend)(size, self,
                                                            **kwargs)

        self.time = kwargs.get("startTime", 0)
        self.deltaTime = None

        self.data = OrderedDict({})

        self.debug = kwargs.get("debug", False)
        self.handler = EventHandler(types=["tick"])
        self.on("tick", type(self).onTick)

        self.fps = self.backend.fps
        self.frame_time = 1000 / self.fps

        if self.backend.interactive: self.init_interactive(**kwargs)
        if self.debug: self.init_debug(**kwargs)

    def init_debug(self, **kwargs):
        self.addObject(
            Text((0, 0),
                 "",
                 "monospace",
                 color=colors.black,
                 onBeforeDraw=setTextToTime,
                 bindings={
                     "start":
                     lambda: self.inverseTransform((10, self.size[1] - 20))
                 }))

#
#
#  EVENTS
#
#

    def fire(self, type, *args, **kwargs):
        self.handler.fire(self, type, *args, **kwargs)

    def on(self, type, function):
        self.handler.on(type, function)

    def init_interactive(self, **kwargs):
        self.handler.add("mouseDown", "mouseUp", "mouseMove", "keyPress")

        self.menu = Menu(self)
        self.menu.addOption("Quit", lambda canvas: sys.exit(), hotkey='q')

        if kwargs.get("movement", True):
            self.handler.on("mouseDown", zooming)
            self.handler.on("mouseMove", panning)
        if kwargs.get("screenCap", True):
            self.handler.on("keyPress", screenCap)
        if self.debug:
            self.handler.on("mouseDown", printPoint)

        self.handler.on("keyPress",
                        openMenuFunction(kwargs.get("menu_key", 'e')))

    def displayMenu(self):
        print("\n" + '\n'.join([
            f"[{option.hotkey}] {option.name}"
            for option in self.menu.getOptions() if option.enabled
        ]))
        self.menu.choose(input('> ')).execute()

    def onTick(self, time_passed):
        pass

#
#
#  GEOMETRY
#
#

    @property
    def min_x(self):
        return -self.center[0] / self.ratio

    @property
    def max_x(self):
        return (self.size[0] - self.center[0]) / self.ratio

    @property
    def min_y(self):
        return -(self.size[1] - self.center[1]) / self.ratio

    @property
    def max_y(self):
        return self.center[1] / self.ratio

    @property
    def transformation(self):
        return self.backend.transformation @ [[self.ratio, 0], [0, self.ratio]]

    @property
    def inverse_transformation(self):
        return self.backend.inverse_transformation @ [[1.0 / self.ratio, 0],
                                                      [0, 1.0 / self.ratio]]

    def transform(self, point):
        return tuple(
            [int(x) for x in (self.transformation @ point + self.center)])

    def inverseTransform(self, point):
        return self.inverse_transformation @ (point - self.center)

    def inRange(self, point):
        return (self.min_x <= point[0] <= self.max_x
                and self.min_y < point[1] < self.max_y)

#
#
#  OBJECTS
#
#

    def addObject(self, object):
        object.attachTo(self)
        return object.id

    def getObjectId(self):
        self.nextObjectId += 1
        return f"sprite_{self.nextObjectId - 1}"

    def getObjectColor(self):
        return self.defaultColor  # TODO

#
#
#  ANIMATIONS
#
#

    def addAnimation(self, animation):
        animation.attachTo(self)
        return animation.id

    def getAnimationId(self):
        self.nextAnimationId += 1
        return f"animation_{self.nextAnimationId - 1}"

    def pauseAnimations(self):
        for id, animation in self.animations.items():
            animation.pause()

    def unpauseAnimations(self):
        for id, animation in self.animations.items():
            animation.unpause()

    def toggleAnimations(self):
        for id, animation in self.animations.items():
            animation.togglePause()

#
#
#  FRAMES
#
#

    def newFrame(self):
        self.backend.fill(self.backgroundColor)

    def advance(self, time_passed=None):  # milliseconds
        if time_passed is None:
            time_passed = self.frame_time
        self.newFrame()
        self.deltaTime = time_passed
        self.time += self.deltaTime
        self.update(time_passed)

    def play(self, time):  # seconds
        n_frames = int(time * self.fps)
        for i in range(1, n_frames + 1):
            if self.debug:
                print(f"Playing {int((i / n_frames) * 100)}%\r", end="")
            self.advance()

    def jump(self, time):
        self.newFrame()
        self.deltaTime = None
        self.time = time
        self.update()

    def update(self, time_passed=None):
        for id, obj in self.objects.items():
            obj.beforeDraw()
            obj.draw()
        self.fire("tick", time_passed)
        self.backend.update()

    def loop(self, frequency=None):  # frequency in Hz; Can't be stopped
        if not self.backend.interactive:
            raise NotImplemented
        while 1:
            if frequency is None:
                frequency = self.backend.fps
            self.advance(int(1000 / frequency))  # in ms
            sleep(1 / frequency)  # in seconds

#
#
#  SAVING
#
#

    def startRecording(self, filename, **kwargs):
        self.backend.startRecording(filename, **kwargs)

    def stopRecording(self):
        self.backend.stopRecording()

    def saveFrame(self, filename):
        self.backend.saveFrame(filename)


#
#
#  DRAWING
#
#

    def putPixel(self, position, color):
        self.backend.putPixel(self.transform(position), color)

    def drawLine(self, start, end, color, **kwargs):
        self.backend.drawLine(self.transform(start), self.transform(end),
                              tuple(color), **kwargs)

    def drawRectangle(self, start, width, height, color, **kwargs):
        self.backend.drawRectangle(self.transform(start),
                                   int(width * self.ratio),
                                   int(height * self.ratio), tuple(color),
                                   **kwargs)

    def drawCircle(self, center, radius, color, **kwargs):
        self.backend.drawCircle(self.transform(center),
                                int(radius * self.ratio), tuple(color),
                                **kwargs)

    def drawPolygon(self, points, color, **kwargs):
        self.backend.drawPolygon([self.transform(p) for p in points],
                                 tuple(color), **kwargs)

    def drawConvexPolygon(self, points, color, **kwargs):
        self.backend.drawConvexPolygon([self.transform(p) for p in points],
                                       tuple(color), **kwargs)

    def drawImage(self, point, image):
        self.backend.drawImage(self.transform(point), image)

    def drawArrow(self, start, end, color):
        length = np.sqrt((start[0] - end[0])**2 + (start[1] - end[1])**2)
        p1, p2 = arrow_points(start, end, min(length / 4, .20), np.pi / 6)
        p1, p2, start, end = map(self.transform, [p1, p2, start, end])
        self.backend.drawLine(start, end, tuple(color), width=2)
        self.backend.drawConvexPolygon([end, p1, p2], tuple(color))

    def drawText(self, point, text, font, color, **kwargs):
        self.backend.drawText(self.transform(point), text, font, tuple(color),
                              **kwargs)
Example #37
0
    def drop(self):
        # prompt to drop something; drop it
        xu = self.map.size.x//4
        yu = self.map.size.y//4
        b = Menu( Position(xu,yu), Position(xu*2,yu*2), title="Drop" )
        
        b.add('x','Do nothing')
        b.add_spacer()

        for idx in range(len(self.items)):
            v = self.items[idx]
            if not v is None:
                b.add('%d'%(idx+1),str(v))

        b.add_spacer()
        idx += 1

        for k in self.slot_keys:
            idx += 1
            if not self.slot_items[k] is None:
                b.add('%d'%idx,str(self.slot_items[k]))

        c = b.get_key()
                    
        item_index = None
        if isinstance(c,str) and c.isnumeric():
            item_index = int(c) - 1
        self.redraw_screen()
        del b

        if item_index is None:
            return 0.0

        i = None
        if item_index < len(self.items):
            i = self.items[item_index]
            self.items[item_index] = None
        elif item_index < len(self.items)+len(self.slot_keys):
            k = self.slot_keys[item_index-len(self.items)]
            i = self.slot_items[k]
            self.slot_items[k] = None

        if not i is None:
            i.drop_at(self.pos)
            self.map.add(i)
            return self.ITEM_DROP_COST 

        return 0.0
Example #38
0
    if not port:
        port = '2983'
    addr = Address(ipaddr, int(port))

    global CLIENT
    CLIENT = Client(addr)


def print_events():
    if CLIENT is None:
        print("No client connected")
    else:
        print(CLIENT.events)


def subscribe():
    if CLIENT is None:
        print("No client connected")
    else:
        event = input("Enter the event name: ")
        CLIENT.subscribe(event)


if __name__ == '__main__':
    main_menu = Menu([
        MenuOption('Connect', connect),
        MenuOption('Print Events', print_events),
        MenuOption('Subscribe', subscribe)
    ])
    main_menu.display()
Example #39
0
maze = MazeCreator(10, 10)
maze.create((0, 0))

# Create all game surfaces
hotbar = Hotbar()
inv = Inventory()
inspector = Inspector()
tab = Tab()
equipment = Equipment()
attributes = Attributes()
xp_bar = XPBar()
item_drop_display = ItemDropDisplay()
board = Board(2050, 2050)
st = SkillTree(width, height)
menu = Menu([("Resume", lambda: exec("show_menu = False", globals())),
             ("Help", lambda: exec("")),
             ("Quit", lambda: exec("running = False", globals()))])

# Create entities
player = Player()
enemies = [
    LargeEnemy((380 * randint(1, 5)) - 190, (380 * randint(1, 5)) - 190)
    for i in range(2)
]
melee_swing = MeleeSwing(player, hotbar[hotbar.selected_pos][1])

healthbar = HealthBar(player.health)
manabar = ManaBar(player.mana)

# Misc Variables
font = pygame.font.SysFont("Courier", 15, True)
Example #40
0
def init_app(input, output):
    global main_menu, callback, i, o
    i = input
    o = output
    main_menu = Menu(main_menu_contents, i, o, "Volume menu")
    callback = main_menu.activate
Example #41
0
File: main.py Project: VicSera/UBB
import time
from random import seed

from controller import Controller
from repository import Repository
from ui import Menu

if __name__ == "__main__":
    seed(time.time())
    repository = Repository()
    controller = Controller(repository)
    menu = Menu(controller)
    menu.run()
Example #42
0
    def activate(self, activator=None):
        if CountUpTile.activate(self, activator):
            xu = self.map.size.x // 4
            yu = self.map.size.y // 4
            b = Menu(Position(xu, yu),
                     Position(xu * 2, yu * 2),
                     title="Trap Control")
            b.add('1', "View traps")
            b.add(
                '2',
                "%s traps" % (TrapConsole.traps_on and 'Disable' or 'Enable'))
            b.add('3', "Set off traps")
            b.add('x', "Exit")

            c = b.get_key()
            del b

            traps = self.map.find_all(Trap, Tile)

            if c == '1':
                for t in traps:
                    t.visible_to_player = True
                self.map.player.handle_keys()

            elif c == '2':
                for trap in traps:
                    trap.enabled = TrapConsole.traps_on

                TrapConsole.traps_on = not TrapConsole.traps_on

            elif c == '3':
                for trap in traps:
                    trap.trip()

            return True
        return False
Example #43
0
def pomodoro_options_menu():
    menu_contents = [["Acknowledge", e_wr(ack_notification)],
                     ["Start", e_wr(start_monitoring)],
                     ["Start break", e_wr(start_break)],
                     ["Stop", e_wr(stop_monitoring)]]
    Menu(menu_contents, i, o, "Pomodoro options menu").activate()
Example #44
0
 def on_start(self):
     """gets called when application is activated in the main menu"""
     super(SkeletonApp, self).on_start()  # call to base class method. Not mandatory but good practice
     Menu(self.main_menu_contents, self.i, self.o, "Skeleton app menu").activate()
Example #45
0
def all_units():
    menu_contents = []
    units = systemctl.list_units()
    for unit in units:
        menu_contents.append([unit["name"], lambda x=unit: unit_menu(x)])
    Menu(menu_contents, i, o, "Systemctl: all unit list menu").activate()
Example #46
0
 def idle_loop(self):
     Menu.idle_loop(self)
     self.refresh()