示例#1
0
 def __init__(self):
     self.sm = SpriteManager()
     self.button_new_game = Button(352, 0, 96, 23, sprite=self.sm.sprites['new_game_button'], callback=self.start_new_game)
     self.button_load_game = Button(378, 23, 44, 23, sprite=self.sm.sprites['load_button'], callback=self.load_game)
     self.button_exit = Button(378, 46, 41, 23, sprite=self.sm.sprites['exit_button'], callback=self.exit_game)
     self.version_label = Label(0, 580, "Version 0.1")
     event_manager.event_manager.add_listener(event_manager.MESSAGE_MOUSE_UP, self)
示例#2
0
    def init(self, game):
        btn_inv = Button((globals.VIEW_OFFSET[0], globals.WINDOW_HEIGHT - 100), 'Inventory')
        btn_inv.on_click = self.open_inventory

        self.add_entity(btn_inv)
        self.add_entity(Label((globals.VIEW_OFFSET[0], globals.WINDOW_HEIGHT - 40), 'Status'), 'lbl_status')
        self.add_entity(Label((globals.VIEW_OFFSET[0] + 150, 10)), 'lbl_hunger')
        self.add_entity(Label((globals.WINDOW_WIDTH - 200, 10)), 'lbl_tod')
 def create_library_list(self):
     y = 80
     for category in SelectMusic.CATEGORIES:
         library_option_button = Button(Rect(40, y, 240, 40),
                                        34,
                                        Label.LEFT,
                                        text=category)
         library_option_button.on_tapped.connect(self.select_library_option)
         self.add_child(library_option_button)
         y += 80
示例#4
0
 def drawAdditionalContent(self, data, appendButtons=[]):
     self.allSprites = []
     text = Text(text="Player %s Win!" % (data + 1),
                 fontSize=50,
                 alignment=CENTER_MIDDLE,
                 location=(self.pageSize[POS_X]/2, self.pageSize[POS_Y]/4),
                 basePoint=self.popUpPageBasePoint)
     self.allSprites.append(text)
     for appendButton in appendButtons:
         buttonSprite = Button(appendButton["func"],
                               buttonSize=(150, 40),
                               text=appendButton["name"],
                               fontSize=30,
                               location=(self.pageSize[POS_X] if appendButton["location"][POS_X] == PARENT_SIZE_WIDTH  else appendButton["location"][POS_X],
                                         self.pageSize[POS_Y] if appendButton["location"][POS_Y] == PARENT_SIZE_HEIGHT  else appendButton["location"][POS_Y]),
                               alignment=appendButton["alignment"],
                               basePoint=self.popUpPageBasePoint)
         buttonSprite.listen(appendButton["listener"])
         self.allSprites.append(buttonSprite)
示例#5
0
    def __init__(self, parent=None):
        super().__init__()

        button = QPushButton('Me!')
        strip = QHBoxLayout()
        strip.setAlignment(Qt.AlignTop)
        self.setLayout(strip)
        strip.addWidget(Button())

        verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Expanding,
                                     QSizePolicy.Minimum)
        strip.addItem(verticalSpacer)
    def generate_rooms(self):
        checkbox_empty_image = Image('checkbox_empty',
                                     filename='checkbox_empty.png')
        checkbox_filled_image = Image('checkbox_filled',
                                      filename='checkbox_filled.png')
        members = self.sonos.group_members
        y = 80
        for zone in self.sonos.potential_members:
            select_room_button = Button(Rect(60, y, 280, 30),
                                        34,
                                        Label.LEFT,
                                        image=checkbox_empty_image,
                                        checked_image=checkbox_filled_image,
                                        text=zone)
            select_room_button.on_tapped.connect(self.select_room)
            self.add_child(select_room_button)
            self.room_buttons.append(select_room_button)
            y += 60

            if zone in members:
                # this zone is already a member
                select_room_button.checked = True
示例#7
0
    def __init__(self, scroller, target, width=1280, height=720):
        super().__init__(57, 67, 63, 0, width=width, height=height)
        
        picDir = '../res/popup_resources/choose_hero_popup.png'

        self.scroller = scroller
        self.opacity = 0
        self.target = target

        self.image = pyglet.image.load(picDir)
        self.spr = cocos.sprite.Sprite(self.image, position=(640,360))

        self.backButton = Button(1070,627, '../res/popup_resources/exit_button.png',self,self.hide)
        self.backButton.setHasHighlight('../res/popup_resources/exit_button_h.png')

        self.highlight = False
        self.onHover = False
        self.highlight = True

        self.add(self.backButton,1)
        self.add(self.spr,0)

        self.spr.do(Hide())
        self.backButton.spr.do(Hide())
    def __init__(self, sonos):
        ModalScene.__init__(self, sonos.current_zone)

        self.sonos = sonos

        in_party_mode = Sonos.in_party_mode()

        ##### Party Mode On Button #####
        icon_party_on_image = Image('icon_party_on',
                                    filename='icon_party_on.png')
        self.party_on_button = Button(Rect(270, 20, 30, 30),
                                      image=icon_party_on_image)
        self.party_on_button.hidden = in_party_mode
        self.party_on_button.on_tapped.connect(self.group_all)
        self.add_child(self.party_on_button)

        ##### Party Mode Off Button #####
        icon_party_off_image = Image('icon_party_off',
                                     filename='icon_party_off.png')
        self.party_off_button = Button(Rect(270, 20, 30, 30),
                                       image=icon_party_off_image)
        self.party_off_button.on_tapped.connect(self.group_none)
        self.party_off_button.hidden = not in_party_mode
        self.add_child(self.party_off_button)

        ##### Done Button #####
        self.done_button = Button(Rect(20, 430, 280, 40), 40, text='Done')
        self.done_button.on_tapped.connect(self.done)
        self.add_child(self.done_button)

        self.room_buttons = []

        self.unchanged = True

        self.layout()
        self.generate_rooms()
示例#9
0
    def init(self, game):
        cell = game.hex_map.get_cell(globals.CAMERA_ROW, globals.CAMERA_COLUMN)
        cursor = EditorObject(cell)
        self.add_entity(cursor)

        ico = Icon((globals.VIEW_OFFSET[0], globals.WINDOW_HEIGHT - 100), tile_back=blue, data='water')
        ico.on_click = self.on_icon_selected
        self.add_entity(ico)

        ico = Icon((globals.VIEW_OFFSET[0] + 40, globals.WINDOW_HEIGHT - 100), tile_back=green, data='grass')
        ico.on_click = self.on_icon_selected
        self.add_entity(ico)

        ico = Icon((globals.VIEW_OFFSET[0] + 80, globals.WINDOW_HEIGHT - 100), tile_back=yellow, data='sand')
        ico.on_click = self.on_icon_selected
        self.add_entity(ico)

        btn = Button((globals.VIEW_OFFSET[0], globals.WINDOW_HEIGHT - 50), 'Save')
        btn.on_click = self.on_save_map
        self.add_entity(btn)

        btn = Button((globals.VIEW_OFFSET[0] + 150, globals.WINDOW_HEIGHT - 50), 'Load')
        btn.on_click = self.on_load_map
        self.add_entity(btn)
    def __init__(self, title):
        Scene.__init__(self)

        self.background_color = colors.MODAL

        # Title label
        self.title_label = Label(Rect(50, 20, 220, 40), title, 40,
                                 colors.WHITE)
        self.add_child(self.title_label)

        ##### Back Button #####
        icon_back_image = Image('icon_back', filename='icon_back.png')
        self.back_button = Button(Rect(20, 20, 30, 30), image=icon_back_image)
        self.back_button.on_tapped.connect(self.back)
        self.add_child(self.back_button)

        self.layout()
    def generate_room_list(self):
        ''' Generates a list of rooms/zones

        If a room is a zone coordinator and has members in its group,
        it will be displayed first with all its members appended to it
        with commas'''
        y = 80
        for zone in Sonos.get_zone_groups():
            if zone["is_coordinator"]:
                button_text = zone["name"]
                for member in zone["members"]:
                    button_text += ", {}".format(member)
                room_button = Button(Rect(20, y, 280, 40),
                                     30,
                                     text=button_text)
                room_button.on_tapped.connect(self.change_room)
                self.add_child(room_button)
                y += 60
    def create_items(self):
        # Clean up any old buttons before addings new ones
        for button in self.list_buttons:
            button.remove()

        self.update_list_navigation()
        y = 0
        for index, item in enumerate(self.items):
            if index >= self.list_index and index < (self.list_index +
                                                     self.per_page):
                item_button = Button(Rect(40, y, 240, 30),
                                     30,
                                     Label.LEFT,
                                     text=item)
                item_button.on_tapped.connect(self.select_item)
                self.add_child(item_button)
                self.list_buttons.append(item_button)
                y += 50
示例#13
0
def fill_widgets(player, widgets, config, game_state):
    # Fills the needed widgets on the screen depending the current game state.

    # Fill inventory full of widgets based on the items in the inventory.
    if game_state == GameState.show_inventory:
        x = int(config['window_width'] / 2) - 35
        y = 25
        color = config['button']['inventory']['item']['default']
        selected_color = config['button']['inventory']['item']['selected']
        for item in player.alive.inventory.items:
            text = '%s - %s' % (item.name, item.quantity)
            widgets.append(
                Button(x,
                       y,
                       text,
                       color,
                       selected_color,
                       item.action,
                       attached=item))
            y += 6
示例#14
0
    def __init__(self) -> None:
        self.name = "enter your name"
        self.letter = "A"
        self.buttons = []
        self.move_timer = 0
        self.plate = pygame.Surface((300 * s.scale, 300 * s.scale))

        self.game_over = Text("Name change", (255, 255, 255), 30,
                              Position(s.WIN_W // 2, s.WIN_H // 4))
        self.name_text = Text(self.name, (255, 255, 255), 30,
                              Position(s.WIN_W // 2, s.WIN_H * 2 // 4))
        self.press_a_btn = Text(
            "A to select letter",
            (255, 255, 255),
            15,
            Position(s.WIN_W // 2, s.WIN_H * 3 // 4),
        )
        self.press_start_btn = Text(
            "Start to confirm",
            (255, 255, 255),
            15,
            Position(s.WIN_W // 2, s.WIN_H * 3 // 4 + 15),
        )
        self.press_b_btn = Text(
            "B to clear letter",
            (255, 255, 255),
            15,
            Position(s.WIN_W // 2, s.WIN_H * 3 // 4 + 30),
        )
        x0 = 0
        y0 = 0
        for letter in LETTERS:
            x = x0 * 15 * s.scale + 90 * s.scale
            y = y0 * 20 * s.scale + 75 * s.scale
            self.buttons.append(
                Button(letter, letter, 14, Position(x, y), self.plate))
            x0 += 1
            if x0 == 9:
                x0 = 0
                y0 += 1
示例#15
0
# Values start maxed out
tree_parameters = {
    'pos': ((WINDOW_WIDTH - 400) / 2 + 400, WINDOW_HEIGHT),
    'angle': 90,
    'tick': 15,
    'vel': 10,
    'number': 14,
    'division_ratio': 2,
    'division_angle': 90,
    'divide_angles': True,
    'divide_distance': True,
    'fruits': False
}

buttons = {
    'button_reset': Button((50, WINDOW_HEIGHT - 125, 300, 75), 'Reset', outline_width=4),
    'button_hide': Button((415, 25, 25, 25), '<', size=30, outline_width=2)

}

sliders = {
    'slider_number': Slider((50, WINDOW_HEIGHT - 225, 300, 75), 'Divisions', tree_parameters['number']),
    'slider_division_ratio': Slider((50, WINDOW_HEIGHT - 350, 300, 75), 'Division Ratio', tree_parameters['division_ratio']),
    'slider_division_angle': Slider((50, WINDOW_HEIGHT - 475, 300, 75), 'Division Angle', tree_parameters['division_angle'])
}

checkboxes = {
    'checkbox_divide_angles': CheckBox((50, 200), 'Divide Angles'),
    'checkbox_divide_distance': CheckBox((50, 125), 'Divide Distance'),
    'checkbox_fruits': CheckBox((50, 50), "Spawn 'Fruits'")
}
示例#16
0
    def __init__(self, director, state):

        self.director = director
        self.state = state

        self.dna = GameBackground('../res/main_game_backgrounds/main.png')
        # self.bg = GameBackground('../res/main_game_backgrounds/background.png')

        super().__init__()

        self.save_dir = 'profiles/save.json'
        if self.state == 'newgame':
            self.profile = Profile()
        else:
            self.profile = Profile() if not os.path.exists(
                self.save_dir) else Profile.read_save(self.save_dir)

        self.popups = {}
        self.shown_popup = None
        # for name in os.
        self.popups['finish_helicase'] = cocos.sprite.Sprite(
            pyglet.image.load('../res/popups/finish_helicase.png'),
            position=(640, 360))
        self.popups['fail_helicase'] = cocos.sprite.Sprite(
            pyglet.image.load('../res/popups/fail_helicase.png'),
            position=(640, 360))
        self.popups['finish_pp'] = cocos.sprite.Sprite(
            pyglet.image.load('../res/popups/finish_pp.png'),
            position=(640, 360))
        self.popups['fail_pp'] = cocos.sprite.Sprite(
            pyglet.image.load('../res/popups/fail_pp.png'),
            position=(640, 360))
        self.popups['finish_ligase'] = cocos.sprite.Sprite(
            pyglet.image.load('../res/popups/finish_ligase.png'),
            position=(640, 360))
        self.popups['fail_ligase'] = cocos.sprite.Sprite(
            pyglet.image.load('../res/popups/fail_ligase.png'),
            position=(640, 360))

        for pop in self.popups.values():
            self.add(pop, 4)
            pop.do(Hide())

        self.case = self.profile.information['case']

        self.pos = [600, 0]

        self.life_num = self.profile.get_lives()
        print('new life number', self.life_num)
        self.lives = cocos.sprite.Sprite(
            pyglet.image.load('../res/lives_' + str(self.life_num) + '.png'),
            position=(224, 637))

        self.scroller = cocos.layer.ScrollingManager()
        self.MGLayer = MainGameLayer(self.director, self.scroller, self,
                                     self.case, self.profile, self.dna)

        back_button = Button(1199, 658, '../res/back_button.png', self,
                             self.back)
        back_button.setHasHighlight('../res/back_button_h.png')

        left_button = Button(1050, 90, '../res/BUTTON LEFT.png', self,
                             self.set_pos_left)
        left_button.setHasHighlight('../res/BUTTON LEFT HIGHLIGHTED.png')
        right_button = Button(1190, 90, '../res/BUTTON RIGHT.png', self,
                              self.set_pos_right)
        right_button.setHasHighlight('../res/BUTTON RIGHT HIGHLIGHTED.png')

        self.add(back_button, z=1)
        self.add(left_button, z=1)
        self.add(right_button, z=1)
        self.add(self.lives, z=1)
        self.scroller.add(self.MGLayer, z=0)
        self.add(self.scroller, z=0)

        # initial view position
        self.scroller.set_focus(*self.pos)
    def __init__(self, sonos):
        Scene.__init__(self)
        self.sonos = sonos                  
        self.firstLoad = True

        ########## SETUP UI ##########

        self.background_color = colors.NAVY

        # Select Music
        select_music_image = Image('select_music',filename='select_music.png')
        self.select_music_button = Button(Rect(20,20,30,30),image=select_music_image)
        self.select_music_button.on_tapped.connect(self.select_music_modal)
        self.add_child(self.select_music_button)

        # Current Room   
        self.room_label = Label(Rect(50,24,220,30),self.sonos.current_zone_label,30,colors.WHITE)
        self.add_child(self.room_label)

        # Select Room
        select_room_image = Image('select_room',filename='select_room.png')
        self.select_room_button = Button(Rect(270,20,30,30),image=select_room_image)
        self.select_room_button.on_tapped.connect(self.select_room_modal)
        self.add_child(self.select_room_button)

        # Album Art
        self.empty_album_image = Image('empty_album',filename='empty_album_art.png')
        self.tv_album_image = Image('tv_album_art',filename='tv_album_art.png')
        self.album_art_view = ImageView(Rect(80,72,160,160),self.empty_album_image)
        self.add_child(self.album_art_view)

        # Track Title   
        self.track_label = Label(Rect(20,256,280,30),"",36, colors.WHITE)             
        self.add_child(self.track_label)
        # Artist
        self.artist_label = Label(Rect(20,296,280,20),"",24, colors.GRAY)
        self.add_child(self.artist_label)
        # Album
        self.album_label = Label(Rect(20,321,280,20),"",24, colors.GRAY)
        self.add_child(self.album_label)

        ##### Play Button #####
        play_track_img = Image('play_track',filename='play_track.png')
        play_track_disabled_img = Image('play_track_disabled',filename='play_track_disabled.png')
        self.play_button = Button(Rect(130,360,60,60),image=play_track_img, disabled_image=play_track_disabled_img)
        #Touch Handler
        self.play_button.on_tapped.connect(self.play)
        self.add_child(self.play_button)

        ##### Pause Button #####
        pause_track_img = Image('pause_track',filename='pause_track.png')
        self.pause_button = Button(Rect(130,360,60,60),image=pause_track_img)
        self.pause_button.hidden = True
        #Touch Handler
        self.pause_button.on_tapped.connect(self.pause)
        self.add_child(self.pause_button)

        ##### Previous Track #####
        previous_track_img = Image('previous_track',filename='previous_track.png')
        previous_track_disabled_img = Image('previous_track_disabled',filename='previous_track_disabled.png')        
        self.previous_button = Button(Rect(65,370,40,40),image=previous_track_img, disabled_image=previous_track_disabled_img)
        #Touch Handler
        self.previous_button.on_tapped.connect(self.previous)
        self.add_child(self.previous_button)

        ##### Next Track #####
        next_track_img = Image('next_track',filename='next_track.png')
        next_track_disabled_img = Image('next_track_disabled',filename='next_track_disabled.png')
        self.next_button = Button(Rect(215,370,40,40),image=next_track_img,disabled_image=next_track_disabled_img)
        #Touch Handler
        self.next_button.on_tapped.connect(self.next)
        self.add_child(self.next_button)

        ##### Volume Down Button #####
        volume_down_img = Image('volume_down',filename='volume_down.png')
        self.volume_down_button = Button(Rect(92,438,30,30),image=volume_down_img)
        #Touch Handler
        self.volume_down_button.on_tapped.connect(self.volume_down)
        self.add_child(self.volume_down_button)

        ##### Volume On Button #####
        volume_on_img = Image('volume_on',filename='volume_on.png')
        self.volume_on_button = Button(Rect(147,440,26,26),image=volume_on_img)
        #Touch Handler
        self.volume_on_button.on_tapped.connect(self.mute)
        self.add_child(self.volume_on_button)

        ##### Volume Mute Button #####
        volume_mute_img = Image('volume_mute',filename='volume_mute.png')
        self.volume_mute_button = Button(Rect(147,440,26,26),image=volume_mute_img)
        self.volume_mute_button.hidden = True
        #Touch Handler
        self.volume_mute_button.on_tapped.connect(self.unmute)
        self.add_child(self.volume_mute_button)

        # Volume Level Label
        self.volume_label = Label(Rect(30,447,40,30),"",20, colors.GRAY)
        self.add_child(self.volume_label)

        ##### Volume Up Button #####
        volume_up_img = Image('volume_up',filename='volume_up.png')    
        self.volume_up_button = Button(Rect(197,438,30,30),image=volume_up_img)
        #Touch Handler
        self.volume_up_button.on_tapped.connect(self.volume_up)
        self.add_child(self.volume_up_button)

        ##### Group Rooms Button #####
        group_rooms_img = Image('group_rooms',filename='group_rooms.png')
        self.group_rooms_button = Button(Rect(270,440,26,26),image=group_rooms_img)
        #Touch Handler
        self.group_rooms_button.on_tapped.connect(self.group_rooms_modal)
        self.add_child(self.group_rooms_button)        

        # Layout the scene
        self.layout()

        # Keep hidden until everything has loaded
        self.hidden = True

        ########## END SETUP UI ##########

        # Listen for all changes to the current zone   
        self.sonos.listen_for_zone_changes(self.zone_state_changed)
示例#18
0
class MiniGame2(cocos.scene.Scene):

# init
    def __init__(self, director, victory_action, fail_action):
        
        self.director = director
        # self.mainGameLayer = mainGameLayer
        self.victory_action = victory_action
        self.fail_action = fail_action

        super().__init__()

        bg = GameBackground('../res/minigame2/minigame2_background.png')        
        self.pos = [1280, 720]

        self.youre_next = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/popup.png'), position=(255,330))
        self.youre_next.do(Hide())
        self.click_anywhere = Button(640,360,'../res/minigame1/finish_level_button.png', self, self.assign_next)
        self.click_anywhere.disable()

        self.arrow_down = Button(550,560,'../res/minigame2/arrow_sprite_sheet.png', self, self.victory_action, isSpriteSheet=True, speed=0.125)
        self.add(self.arrow_down, 4)

        self.dp1 = cocos.sprite.Sprite(pyglet.image.load('../res/Profile_picture/Polymerase_Active_Agent.png'), position=(811,665))
        # self.dp1 = Button(850,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.back, toAdjust=True)
        self.dp2 = cocos.sprite.Sprite(pyglet.image.load('../res/Profile_picture/Primase_Active_Agent.png'), position=(350,665))
        # self.dp = Button(350,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.back, toAdjust=True)
        self.add(self.dp2, 11)
        self.add(self.dp1, 11)

        self.platform = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/buttons/platform.png'), position=(620,94))
        # self.platform = Button(640,360,'../res/minigame2/buttons/platform.png', self, self.back, toAdjust=True)
        self.add(self.platform, 1)

        self.buttons = {}

        self.next_turn = False

        self.bases = [  'a' if x == 0 else 
                        't' if x == 1 else
                        'c' if x == 2 else
                        'g' if x == 3 else
                        'b' for x in [random.randrange(0,4) for i in range(0,20)]]

        # self.is_num = len(self.bases)-1
            # if index in range(0,5): 
            #     sug.do(Hide())

        # self.sugar = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/sugar.png'), position=(2000,2000))

        self.do_list = [(34, 348),
                        (106, 307),
                        (224, 295),
                        (303, 364),
                        (417, 414),
                        (536, 459),
                        (654, 388),
                        (751, 279),
                        (871, 320),
                        (956, 392),
                        (1076, 444),
                        (1200, 384)
                    ]

        # self.position_sugar(self.sugar, self.do_list[3], self.do_list[4])
        # self.add(self.sugar, z=11)

        # self.do_list.reverse()
        self.game_counter = 0
        self.alive_nucleotides = 5
        self.buffer = 0

        self.buttons['back'] = Button(78,666, '../res/main_left.png', self, self.back)
        self.buttons['back'].setHasHighlight('../res/main_left_h.png')

        self.characters = {}
        self.characters['primase'] = Button(64,75, '../res/minigame2/primase_smol.png', self, self.back)
        self.characters['polymerase'] = Button(190,75, '../res/minigame2/polymerase_smol.png', self, self.back)

        self.popup_anchor = (640,360)
        self.buttons['A'] = Button(476,90,'../res/minigame2/buttons/a.png', self, self.put_a)
        self.buttons['A'].setHasClicked('../res/minigame2/buttons/a_p.png')
        self.buttons['T'] = Button(576,90,'../res/minigame2/buttons/t.png', self, self.put_t)
        self.buttons['T'].setHasClicked('../res/minigame2/buttons/t_p.png')
        self.buttons['C'] = Button(676,90,'../res/minigame2/buttons/c.png', self, self.put_c)
        self.buttons['C'].setHasClicked('../res/minigame2/buttons/c_p.png')
        self.buttons['G'] = Button(776,90,'../res/minigame2/buttons/g.png', self, self.put_g)
        self.buttons['G'].setHasClicked('../res/minigame2/buttons/g_p.png')
        self.buttons['P'] = Button(630,90,'../res/minigame2/buttons/p.png', self, self.put_p)
        self.buttons['P'].setHasClicked('../res/minigame2/buttons/p_p.png')

        self.dna = []

        for num, base in enumerate(self.bases):

            temp = Button(2000,2000, '../res/minigame2/nucleotide_'+base+'.png', self, self.back)
            temp.identity = base
            temp.setHasInactive('../res/minigame2/nucleotide_hide.png')
            self.dna.append(temp)

        self.interval_sugars = [cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/upper_sugar.png'), position=(2000,2000)) for i in range(0,19)]
        for index, sug in enumerate(self.interval_sugars):
            self.add(sug, 1)
            sug.do(Hide())


        self.reconfigure_dna(init=True)
        
        # for index, nucleotide in enumerate(self.dna):
        #     print('dddd')
        #     if not index == 19:
        #         self.position_sugar(self.interval_sugars[index], self.dna[index].spr.position, nucleotide.spr.position)

        for key, button in self.buttons.items():
            self.add(button, 2)
            if not key in ['P','back']:
                button.do(Hide())
                button.disable()

        for character in self.characters.values():
            self.add(character, 3)

        for nucleotide in self.dna:
            self.add(nucleotide, 2)

        self.add(bg, 0)
        self.add(self.youre_next, 4)
        self.add(self.click_anywhere, 4)

# methods
    def back(self):
        self.director.pop()
        print("select stage back")

    def activate_nucleobuttons(self):
        for key, button in self.buttons.items():
            if key in ['A','T','C','G']:
                button.opacity = 0
                button.enable()
                button.do(Show()+FadeIn(0.125))
            elif key in ['P']:
                button.do(FadeOut(0.125)+Hide())
                button.disable()



    def position_sugar(self, sugar, block_coord, block2_coord,show=False, up=True):
        # angle_of_rotate = -math.degrees(math.atan2((block2_coord[1]-block_coord[1]),(block2_coord[0]-block_coord[0])))
        sugar.do(MoveTo(((block_coord[0]+block2_coord[0])/2, (block_coord[1]+block2_coord[1])/2), 0.5))
        sugar.do(RotateTo(-math.degrees(math.atan2((block2_coord[1]-block_coord[1]),(block2_coord[0]-block_coord[0]))), 0.5)+Show())

    def immediate_position_sugar(self, sugar, block_coord, block2_coord,show=False, up=True):
        # angle_of_rotate = -math.degrees(math.atan2((block2_coord[1]-block_coord[1]),(block2_coord[0]-block_coord[0])))
        sugar.do(MoveTo(((block_coord[0]+block2_coord[0])/2, (block_coord[1]+block2_coord[1])/2), 0)+Show())
        sugar.do(RotateTo(-math.degrees(math.atan2((block2_coord[1]-block_coord[1]),(block2_coord[0]-block_coord[0]))), 0))

    def put_a(self):
        print('a')
        self.put_block('a')

    def put_t(self):
        print('T')
        self.put_block('t')

    def put_c(self):
        print('C')
        self.put_block('c')

    def put_g(self):
        print('G')
        self.put_block('g')

    def put_p(self):
        print('p')
        self.put_block('p')

    def assign_next(self):
        print('assign next')
        self.next_turn = False
        self.youre_next.do(FadeOut(0.125)+Hide())
        self.activate_nucleobuttons()
        self.click_anywhere.disable()

    def put_block(self, letter):

        if self.game_counter < len(self.bases): 
            imgDir = ''
            
            self.button_to_assign = self.dna[self.game_counter]

            if self.next_turn:
                self.youre_next.opacity = 0
                self.youre_next.do(Show()+FadeIn(0.125))
                self.click_anywhere.enable()
                return
            elif self.game_counter > 9:
                self.img_to_assign='../res/minigame2/nucleotide_'+self.dna[self.game_counter].identity+letter+'.png'
                self.characters['polymerase'].work((536, 459), self.change_button_sprite, self.check_victory)
            else:
                self.img_to_assign='../res/minigame2/nucleotide_primer_'+self.dna[self.game_counter].identity+'.png'
                self.throw_ball(self.characters['primase'].spr.get_rect().center, (536, 459), self.change_button_sprite)

            if self.alive_nucleotides < 11:
                self.alive_nucleotides += 1
            else:
                self.buffer += 1

            self.game_counter += 1
            if self.game_counter == 10:
                self.next_turn = True
            self.reconfigure_dna()

        else:
            self.back()
        # print(self.game_counter)

    def check_victory(self):
        if self.game_counter >= len(self.bases):
            self.victory_action()

    def change_button_sprite(self):
        try:
            self.button_to_assign.spr.image = pyglet.image.load(self.img_to_assign)
        except Exception as e:
            self.fail_action()

    def reconfigure_dna(self, init=False):


        if init:

            tempindex = self.alive_nucleotides
            for index, nucleotide in enumerate(self.dna):
                if index > self.alive_nucleotides:
                    return
                else: 
                    nucleotide.set_position(*self.do_list[tempindex])
                    nucleotide.enable()
                    if not tempindex == 0:
                        self.immediate_position_sugar(self.interval_sugars[index],self.do_list[tempindex],self.do_list[tempindex-1])
                        
                    tempindex -= 1


        else:

            th.start_new_thread(self.wait_thread_reconfigure, ())

    def throw_ball(self, throw_position, target_position, effect):
        ball = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/ball.png'), position=throw_position)
        self.add(ball)
        act = MoveTo(target_position, 0.5)+CallFunc(effect)+Hide()
        ball.do(act)

    def wait_thread_reconfigure(self):

        time.sleep(0.5)

        tempindex = self.alive_nucleotides # is the index of the position of the sprites
        # self.buffer
        maxx = self.alive_nucleotides+self.buffer
        minn = self.buffer

        for index, nucleotide in enumerate(self.dna):

            if not index in range(minn, maxx+1):
                    nucleotide.disable()
                    nucleotide.shift(2000,2000)
                    try:
                        # pass
                        self.position_sugar(self.interval_sugars[index],[2000,2000],[2000,2000])    
                    except Exception as e:
                        # raise e
                        print('lmao')
                    # print('disabled')                                          
            else:
                if not nucleotide.enabled:
                    nucleotide.enable()
                    # print('enabled')
                
                if nucleotide.spr.position == (2000,2000):
                    nucleotide.shift_then_show(*self.do_list[tempindex])                    
                else:
                    nucleotide.shift(*self.do_list[tempindex])
                

                # print(index)
                # print(nucleotide.spr.position)
                # print(self.dna[index+1].spr.position)
                if not tempindex == 0:
                    if self.do_list[tempindex][0] > 654:
                        # print('lampas naaa')
                        temp_coord = [self.do_list[tempindex][0],self.do_list[tempindex][1]]
                        temp_coord[1] = temp_coord[1]+60

                        temp_coord2 = [nucleotide.spr.position[0], nucleotide.spr.position[1]]
                        temp_coord2[1] = temp_coord2[1]+60

                        self.position_sugar(self.interval_sugars[index],temp_coord,temp_coord2)

                    elif self.do_list[tempindex][0] > 536:
                        
                        temp_coord = [self.do_list[tempindex][0],self.do_list[tempindex][1]]
                        temp_coord[1] = temp_coord[1]+60

                        self.position_sugar(self.interval_sugars[index],temp_coord,nucleotide.spr.position)

                    else:
                        # try:
                        self.position_sugar(self.interval_sugars[index],self.do_list[tempindex],nucleotide.spr.position)

                tempindex -= 1
示例#19
0
    def __init__(self, director, victory_action, fail_action):
        
        self.director = director
        # self.mainGameLayer = mainGameLayer
        self.victory_action = victory_action
        self.fail_action = fail_action

        super().__init__()

        bg = GameBackground('../res/minigame2/minigame2_background.png')        
        self.pos = [1280, 720]

        self.youre_next = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/popup.png'), position=(255,330))
        self.youre_next.do(Hide())
        self.click_anywhere = Button(640,360,'../res/minigame1/finish_level_button.png', self, self.assign_next)
        self.click_anywhere.disable()

        self.arrow_down = Button(550,560,'../res/minigame2/arrow_sprite_sheet.png', self, self.victory_action, isSpriteSheet=True, speed=0.125)
        self.add(self.arrow_down, 4)

        self.dp1 = cocos.sprite.Sprite(pyglet.image.load('../res/Profile_picture/Polymerase_Active_Agent.png'), position=(811,665))
        # self.dp1 = Button(850,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.back, toAdjust=True)
        self.dp2 = cocos.sprite.Sprite(pyglet.image.load('../res/Profile_picture/Primase_Active_Agent.png'), position=(350,665))
        # self.dp = Button(350,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.back, toAdjust=True)
        self.add(self.dp2, 11)
        self.add(self.dp1, 11)

        self.platform = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/buttons/platform.png'), position=(620,94))
        # self.platform = Button(640,360,'../res/minigame2/buttons/platform.png', self, self.back, toAdjust=True)
        self.add(self.platform, 1)

        self.buttons = {}

        self.next_turn = False

        self.bases = [  'a' if x == 0 else 
                        't' if x == 1 else
                        'c' if x == 2 else
                        'g' if x == 3 else
                        'b' for x in [random.randrange(0,4) for i in range(0,20)]]

        # self.is_num = len(self.bases)-1
            # if index in range(0,5): 
            #     sug.do(Hide())

        # self.sugar = cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/sugar.png'), position=(2000,2000))

        self.do_list = [(34, 348),
                        (106, 307),
                        (224, 295),
                        (303, 364),
                        (417, 414),
                        (536, 459),
                        (654, 388),
                        (751, 279),
                        (871, 320),
                        (956, 392),
                        (1076, 444),
                        (1200, 384)
                    ]

        # self.position_sugar(self.sugar, self.do_list[3], self.do_list[4])
        # self.add(self.sugar, z=11)

        # self.do_list.reverse()
        self.game_counter = 0
        self.alive_nucleotides = 5
        self.buffer = 0

        self.buttons['back'] = Button(78,666, '../res/main_left.png', self, self.back)
        self.buttons['back'].setHasHighlight('../res/main_left_h.png')

        self.characters = {}
        self.characters['primase'] = Button(64,75, '../res/minigame2/primase_smol.png', self, self.back)
        self.characters['polymerase'] = Button(190,75, '../res/minigame2/polymerase_smol.png', self, self.back)

        self.popup_anchor = (640,360)
        self.buttons['A'] = Button(476,90,'../res/minigame2/buttons/a.png', self, self.put_a)
        self.buttons['A'].setHasClicked('../res/minigame2/buttons/a_p.png')
        self.buttons['T'] = Button(576,90,'../res/minigame2/buttons/t.png', self, self.put_t)
        self.buttons['T'].setHasClicked('../res/minigame2/buttons/t_p.png')
        self.buttons['C'] = Button(676,90,'../res/minigame2/buttons/c.png', self, self.put_c)
        self.buttons['C'].setHasClicked('../res/minigame2/buttons/c_p.png')
        self.buttons['G'] = Button(776,90,'../res/minigame2/buttons/g.png', self, self.put_g)
        self.buttons['G'].setHasClicked('../res/minigame2/buttons/g_p.png')
        self.buttons['P'] = Button(630,90,'../res/minigame2/buttons/p.png', self, self.put_p)
        self.buttons['P'].setHasClicked('../res/minigame2/buttons/p_p.png')

        self.dna = []

        for num, base in enumerate(self.bases):

            temp = Button(2000,2000, '../res/minigame2/nucleotide_'+base+'.png', self, self.back)
            temp.identity = base
            temp.setHasInactive('../res/minigame2/nucleotide_hide.png')
            self.dna.append(temp)

        self.interval_sugars = [cocos.sprite.Sprite(pyglet.image.load('../res/minigame2/upper_sugar.png'), position=(2000,2000)) for i in range(0,19)]
        for index, sug in enumerate(self.interval_sugars):
            self.add(sug, 1)
            sug.do(Hide())


        self.reconfigure_dna(init=True)
        
        # for index, nucleotide in enumerate(self.dna):
        #     print('dddd')
        #     if not index == 19:
        #         self.position_sugar(self.interval_sugars[index], self.dna[index].spr.position, nucleotide.spr.position)

        for key, button in self.buttons.items():
            self.add(button, 2)
            if not key in ['P','back']:
                button.do(Hide())
                button.disable()

        for character in self.characters.values():
            self.add(character, 3)

        for nucleotide in self.dna:
            self.add(nucleotide, 2)

        self.add(bg, 0)
        self.add(self.youre_next, 4)
        self.add(self.click_anywhere, 4)
示例#20
0
class StartMenuState:
    def __init__(self):
        self.sm = SpriteManager()
        self.button_new_game = Button(352, 0, 96, 23, sprite=self.sm.sprites['new_game_button'], callback=self.start_new_game)
        self.button_load_game = Button(378, 23, 44, 23, sprite=self.sm.sprites['load_button'], callback=self.load_game)
        self.button_exit = Button(378, 46, 41, 23, sprite=self.sm.sprites['exit_button'], callback=self.exit_game)
        self.version_label = Label(0, 580, "Version 0.1")
        event_manager.event_manager.add_listener(event_manager.MESSAGE_MOUSE_UP, self)

    def process(self):
        video.clean()
        self.button_new_game.draw(video.screen)
        self.button_load_game.draw(video.screen)
        self.button_exit.draw(video.screen)
        self.version_label.draw(video.screen)
        video.flip()

    def process_message(self, pos_x, pos_y, button):
        self.button_new_game.is_pressed(pos_x, pos_y, button)
        self.button_load_game.is_pressed(pos_x, pos_y, button)
        self.button_exit.is_pressed(pos_x, pos_y, button)

    def start_new_game(self):
        event_manager.event_manager.purge()
        state = GlobalMapState()
        state.new_game()
        application.push_state(state)

    def load_game(self):
        event_manager.event_manager.purge()
        state = GlobalMapState()
        state.load_game(from_start_menu=True)
        application.push_state(state)

    def exit_game(self):
        application.running = False
示例#21
0
    def __init__(self, application):
        gtk.ScrolledWindow.__init__(self)

        self.observer = Observer()

        self.objects = dict()

        from canvas import Canvas
        self.canvas = Canvas(application)

        self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)

        properties = gtk.VBox()
        self.add_with_viewport(properties)

        self.group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)

        #---START-------------------------------------------------------
        button = Button(_("General properties"))
        properties.pack_start(button, False, False)

        form = Form("general", self)
        button.add(form)

        form.add_section(_("Units"))

        entry = gtk.combo_box_new_text()
        entry.append_text(CENTIMETERS)
        entry.append_text(MILLIMETERS)
        entry.append_text(DOTS)
        entry.append_text(INCHES)
        entry.set_active(1)

        form.add_entry(_("Preferred linear unit"), entry, "linear-unit")

        entry = gtk.combo_box_new_text()
        entry.append_text(DEGREES)
        entry.append_text(RADIANS)
        entry.set_active(1)

        form.add_entry(_("Preferred angular unit"), entry, "angular-unit")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Document properties"))
        properties.pack_start(button, False, False)

        form = Form("document", self)
        button.add(form)

        form.add_section(_("Size"))

        entry = LinearEntry()
        form.add_entry(_("Width"), entry, "width")

        entry = LinearEntry()
        form.add_entry(_("Height"), entry, "height")

        form.add_section(_("Margins"))

        entry = LinearEntry()
        form.add_entry(_("Top"), entry, "top-margin")

        entry = LinearEntry()
        form.add_entry(_("Bottom"), entry, "bottom-margin")

        entry = LinearEntry()
        form.add_entry(_("Left"), entry, "left-margin")

        entry = LinearEntry()
        form.add_entry(_("Right"), entry, "right-margin")

        form.add_section(_("Config"))

        entry = LinearEntry()
        form.add_entry(_("Grid size"), entry, "grid-size")

        entry = LinearEntry()
        form.add_entry(_("Guides size"), entry, "guides-size")

        entry = gtk.CheckButton(_("Show margins"))
        form.add_entry(None, entry, "margins-active")

        entry = gtk.CheckButton(_("Show guides"))
        form.add_entry(None, entry, "guides-active")

        entry = gtk.CheckButton(_("Show grid"))
        form.add_entry(None, entry, "grid-active")

        entry = gtk.CheckButton(_("Enable snap"))
        form.add_entry(None, entry, "snap")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Line properties"))
        self.objects["Line"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("line", self)
        button.add(form)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Box properties"))
        self.objects["Box"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("box", self)
        button.add(form)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Rounded box properties"))
        self.objects["Rounded"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("rounded", self)
        button.add(form)

        form.add_section(_("Shape"))

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Radius"), entry, "radius")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Text properties"))
        self.objects["Text"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("text", self)
        button.add(form)

        form.add_section(_("Format"))

        entry = gtk.FontButton()
        entry.connect("font-set", self.change_font)
        form.add_entry(_("Font"), entry, "font")

        entry = gtk.CheckButton(_("Preserve aspect"))
        entry.connect("toggled", self.preserve)
        form.add_entry(None, entry, "preserve")

        form.add_section(_("Text"))

        entry = TextPad(application)
        self.disconnect_handler = entry.buffer.connect("changed", self.changed)
        entry.connect("cursor-moved", self.cursor_moved)
        form.add_entry(None, entry, "text")
        #---END---------------------------------------------------------

        #---START--------ARC properties-----------------------------------------------
        button = Button(_("Arc properties"))
        self.objects["Arc"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("arc", self)
        button.add(form)

        form.add_section(_("Angle"))
        self.angle_start = AngularEntry()
        form.add_entry(_("Start Angle"), self.angle_start, "start")
        self.angle_start.spin.connect("value-changed", self.change_angle_start)

        self.angle_stop = AngularEntry()
        form.add_entry(_("Stop Angle"), self.angle_stop, "stop")
        self.angle_stop.spin.connect("value-changed", self.change_angle_stop)

        form.add_section(_("Other"))
        self.closed_btn = gtk.CheckButton()
        form.add_entry(_("Closed Arc"), self.closed_btn, "closed")
        self.closed_btn.connect("toggled", self.close_arc)

        self.closed_at_centre_btn = gtk.CheckButton()
        self.closed_at_centre_btn.set_active(1)
        form.add_entry(_("Closed Arc at Centre"), self.closed_at_centre_btn,
                       "closed-at-centre")
        self.closed_at_centre_btn.connect("toggled", self.close_at_centre_arc)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Table properties"))
        self.objects["Table"] = button
        properties.pack_start(button, False, False)

        form = PositionedObjectForm("table", self)
        button.add(form)

        form.add_section(_("Spacing"))

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Vertical"), entry, "vertical-spacing")

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Horizontal"), entry, "horizontal-spacing")

        form.add_section(_("Size"))

        entry = LinearEntry()
        entry.set_value(1)
        entry.connect("value-changed", self.set_table_columns)
        form.add_entry(_("Columns"), entry, "columns")

        entry = LinearEntry()
        entry.set_value(5)
        entry.connect("value-changed", self.set_table_rows)
        form.add_entry(_("Rows"), entry, "rows")

        form.add_section(_("Color"))

        entry = gtk.ColorButton()
        form.add_entry(_("Stroke"), entry, "stroke")

        entry = gtk.ColorButton()
        form.add_entry(_("Fill"), entry, "fill")

        form.add_section(_("Format"))

        entry = gtk.FontButton()
        entry.connect("font-set", self.set_table_font)
        form.add_entry(_("Font"), entry, "font")

        form.add_section(_("Columns"))

        entry = ColumnsEditor()
        entry.add_column()
        entry.connect("width-edited", self.set_table_column_width)
        entry.connect("title-edited", self.set_table_column_title)
        form.add_entry(None, entry, "columns-editor")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Barcode properties"))
        self.objects["BarCode"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("barcode", self)
        button.add(form)

        form.add_section(_("Barcode"))

        entry = gtk.combo_box_new_text()
        entry.connect("changed", self.changed_barcode_type)
        for type in sorted(barcodes, key=lambda type: barcodes[type]):
            entry.append_text(type)
        form.add_entry(_("Type"), entry, "type")

        entry = gtk.Entry()
        entry.connect("changed", self.changed_barcode_code)
        form.add_entry(_("Code"), entry, "code")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Image properties"))
        self.objects["Image"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("image", self)
        button.add(form)

        form.add_section(_("Image"))

        def update_preview(dialog, preview):
            filename = dialog.get_preview_filename()
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename, 128,
                                                              128)
                preview.set_from_pixbuf(pixbuf)
                have_preview = True
            except:
                have_preview = False
            dialog.set_preview_widget_active(have_preview)

        dialog = gtk.FileChooserDialog(title="Source image file",
                                       #parent = self,
                                       action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                       buttons=(
                                       gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT),
                                       backend=None)

        preview = gtk.Image()

        dialog.set_preview_widget(preview)
        dialog.connect("update-preview", update_preview, preview)

        #dialog.set_transient_for(self)
        dialog.set_default_response(gtk.RESPONSE_OK)

        def add_filter(dialog, name, pattern, type=None):
            filter = gtk.FileFilter()
            filter.set_name(name)
            if type:
                filter.add_mime_type(type)
            filter.add_pattern(pattern)
            dialog.add_filter(filter)

        add_filter(dialog, "PNG files", "*.png", "image/png")
        add_filter(dialog, "JPG files", "*.jpg", "image/jpg")
        add_filter(dialog, "All files", "*")

        dialog.connect("file-activated", self.changed_image_file)

        entry = gtk.FileChooserButton(dialog)
        form.add_entry(_("Image file"), entry, "file", True)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Chart properties"))
        self.objects["Chart"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("chart", self)
        button.add(form)

        form.add_section(_("Chart"))

        entry = gtk.combo_box_new_text()
        entry.connect("changed", self.changed_chart_type)
        for type in sorted(chart_types, key=lambda type: chart_types[type]):
            entry.append_text(type)
        form.add_entry(_("Type"), entry, "type")
        #---END---------------------------------------------------------

        fill = gtk.Label("\n")
        properties.add(fill)
示例#22
0
class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""

        pygame.init()

        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # Full screen
        # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Alien Invasion")

        # Create an instance to store game statistics, and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self._start_event_handler()

        # MAke the play button
        self.play_button = Button(self, "Play")

    def _start_event_handler(self):
        """Start event handler"""
        self.event_handler = EventHandler()
        self._add_accepted_event_types()
        self._add_accepted_key_down_type()
        self._add_accepted_key_up_type()

    def _add_accepted_event_types(self):
        """Add available event types"""
        self.event_handler.register_types({
            pygame.QUIT:
            EventType(sys.exit, False),
            pygame.KEYDOWN:
            EventType(self._check_keydown_events, True),
            pygame.KEYUP:
            EventType(self._check_keyup_events, True),
            pygame.MOUSEBUTTONDOWN:
            EventType(self._check_play_button, False),
        })

    def _add_accepted_key_down_type(self):
        self.event_handler.register_key_down_actions({
            pygame.K_RIGHT:
            self.ship.move_right,
            pygame.K_LEFT:
            self.ship.move_left,
            pygame.K_UP:
            self.ship.move_up,
            pygame.K_DOWN:
            self.ship.move_down,
            pygame.K_SPACE:
            self._fire_bullet,
            pygame.K_q:
            sys.exit,
        })

    def _add_accepted_key_up_type(self):
        self.event_handler.register_key_up_actions({
            pygame.K_RIGHT:
            self.ship.stop_move_right,
            pygame.K_LEFT:
            self.ship.stop_move_left,
            pygame.K_UP:
            self.ship.stop_move_up,
            pygame.K_DOWN:
            self.ship.stop_move_down,
        })

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets"""
        # Update bullets position
        self.bullets.update()

        self._clear_bullets()

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet-alien collisions."""
        # Remove any bullets and aliens that have collided.
        collisions = pygame.sprite.groupcollide(self.bullets,
                                                self.aliens,
                                                dokilla=True,
                                                dokillb=True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

        if not self.aliens:
            # Destroy existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level.
            self.stats.level += 1
            self.sb.prep_level()

    def _clear_bullets(self):
        """Get rid of bullets that have disappeared."""
        for b in self.bullets.copy():
            if b.rect.bottom <= 0:
                self.bullets.remove(b)

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        # Redraw the screen during each pass though the loop
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for b in self.bullets.sprites():
            b.draw_bullet()
        self.aliens.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

    def _check_events(self):
        """Respond to key presses and mouse events"""
        for event in pygame.event.get():
            self.event_handler.execute_event(event)

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        self.event_handler.execute_key_up(event.key)

    def _check_keydown_events(self, event):
        """Respond to key presses."""
        self.event_handler.execute_key_down(event.key)

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _create_fleet(self):
        """Create the fleet of aliens"""
        alien_height, number_aliens_x = self._get_alien_height_and_number_of_aliens_per_line(
        )

        number_rows = self._get_number_of_rows_of_aliens_based_on_alien_height(
            alien_height)

        # Create the full fleet of aliens
        for row in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._creat_alien(alien_number, row)

    def _get_number_of_rows_of_aliens_based_on_alien_height(
            self, alien_height):
        """Base on screen height and alien height, calculate how many line of aliens we can have."""
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)
        return number_rows

    def _get_alien_height_and_number_of_aliens_per_line(self):
        """
        Get alien size, calculate the number of aliens that fit in one row
        and return the height of alien and the number.
        """
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)
        return alien_height, number_aliens_x

    def _creat_alien(self, alien_number, row_number):
        """Create an alien and place it in the row."""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien_height + 2 * alien_height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        """
        Check if the fleet is at an edge, then update the positions of all aliens in the fleet
        """
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Look for aliens hitting the bottom of the screen
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reached and edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""

        if self.stats.ships_left > 0:

            # Decrement ships_left.
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break

    def _check_play_button(self):
        """Start a new game when the player clicks Play."""
        mouse_pos = pygame.mouse.get_pos()
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game settings
            self.settings.initialize_dynamic_settings()

            # Reset the game statistics
            self.stats.reset_stats()

            self.stats.game_active = True

            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)
示例#23
0
    def __init__(self, application):
        gtk.ScrolledWindow.__init__(self)

        self.observer = Observer()

        self.objects = dict()

        from canvas import Canvas
        self.canvas = Canvas(application)

        self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)

        properties = gtk.VBox()
        self.add_with_viewport(properties)

        self.group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)

        #---START-------------------------------------------------------
        button = Button(_("General properties"))
        properties.pack_start(button, False, False)

        form = Form("general", self)
        button.add(form)

        form.add_section(_("Units"))

        entry = gtk.combo_box_new_text()
        entry.append_text(CENTIMETERS)
        entry.append_text(MILLIMETERS)
        entry.append_text(DOTS)
        entry.append_text(INCHES)
        entry.set_active(1)

        form.add_entry(_("Preferred linear unit"), entry, "linear-unit")

        entry = gtk.combo_box_new_text()
        entry.append_text(DEGREES)
        entry.append_text(RADIANS)
        entry.set_active(1)

        form.add_entry(_("Preferred angular unit"), entry, "angular-unit")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Document properties"))
        properties.pack_start(button, False, False)

        form = Form("document", self)
        button.add(form)

        form.add_section(_("Size"))

        entry = LinearEntry()
        form.add_entry(_("Width"), entry, "width")

        entry = LinearEntry()
        form.add_entry(_("Height"), entry, "height")

        form.add_section(_("Margins"))

        entry = LinearEntry()
        form.add_entry(_("Top"), entry, "top-margin")

        entry = LinearEntry()
        form.add_entry(_("Bottom"), entry, "bottom-margin")

        entry = LinearEntry()
        form.add_entry(_("Left"), entry, "left-margin")

        entry = LinearEntry()
        form.add_entry(_("Right"), entry, "right-margin")

        form.add_section(_("Config"))

        entry = LinearEntry()
        form.add_entry(_("Grid size"), entry, "grid-size")

        entry = LinearEntry()
        form.add_entry(_("Guides size"), entry, "guides-size")

        entry = gtk.CheckButton(_("Show margins"))
        form.add_entry(None, entry, "margins-active")

        entry = gtk.CheckButton(_("Show guides"))
        form.add_entry(None, entry, "guides-active")

        entry = gtk.CheckButton(_("Show grid"))
        form.add_entry(None, entry, "grid-active")

        entry = gtk.CheckButton(_("Enable snap"))
        form.add_entry(None, entry, "snap")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Line properties"))
        self.objects["Line"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("line", self)
        button.add(form)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Box properties"))
        self.objects["Box"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("box", self)
        button.add(form)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Rounded box properties"))
        self.objects["Rounded"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("rounded", self)
        button.add(form)

        form.add_section(_("Shape"))

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Radius"), entry, "radius")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Text properties"))
        self.objects["Text"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("text", self)
        button.add(form)

        form.add_section(_("Format"))

        entry = gtk.FontButton()
        entry.connect("font-set", self.change_font)
        form.add_entry(_("Font"), entry, "font")

        entry = gtk.CheckButton(_("Preserve aspect"))
        entry.connect("toggled", self.preserve)
        form.add_entry(None, entry, "preserve")

        form.add_section(_("Text"))

        entry = TextPad(application)
        self.disconnect_handler = entry.buffer.connect("changed", self.changed)
        entry.connect("cursor-moved", self.cursor_moved)
        form.add_entry(None, entry, "text")
        #---END---------------------------------------------------------

        #---START--------ARC properties-----------------------------------------------
        button = Button(_("Arc properties"))
        self.objects["Arc"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("arc", self)
        button.add(form)

        form.add_section(_("Angle"))
        self.angle_start = AngularEntry()
        form.add_entry(_("Start Angle"), self.angle_start, "start")
        self.angle_start.spin.connect("value-changed", self.change_angle_start)

        self.angle_stop = AngularEntry()
        form.add_entry(_("Stop Angle"), self.angle_stop, "stop")
        self.angle_stop.spin.connect("value-changed", self.change_angle_stop)

        form.add_section(_("Other"))
        self.closed_btn = gtk.CheckButton()
        form.add_entry(_("Closed Arc"), self.closed_btn, "closed")
        self.closed_btn.connect("toggled", self.close_arc)

        self.closed_at_centre_btn = gtk.CheckButton()
        self.closed_at_centre_btn.set_active(1)
        form.add_entry(_("Closed Arc at Centre"), self.closed_at_centre_btn,
                       "closed-at-centre")
        self.closed_at_centre_btn.connect("toggled", self.close_at_centre_arc)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Table properties"))
        self.objects["Table"] = button
        properties.pack_start(button, False, False)

        form = PositionedObjectForm("table", self)
        button.add(form)

        form.add_section(_("Spacing"))

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Vertical"), entry, "vertical-spacing")

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Horizontal"), entry, "horizontal-spacing")

        form.add_section(_("Size"))

        entry = LinearEntry()
        entry.set_value(1)
        entry.connect("value-changed", self.set_table_columns)
        form.add_entry(_("Columns"), entry, "columns")

        entry = LinearEntry()
        entry.set_value(5)
        entry.connect("value-changed", self.set_table_rows)
        form.add_entry(_("Rows"), entry, "rows")

        form.add_section(_("Color"))

        entry = gtk.ColorButton()
        form.add_entry(_("Stroke"), entry, "stroke")

        entry = gtk.ColorButton()
        form.add_entry(_("Fill"), entry, "fill")

        form.add_section(_("Format"))

        entry = gtk.FontButton()
        entry.connect("font-set", self.set_table_font)
        form.add_entry(_("Font"), entry, "font")

        form.add_section(_("Columns"))

        entry = ColumnsEditor()
        entry.add_column()
        entry.connect("width-edited", self.set_table_column_width)
        entry.connect("title-edited", self.set_table_column_title)
        form.add_entry(None, entry, "columns-editor")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Barcode properties"))
        self.objects["BarCode"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("barcode", self)
        button.add(form)

        form.add_section(_("Barcode"))

        entry = gtk.combo_box_new_text()
        entry.connect("changed", self.changed_barcode_type)
        for type in sorted(barcodes, key=lambda type: barcodes[type]):
            entry.append_text(type)
        form.add_entry(_("Type"), entry, "type")

        entry = gtk.Entry()
        entry.connect("changed", self.changed_barcode_code)
        form.add_entry(_("Code"), entry, "code")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Image properties"))
        self.objects["Image"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("image", self)
        button.add(form)

        form.add_section(_("Image"))

        def update_preview(dialog, preview):
            filename = dialog.get_preview_filename()
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                    filename, 128, 128)
                preview.set_from_pixbuf(pixbuf)
                have_preview = True
            except:
                have_preview = False
            dialog.set_preview_widget_active(have_preview)

        dialog = gtk.FileChooserDialog(
            title="Source image file",
            #parent = self,
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OPEN,
                     gtk.RESPONSE_ACCEPT),
            backend=None)

        preview = gtk.Image()

        dialog.set_preview_widget(preview)
        dialog.connect("update-preview", update_preview, preview)

        #dialog.set_transient_for(self)
        dialog.set_default_response(gtk.RESPONSE_OK)

        def add_filter(dialog, name, pattern, type=None):
            filter = gtk.FileFilter()
            filter.set_name(name)
            if type:
                filter.add_mime_type(type)
            filter.add_pattern(pattern)
            dialog.add_filter(filter)

        add_filter(dialog, "PNG files", "*.png", "image/png")
        add_filter(dialog, "JPG files", "*.jpg", "image/jpg")
        add_filter(dialog, "All files", "*")

        dialog.connect("file-activated", self.changed_image_file)

        entry = gtk.FileChooserButton(dialog)
        form.add_entry(_("Image file"), entry, "file", True)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Chart properties"))
        self.objects["Chart"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("chart", self)
        button.add(form)

        form.add_section(_("Chart"))

        entry = gtk.combo_box_new_text()
        entry.connect("changed", self.changed_chart_type)
        for type in sorted(chart_types, key=lambda type: chart_types[type]):
            entry.append_text(type)
        form.add_entry(_("Type"), entry, "type")
        #---END---------------------------------------------------------

        fill = gtk.Label("\n")
        properties.add(fill)
示例#24
0
    def __init__(self, director, victory_action, fail_action):

        self.director = director
        # self.mainGameLayer = mainGameLayer
        self.victory_action = victory_action
        self.fail_action = fail_action

        super().__init__()

        bg = GameBackground('../res/minigame3/minigame3_background.png')
        bg2 = GameBackground('../res/minigame3/nearplane.png')
        self.bg3 = cocos.sprite.Sprite(
            pyglet.image.load('../res/minigame3/longcloud.png'),
            position=(640, 360))
        self.pos = [1280, 720]

        self.dp = cocos.sprite.Sprite(pyglet.image.load(
            '../res/Profile_picture/Ligase_Active_Agent.png'),
                                      position=(350, 665))
        # self.dp = Button(350,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.back, toAdjust=True)
        self.add(self.dp, 11)

        self.buttons = {}

        # self.buttons['boi'] = Button(640,360, '../res/boi.png', self, self.back, isSpriteSheet=True)

        # self.do_list.reverse()
        self.game_counter = 0
        self.alive_nucleotides = 5
        self.buffer = 0

        self.objects_hit = 0
        self.missed = 0

        self.buttons['back'] = Button(53, 666, '../res/main_left.png', self,
                                      self.back)
        self.buttons['back'].setHasHighlight('../res/main_left_h.png')

        self.strand = [
            'a' if x == 0 else
            't' if x == 1 else 'c' if x == 2 else 'g' if x == 3 else 'b'
            for x in [random.randrange(0, 4) for i in range(0, 60)]
        ]

        # self.land_blocks = {}
        self.dna = []
        anchor = [0, 0]
        for base in self.strand:
            block = Button(1236 + anchor[0], 162 + anchor[1],
                           '../res/minigame3/block_' + base + '.png', self,
                           self.back)
            block.move_right_inf()

            self.dna.append(block)

            anchor = [anchor[0] - 120, anchor[1]]

        # self.counter_strand = 'atcgabctgagcbtagcbtagbctagbctagbctag'
        self.counter_strand = [
            'a' if x == 't' else
            'g' if x == 'c' else 'c' if x == 'g' else 't' if x == 'a' else 'b'
            for x in self.strand
        ]

        # self.num_to_random = [x for x in ]
        self.num_to_random = 20
        # counter = self.num_to_random
        self.rand_list = random.sample(range(7, len(self.strand)),
                                       self.num_to_random)
        self.rand_list.sort()
        # self.rand_list.reverse()

        # self.blank_counter_strand = ['b' if index in self.rand_list else x for index, x in enumerate(self.counter_strand)]

        self.counter_dna = []
        self.ammo = []

        anchor = [0, 0]
        for index, base in enumerate(self.counter_strand):
            # print('yo')
            # if not base == 'b':
            block = Button(1200 + anchor[0], 83 + anchor[1],
                           '../res/minigame3/block_' + base + '.png', self,
                           self.back)
            block.move_right_inf()

            self.counter_dna.append(block)

            anchor = [anchor[0] - 120, anchor[1]]

            if index in self.rand_list:

                block.spr.do(Hide())
                print('ammo index', index)

                self.ammo.append(
                    'a' if self.strand[index] == 't' else 'g' if self.
                    strand[index] == 'c' else 'c' if self.strand[index] ==
                    'g' else 't' if self.strand[index] == 'a' else 'b')

        self.dna.reverse()
        # self.counter_dna.reverse()
        # self.ammo.reverse()

        self.deployed_ammo = 0
        self.ammo_blocks = []
        # anchor = [0,0]
        for index, base in enumerate(self.ammo):
            # print('yo')
            # if not base == 'b':
            block = Button(970, 549, '../res/minigame3/block_' + base + '.png',
                           self, self.back)
            block.target_hit_action = self.hit_object
            block.target_miss_action = self.missed_object
            block.spr.do(Hide())
            # block.move_right_inf()

            self.ammo_blocks.append(block)

        # self.ammo_blocks.reverse()

        self.characters = {}
        self.characters['squirrelboi'] = Button(
            970, 549, '../res/minigame3/squirrelboi.png', self, self.back)
        # self.characters['squirrelboi'] = Button(970,549,'../res/minigame3/squirrelboi.png', self, self.back)
        self.characters['squirrelboi'].move_up_and_down()

        for button in self.buttons.values():
            self.add(button, 5)

        for block in self.dna:
            self.add(block, 1)

        self.counter_dna.reverse()
        for block in self.counter_dna:
            self.add(block, 2)
        self.counter_dna.reverse()

        for block in self.ammo_blocks:
            self.add(block, 1)

        for block in self.characters.values():
            self.add(block, 3)

        # for nucleotide in self.dna:
        #     self.add(nucleotide, 2)

        self.add(bg, 0)
        self.add(self.bg3, 1)
        self.add(bg2, 3)
        self.add(Bomb_Deployer(self, self.deployed))

        self.bg3.do(Repeat(MoveBy((10, 0), 1)))
        th.start_new_thread(self.endgame_checker, ())
示例#25
0
    def __init__(self, director, victory_action, fail_action, strand=None):
        
        self.director = director
        self.victory_action = victory_action
        self.fail_action = fail_action

        super().__init__()

        self.finish_level_pictures = {}
        # self.finish_level_pictures['0']=cocos.
        for i in range(0,5):
            self.finish_level_pictures[str(i)] = cocos.sprite.Sprite(pyglet.image.load('../res/minigame1/End/'+str(i)+'.png'), position=(640,360))

        # bg = GameBackground('../res/minigame1/end/click anywhere to continue.png')

        self.dp = Button(350,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.victory_action)
        self.add(self.dp, 11)

        self.accomplished_targets = 0
        self.target_eliminated = False

        self.bg_index = 0

        self.completed = False
        self.victory = False

        self.img_to_assign = pyglet.image.load('../res/minigame1/punch.png')

        self.to_clean = []

        self.buttons = {}

        self.buttons['back'] = Button(53,666, '../res/main_left.png', self, self.back)
        self.buttons['back'].setHasHighlight('../res/main_left_h.png')

        self.finish_button = Button(640, 360, '../res/minigame1/finish_level_button.png', self, self.next_image)
        self.finish_button.disable()


        # if strand == None:
        # self.strand = list('a') # defines the left strand
        # else:
        #     self.strand = strand

        self.strand = [ 'a' if x == 0 else 
                        't' if x == 1 else
                        'c' if x == 2 else
                        'g' if x == 3 else
                        'b' for x in [random.randrange(0,4) for i in range(0,20)]]
        self.strand.reverse()
        self.counter_strand = [ 'a' if x == 't' else 
                                't' if x == 'a' else
                                'c' if x == 'g' else
                                'g' if x == 'c' else
                                'b' for x in self.strand]

        print('strand', self.strand)
        self.game_counter = len(self.strand)-1
        print('counter_strand', self.counter_strand)

        self.backgrounds = []
        for index, base in enumerate(self.strand):
            bg_pair = [cocos.sprite.Sprite(pyglet.image.load('../res/minigame1/left_'+base+'.png'),position=(640,360)),
                                cocos.sprite.Sprite(pyglet.image.load('../res/minigame1/right_'+self.counter_strand[index]+'.png'),position=(640,360))]
            self.backgrounds.append(bg_pair)
            self.add(bg_pair[0], 1)
            self.add(bg_pair[1], 1)

        self.targets = []
        for base in self.strand:
            for i in range(0,3):
                random_coordinate = (random.randint(200, 1080), random.randint(200, 520))
                target = Button(*random_coordinate, '../res/minigame1/TARGET.png', self, self.target_clicked, isSpriteSheet=True)
                target.hide()
                self.targets.append(target)
                self.add(target,3)

        for button in self.buttons.values():
            self.add(button, 2)

        self.ad = Arm_Deployer(self,self.back)

        self.add(self.ad,4)
        # self.add(self.finish_level_pictures[0],0)   
        for i in range(4,-1,-1):
            self.add(self.finish_level_pictures[str(i)],0)

        self.add(self.finish_button,0)

        # th.start_new_thread(self.run_game, ())
        self.generate_target()
示例#26
0
    def update_buttons(self, b_press=set()):

        b_size = (150, 60)

        b_press_up_color = (0, 200, 0)
        b_press_down_color = (0, 100, 0)
        if "b_play" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_play = Button(tag="b_play",
                        text="Play",
                        font=self.files.get_font(40),
                        text_color=(255, 255, 255),
                        img_file_str=self.files.get_button_img_str(),
                        b_color=b_color,
                        position=(self.screen_size[0] // 2 - b_size[0] // 2,
                                  self.screen_size[1] // 2.5),
                        size=b_size,
                        rotate=0)

        b_size = (150, 40)
        b_press_up_color = (0, 200, 0)
        b_press_down_color = (0, 100, 0)
        if "b_scores" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_scores = Button(tag="b_scores",
                          text="Highscores",
                          font=self.files.get_font(30),
                          text_color=(255, 255, 255),
                          img_file_str=self.files.get_button_img_str(),
                          b_color=b_color,
                          position=(self.screen_size[0] // 2 - b_size[0] // 2,
                                    self.screen_size[1] // 1.8),
                          size=b_size,
                          rotate=0)

        b_size = (110, 35)
        b_press_up_color = (150, 0, 0)
        b_press_down_color = (50, 0, 0)
        if "b_quit" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_quit = Button(tag="b_quit",
                        text="Quit",
                        font=self.files.get_font(30),
                        text_color=(255, 255, 255),
                        img_file_str=self.files.get_button_img_str(),
                        b_color=b_color,
                        position=(self.screen_size[0] // 2 - b_size[0] // 2,
                                  self.screen_size[1] // 1.4),
                        size=b_size,
                        rotate=0)

        self.buttons.add(b_play)
        self.buttons.add(b_scores)
        self.buttons.add(b_quit)

        self.all_sprites.add(self.buttons)
示例#27
0
class InventoryLayer(cocos.layer.ColorLayer):

    is_event_handler = False

    # init

    def __init__(self, scroller, target, width=1280, height=720):
        super().__init__(57, 67, 63, 0, width=width, height=height)

        picDir = '../res/inventory.png'

        self.scroller = scroller
        self.opacity = 0
        self.target = target

        self.image = pyglet.image.load(picDir)
        self.spr = cocos.sprite.Sprite(self.image, position=(640, 360))

        self.backButton = Button(1070, 627, '../res/inventory_back.png', self,
                                 self.hide)
        self.backButton.setHasHighlight('../res/inventory_back_h.png')

        self.highlight = False
        self.onHover = False
        self.highlight = True

        self.add(self.backButton, 1)
        self.add(self.spr, 0)

        self.spr.do(Hide())
        self.backButton.spr.do(Hide())
        # self.target.unshow()

    # setters/getters
    def setHasHighlight(self, picDir):
        self.highlight = True

    def setTarget(self, target):
        self.target = target

    # methods
    def on_mouse_motion(self, x, y, dx, dy):

        pass

        # x,y = self.scroller.screen_to_world(x,y)

        # if (not self.onHover) and self.target.contains(x,y):
        #     self.onHover = True
        #     if self.highlight:
        #         self.opacity = 70
        #         # self.spr.do(Show())

        # elif self.onHover and (not self.target.contains(x,y)):
        #     self.onHover = False
        #     if self.highlight:
        #         self.opacity = 0
        # self.spr.do(Hide())

    def on_mouse_press(self, x, y, button, mod):
        # if self.onHover:
        #     self.spr.do(Show())

        pass

    def show(self):
        InventoryLayer.is_event_handler = True
        self.opacity = 70
        self.spr.do(Show())
        self.backButton.spr.do(Show())

    def hide(self):
        InventoryLayer.is_event_handler = False
        self.opacity = 0
        self.spr.do(Hide())
        self.backButton.spr.do(Hide())

    def setSprite(self, img):
        self.spr.image = img
示例#28
0
 def init(self, game):
     btn_inv = Button((globals.VIEW_OFFSET[0], globals.WINDOW_HEIGHT - 100), 'Start')
     btn_inv.on_click = self.start_game
     self.add_entity(btn_inv)
示例#29
0
class MiniGame1(cocos.scene.Scene):

# init
    def __init__(self, director, victory_action, fail_action, strand=None):
        
        self.director = director
        self.victory_action = victory_action
        self.fail_action = fail_action

        super().__init__()

        self.finish_level_pictures = {}
        # self.finish_level_pictures['0']=cocos.
        for i in range(0,5):
            self.finish_level_pictures[str(i)] = cocos.sprite.Sprite(pyglet.image.load('../res/minigame1/End/'+str(i)+'.png'), position=(640,360))

        # bg = GameBackground('../res/minigame1/end/click anywhere to continue.png')

        self.dp = Button(350,665, '../res/Profile_picture/Helicase_Active_Agent.png', self, self.victory_action)
        self.add(self.dp, 11)

        self.accomplished_targets = 0
        self.target_eliminated = False

        self.bg_index = 0

        self.completed = False
        self.victory = False

        self.img_to_assign = pyglet.image.load('../res/minigame1/punch.png')

        self.to_clean = []

        self.buttons = {}

        self.buttons['back'] = Button(53,666, '../res/main_left.png', self, self.back)
        self.buttons['back'].setHasHighlight('../res/main_left_h.png')

        self.finish_button = Button(640, 360, '../res/minigame1/finish_level_button.png', self, self.next_image)
        self.finish_button.disable()


        # if strand == None:
        # self.strand = list('a') # defines the left strand
        # else:
        #     self.strand = strand

        self.strand = [ 'a' if x == 0 else 
                        't' if x == 1 else
                        'c' if x == 2 else
                        'g' if x == 3 else
                        'b' for x in [random.randrange(0,4) for i in range(0,20)]]
        self.strand.reverse()
        self.counter_strand = [ 'a' if x == 't' else 
                                't' if x == 'a' else
                                'c' if x == 'g' else
                                'g' if x == 'c' else
                                'b' for x in self.strand]

        print('strand', self.strand)
        self.game_counter = len(self.strand)-1
        print('counter_strand', self.counter_strand)

        self.backgrounds = []
        for index, base in enumerate(self.strand):
            bg_pair = [cocos.sprite.Sprite(pyglet.image.load('../res/minigame1/left_'+base+'.png'),position=(640,360)),
                                cocos.sprite.Sprite(pyglet.image.load('../res/minigame1/right_'+self.counter_strand[index]+'.png'),position=(640,360))]
            self.backgrounds.append(bg_pair)
            self.add(bg_pair[0], 1)
            self.add(bg_pair[1], 1)

        self.targets = []
        for base in self.strand:
            for i in range(0,3):
                random_coordinate = (random.randint(200, 1080), random.randint(200, 520))
                target = Button(*random_coordinate, '../res/minigame1/TARGET.png', self, self.target_clicked, isSpriteSheet=True)
                target.hide()
                self.targets.append(target)
                self.add(target,3)

        for button in self.buttons.values():
            self.add(button, 2)

        self.ad = Arm_Deployer(self,self.back)

        self.add(self.ad,4)
        # self.add(self.finish_level_pictures[0],0)   
        for i in range(4,-1,-1):
            self.add(self.finish_level_pictures[str(i)],0)

        self.add(self.finish_button,0)

        # th.start_new_thread(self.run_game, ())
        self.generate_target()

# methods
    def back(self):
        # self.victory = False
        # self.completed = True
        self.director.pop()
        print("select stage back")

    def next_image(self):
        # pass
        if not self.bg_index == 4: 
            self.finish_level_pictures[str(self.bg_index)].do(FadeOut(1))
            self.bg_index += 1
        else:
            self.finish_level()


    def finish_level(self):
        # self.victory = True
        # self.completed = True
        # self.director.pop()
        print("finished_level")
        self.victory_action()

    def fail_level(self):
        # self.dire

        self.fail_action()

    def generate_target(self):

        self.current_target = self.targets[self.accomplished_targets]
        self.current_target.show()

    def target_clicked(self):
        print('clkiecked')
        # self.cuurspr.do()
        self.accomplished_targets += 1
        self.target_eliminated = True
       
        self.to_clean.append(self.current_target)
        
        self.current_target.spr.do(CallFunc(self.change_button_sprite)+CallFunc(self.next_background))
        self.current_target.disable()


        if self.game_counter >= 0:
            self.generate_target()
        else:
            self.finish_button.enable()

    def next_background(self):

        if self.accomplished_targets%3 == 0:

            print('next bg')
            bg_pair = self.backgrounds[self.game_counter]
            bg_pair[0].do(MoveBy((-640,0),1))
            bg_pair[1].do(MoveBy((640,0),1)+CallFunc(self.clean))
            for button in self.to_clean:
                button.spr.do(MoveBy((640 * (-1 if button.spr.position[0] < 640 else 1),0),1))

            for obj in bg_pair: self.to_clean.append(obj)

            self.game_counter -= 1

    # def change_s
    def clean(self):

        for obj in self.to_clean:            
            self.remove(obj)
        self.to_clean = []

    def change_button_sprite(self):
        try:
            self.current_target.spr.image = self.img_to_assign
            self.current_target.x -= 125
        except Exception as e:
            print(e)
示例#30
0
    def update_pop_ups(self, tag: str, b_press=set()):
        """Renderöi pop-up ikkunat näkyville tagin perusteella. Myös sen napit.

        Args:
            tag (str): mikä pop-up ikkuna halutaan näkyville.
            b_press (set(str), valinnainen): Renderöi kaikki setissä olevat napit painetuiksi.
        """
        size = (350, 250)
        x = (self.screen_size[0] - size[0]) // 2
        y = (self.screen_size[1] - size[1]) // 2
        restart_pop = Tile(0, x, y, color=(100, 100, 100))
        restart_pop.color = (230, 200, 200)
        restart_pop.image = pg.transform.scale(restart_pop.img, size)
        self.pop_ups.add(restart_pop)

        # Buttons:

        margin = 15
        b_size = (90, 35)
        if "b_yes" in b_press:
            b_color = (0, 100, 0)
        else:
            b_color = (0, 200, 0)
        b_yes = Button(tag="b_yes",
                       text="Yes",
                       text_color=(240, 240, 240),
                       img_file_str=self.files.get_button_img_str(),
                       b_color=b_color,
                       position=(x + size[0] // 2 - b_size[0] * 1.5 + 20,
                                 y + size[1] // 1.5),
                       size=b_size,
                       rotate=0)

        if "b_no" in b_press:
            b_color = (100, 0, 0)
        else:
            b_color = (200, 0, 0)
        b_no = Button(tag="b_no",
                      text="No",
                      text_color=(240, 240, 240),
                      img_file_str=self.files.get_button_img_str(),
                      b_color=b_color,
                      position=(x + size[0] // 2 + b_size[0] * .5 - 20,
                                y + size[1] // 1.5),
                      size=b_size,
                      rotate=0)

        self.pop_up_buttons.add(b_yes)
        self.pop_up_buttons.add(b_no)

        # Text:
        x = x + margin
        y = y + margin
        s = ""
        if tag == "restart":
            s = "Are you sure you want restart?"
        elif tag == "menu":
            s = "Return to the main menu?"
        text = Text(s, x, y, 25, (255, 255, 255), size[0] - margin * 2, 40,
                    (100, 100, 100))

        self.pop_ups.add(text)
示例#31
0
    def update_buttons(self, b_press=set()):
        """Renderöi kaikki napit ja nappien värin vaihdon

        Args:
            b_press (set(str), valinnainen): Renderöi kaikki setissä olevat napit painetuiksi.
        """
        b_size = 70
        x = self.m_x + self.cell_size * self.game.get_size()
        y = self.cell_size * self.game.get_size()

        b_press_up_color = (0, 0, 220)
        b_press_down_color = (0, 0, 100)
        y_margin = 30

        if "b_up" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_up = Button(
            tag="b_up",
            text=None,
            text_color=None,
            img_file_str=self.files.get_button_up_img_str(),
            b_color=b_color,
            position=((((self.screen_size[0] - x) // 2) + x) - (b_size // 2),
                      (self.m_y + y // 2) - b_size * 1.5 + y_margin),
            size=(b_size, b_size),
            rotate=0)

        if "b_down" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_down = Button(tag="b_down",
                        text=None,
                        text_color=None,
                        img_file_str=self.files.get_button_up_img_str(),
                        b_color=b_color,
                        position=((((self.screen_size[0] - x) // 2) + x) -
                                  (b_size // 2), (self.m_y + y // 2) -
                                  b_size * 1.5 + b_size * 2 + y_margin),
                        size=(b_size, b_size),
                        rotate=180)

        if "b_right" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_right = Button(
            tag="b_right",
            text=None,
            text_color=None,
            img_file_str=self.files.get_button_up_img_str(),
            b_color=b_color,
            position=((((self.screen_size[0] - x) // 2) + x) - (b_size // 2) +
                      b_size,
                      (self.m_y + y // 2) - b_size * 1.5 + b_size + y_margin),
            size=(b_size, b_size),
            rotate=-90)

        if "b_left" in b_press:
            b_color = b_press_down_color
        else:
            b_color = b_press_up_color
        b_left = Button(tag="b_left",
                        text=None,
                        text_color=None,
                        img_file_str=self.files.get_button_up_img_str(),
                        b_color=b_color,
                        position=((((self.screen_size[0] - x) // 2) + x) -
                                  (b_size // 2) - b_size, (self.m_y + y // 2) -
                                  b_size * 1.5 + b_size + y_margin),
                        size=(b_size, b_size),
                        rotate=90)

        self.buttons.add(b_up)
        self.buttons.add(b_down)
        self.buttons.add(b_right)
        self.buttons.add(b_left)

        if "b_restart" in b_press:
            b_color = (100, 0, 0)
        else:
            b_color = (200, 0, 0)
        b_restart = Button(tag="b_restart",
                           text="Restart",
                           text_color=(240, 240, 240),
                           img_file_str=self.files.get_button_img_str(),
                           b_color=b_color,
                           position=((((self.screen_size[0] - x) // 2) + x) -
                                     (90 // 2) - 90 // 1.5, self.m_y),
                           size=(90, 35),
                           rotate=0)

        if "b_menu" in b_press:
            b_color = (100, 0, 0)
        else:
            b_color = (200, 0, 0)
        b_menu = Button(tag="b_menu",
                        text="Menu",
                        text_color=(240, 240, 240),
                        img_file_str=self.files.get_button_img_str(),
                        b_color=b_color,
                        position=((((self.screen_size[0] - x) // 2) + x) -
                                  (90 // 2) + 90 // 1.5, self.m_y),
                        size=(90, 35),
                        rotate=0)

        self.buttons.add(b_restart)
        self.buttons.add(b_menu)

        self.all_sprites.add(self.buttons)
示例#32
0
    def process(self):
        # Load Image
        slitherPosterImg = utility.loadImage("2017_slither_poster")
        slitherPosterImg = utility.resizeImage(slitherPosterImg, (800, 600))
        slitherPosterRect = slitherPosterImg.get_rect()
        slitherPosterRect.center = SCREEN_MID

        # Load Sound
        introBMG = utility.loadSound("BGM")
        introBMG.set_volume(0.3)

        # event
        mEventDistributor = pygameEventDistributor(GAME_INTRO_LISTENING_EVENT)
        mEventDistributor.listen(
            Request("GameIntro_quit", self._quit, addtionalTarget=pygame.QUIT))
        mTickEventHandler = tickEventHandler.TickEventHandler(
            mEventDistributor)

        # button settings
        buttonSize = (150, 40)
        fontSize = 30
        padding_x = 150
        padding_y = 150

        # make button
        player1Btn = Button(self.returnP1HS,
                            text="1 player",
                            alignment=BOTTOM_LEFT,
                            location=(0 + padding_x,
                                      SCREEN_HEIGHT - padding_y),
                            buttonSize=buttonSize,
                            fontSize=fontSize)
        player1Btn.listen(mTickEventHandler)
        player2Btn = Button(self.returnP2C,
                            text="2 players",
                            alignment=BOTTOM_RIGHT,
                            location=(SCREEN_WIDTH - padding_x,
                                      SCREEN_HEIGHT - padding_y),
                            buttonSize=buttonSize,
                            fontSize=fontSize)
        player2Btn.listen(mTickEventHandler)
        quitBtn = Button(self._quit,
                         text="quit",
                         alignment=BOTTOM_MIDDLE,
                         location=(SCREEN_WIDTH / 2, SCREEN_HEIGHT),
                         buttonSize=buttonSize,
                         fontSize=fontSize,
                         backgroundColor=RED)
        quitBtn.listen(mTickEventHandler)

        # make text
        title = Text(color=BLUE,
                     text="Slither Game by Enjoeyland",
                     fontSize=40,
                     location=(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4),
                     alignment=TOP_MIDDLE)

        # merge(make intro page)
        groupIntro = pygame.sprite.Group()
        groupIntro.add(player1Btn)
        groupIntro.add(player2Btn)
        groupIntro.add(quitBtn)
        groupIntro.add(title)

        utility.playSound(introBMG, loops=PLAY_INFINITELY)

        while self.__changedGameState == None:

            mEventDistributor.distribute()

            self.screen.fill(SCREEN_BACKGROUND)

            self.screen.blit(slitherPosterImg, (0, 0))

            groupIntro.update()
            groupIntro.draw(self.screen)

            pygame.display.update()
            pygame.time.Clock().tick(10)

        introBMG.fadeout(2)
        return self.__changedGameState