def _toggle_img(self, checkbox: UIImage): if self._checkboxes.get(checkbox): checkbox.set_image(LogBookPanel.UNCHECKED_IMG) self._checkboxes[checkbox] = False else: checkbox.set_image(LogBookPanel.CHECKED_IMG) self._checkboxes[checkbox] = True
class Enemy(pygame.sprite.Sprite): def __init__(self, health, manager, x, game, asset): super().__init__() self.game = game self.health = health self.asset = asset self.velocity = 1 self.image = pygame.image.load('assets/enemy.png') self.image = pygame.transform.scale(self.image, (50, 50)) self.ennemyImage = UIImage(relative_rect=pygame.Rect((0, 0), (50, 50)), manager=manager, image_surface=self.image) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = -100 def down(self): if not self.game.checkColision(self, self.game.allPlayers): self.rect.y += self.velocity self.ennemyImage.set_position((self.rect.x, self.rect.y)) else: if self.game.player.hit(): self.remove() if self.rect.y > 530: self.game.score -= 50 self.game.setLabelScore() self.remove() def remove(self): self.ennemyImage.kill() self.game.allEnemy.remove(self)
class Missile(pygame.sprite.Sprite): def __init__(self, player, manager, x): super().__init__() self.velocity = 10 self.player = player self.image = pygame.image.load('assets/missile.png') self.image = pygame.transform.scale(self.image, (10, 50)) # self.rectImage = self.image.get_rect() self.missileImage = UIImage(relative_rect=pygame.Rect( (self.player.rect.x + 25 - 5, self.player.rect.y - 50), (10, 50)), manager=manager, image_surface=self.image) self.rect = self.image.get_rect() self.rect.x = player.rect.x + 25 - 5 + x self.rect.y = player.rect.y - 50 def remove(self): self.player.allMissile.remove(self) self.missileImage.kill() def hit(self, enemy): if enemy.health > 0: enemy.health -= self.player.damage return True def isDead(self, enemy): if enemy.health <= 0: return True return False def move(self): self.rect.y -= self.velocity self.missileImage.set_position((self.rect.x, self.rect.y)) if self.player.game.checkColision(self, self.player.game.allEnemy): for enemy in self.player.game.checkColision( self, self.player.game.allEnemy): self.hit(enemy) if self.isDead(enemy): enemy.remove() self.player.getSurprise(enemy.asset) enemy.ennemyImage.kill() self.player.game.score += self.player.game.addScore self.player.game.setLabelScore() self.player.game.setLabelCredit() self.remove() if self.rect.y < 0: self.remove()
def __init__(self, player, manager, x): super().__init__() self.velocity = 10 self.player = player self.image = pygame.image.load('assets/missile.png') self.image = pygame.transform.scale(self.image, (10, 50)) # self.rectImage = self.image.get_rect() self.missileImage = UIImage(relative_rect=pygame.Rect( (self.player.rect.x + 25 - 5, self.player.rect.y - 50), (10, 50)), manager=manager, image_surface=self.image) self.rect = self.image.get_rect() self.rect.x = player.rect.x + 25 - 5 + x self.rect.y = player.rect.y - 50
def __init__(self, health, manager, x, game, asset): super().__init__() self.game = game self.health = health self.asset = asset self.velocity = 1 self.image = pygame.image.load('assets/enemy.png') self.image = pygame.transform.scale(self.image, (50, 50)) self.ennemyImage = UIImage(relative_rect=pygame.Rect((0, 0), (50, 50)), manager=manager, image_surface=self.image) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = -100
def recreate_ui(self): self.ui_manager.set_window_resolution(self.options.resolution) self.ui_manager.clear_and_reset() self.background_surface = pygame.Surface(self.options.resolution) if self.start_up == True: self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), title_screen_image, self.ui_manager) elif self.enter_mines == True: self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), mines_image, self.ui_manager) elif self.enter_busstop == True: self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), busstop_image, self.ui_manager) elif self.enter_uptown == True: self.image = UIImage(pygame.Rect((0, 0), self.options.resolution), uptown_image, self.ui_manager) else: self.background_surface.fill(self.ui_manager.get_theme().get_colour('dark_bg')) self.background_surface.blit(pygame.image.load("media/images/background.png"), (0, 0)) global response_history response = response_history response_history = response self.text_entry = UITextEntryLine(pygame.Rect((50, 550), (700, 50)), self.ui_manager, object_id = "#text_entry") self.text_block = UITextBox(response, pygame.Rect((50, 25), (700, 500)), self.ui_manager, object_id = "#text_block")
def _create_section(self, title: str, items: Enum, y_offset) -> int: item_height = 35 label_rect = pygame.Rect((0, y_offset), (LogBookPanel.PANEL_WIDTH, item_height)) label_text = "<strong>" + title + "</strong>" title_label = UITextBox(label_text, label_rect, self.manager, container=self.panel) y_offset += item_height item_label_width = LogBookPanel.PANEL_WIDTH - 30 for item in items: img_rect = pygame.Rect((5, y_offset + 6), (24, 24)) checkbox_img = UIImage(img_rect, LogBookPanel.UNCHECKED_IMG, self.manager, container=self.panel) label_rect = pygame.Rect((30, y_offset), (item_label_width, item_height)) item_button = UITextBox(item.pretty(), label_rect, self.manager, container=self.panel) self._checkboxes[checkbox_img] = False y_offset += item_height return y_offset
def __init__(self, rect, ui_manager): super().__init__(rect, ui_manager, window_display_title='Scale', object_id='#scaling_window', resizable=True) loaded_test_image = pygame.image.load( 'data/images/splat.png').convert_alpha() self.test_image = UIImage(pygame.Rect( (10, 10), (self.get_container().get_size()[0] - 20, self.get_container().get_size()[1] - 20)), loaded_test_image, self.ui_manager, container=self, anchors={ 'top': 'top', 'bottom': 'bottom', 'left': 'left', 'right': 'right' }) self.set_blocking(True)
def generate_map_preview(self): map_seed = self.ui_elements['input_seed'].get_text() # just sneaking in some random debug info here print( f"HS Grass Value: {self.ui_elements['hs_grass'].get_current_value()}" ) print( f"HS Water Value: {self.ui_elements['hs_water'].get_current_value()}" ) print( f"HS Mountain Value: {self.ui_elements['hs_mountain'].get_current_value()}" ) # convert to an int if we have a numeric string if type(map_seed) is not int and map_seed.isnumeric(): map_seed = int(map_seed) map_size = self.ui_elements['dd_map_size'].selected_option # this should always be numeric, but lets be proper and check it if type(map_size) is not int and map_size.isnumeric(): map_size = int(map_size) else: raise TypeError(f"Got a non-numeric map size: {map_size}") self.map_grid = generate_height_grid( generate_noise_grid(map_size, map_size, map_seed)) self.pv_img.fill((0, 0, 0)) # okay, should have a height grid now, let's make the image # we also want to offset the image so it's centered in the preview area, so we'll need to adjust the X/Y # values of the image according to the offset from 256 x_off = (256 - self.map_grid.width) // 2 y_off = (256 - self.map_grid.height) // 2 for y in range(self.map_grid.height): for x in range(self.map_grid.width): self.pv_img.set_at((x + x_off, y + y_off), self._c_map[self.map_grid[(x, y)]]) # reload PV image element pv_rect = self.ui_elements['pv_image'].relative_rect self.ui_elements['pv_image'] = UIImage(pv_rect, self.pv_img, self.gui, self.ui_elements['panel'])
def process_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.ui_manager.process_events(event) if event.type == pygame.VIDEORESIZE: self.opt.W = event.w self.opt.H = event.h self.opt.resolution = (event.w, event.h) self.recreate_ui() if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == self.btn_gen_explore: self.pnl_gen_explore.show() self.pnl_gen_search.hide() self.pnl_tiles_explore.hide() self.pnl_tiles_search.hide() self.active_panel = self.pnl_gen_explore elif event.ui_element == self.btn_gen_search: self.pnl_gen_explore.hide() self.pnl_gen_search.show() self.pnl_tiles_explore.hide() self.pnl_tiles_search.hide() self.active_panel = self.btn_gen_search elif event.ui_element == self.btn_tiles_explore: self.pnl_gen_explore.hide() self.pnl_gen_search.hide() self.pnl_tiles_explore.show() self.pnl_tiles_search.hide() self.active_panel = self.btn_tiles_explore elif event.ui_element == self.btn_tiles_search: self.pnl_gen_explore.hide() self.pnl_gen_search.hide() self.pnl_tiles_explore.hide() self.pnl_tiles_search.show() self.active_panel = self.pnl_tiles_search elif event.ui_element == self.btn_gen_explore_save_as_png: self.file_dialog_gen_explore_save_as_png = UIFileDialog( pygame.Rect(self.opt.W // 4, self.opt.H // 4, self.opt.W // 2, self.opt.H // 2), self.ui_manager, window_title='Save as PNG', initial_file_path='map.png', object_id='#file_dialog_gen_explore_save_as_png') if event.user_type == pygame_gui.UI_FILE_DIALOG_PATH_PICKED: if event.ui_element == self.file_dialog_gen_explore_save_as_png: self.gen_explore_image.save(event.text) if event.user_type == pygame_gui.UI_WINDOW_CLOSE: if event.ui_element == self.file_dialog_gen_explore_save_as_png: self.file_dialog_gen_explore_save_as_png = None if event.user_type == pygame_gui.UI_SELECTION_LIST_DOUBLE_CLICKED_SELECTION: if event.ui_element == self.gen_list: if self.gen_state.is_generator(event.text): M = self.gen_state.get_generator(event.text)() surface_w = self.opt.W - 435 surface_h = self.opt.H - 95 self.gen_explore_image = construct_bounded_map_image( M, surface_w, surface_h) image_bytes = self.gen_explore_image.tobytes() im_w, im_h = self.gen_explore_image.size shift_x = (surface_w - im_w) // 2 shift_y = (surface_h - im_h) // 2 if not self.gen_explore_map_image: self.gen_explore_map_image = UIImage( relative_rect=pygame.Rect( 360 + shift_x, 75 + shift_y, im_w, im_h), image_surface=pygame.image.fromstring( image_bytes, self.gen_explore_image.size, self.gen_explore_image.mode), manager=self.ui_manager, container=self.pnl_gen_explore, object_id='#gen_explore_map_image', ) else: self.gen_explore_map_image.set_relative_position( pygame.Rect(360 + shift_x, 75 + shift_y, im_w, im_h)) self.gen_explore_map_image.image = pygame.image.fromstring( image_bytes, self.gen_explore_image.size, self.gen_explore_image.mode) if not self.btn_gen_explore_save_as_png: self.btn_gen_explore_save_as_png = UIButton( pygame.Rect(self.opt.W - 265, 5, 190, 50), 'Save as PNG', manager=self.ui_manager, container=self.pnl_gen_explore, object_id='#btn_gen_explore_save_as_png', starting_height=10, ) else: self.gen_state.change_state(event.text) self.gen_list.set_item_list( self.gen_state.get_current_gen_list())
def __init__(self, layout_info, container, image_path, padding=None): super().__init__(layout_info, container, padding) image_surface = pygame.image.load(image_path).convert_alpha() self.element = UIImage(relative_rect=self.bounds, image_surface=image_surface, manager=self.manager)
class MenuBar(UIElement): """ Menubar sınıfı. İçinde menuler ve alt menuler içeren ui elemanı :param rect: elemanın pygame.Rect'i :param manager: ui yöneticisi :param container: bu elemanın neyin içinde olduğu :param parent: bu objenin 'sahibi' olan eleman :param object_id: objeye atanacak id :param anchors: objenin rect koordinatının nereye göre olduğunu bildiren dict :param menu_bar_data: bardaki menulerin ve alt menülerin bulunduğu dict """ def __init__(self, rect: pygame.Rect, manager, container: Union[IContainerLikeInterface, None] = None, parent: Union[UIElement, None] = None, object_id: Union[str, None] = None, anchors: Union[Dict[str, str], None] = None, menu_bar_data: Dict[str, Dict[str, Union[Dict, str]]] = MENU_BAR_DATA_DICT): super().__init__(rect, manager, container, starting_height=1, layer_thickness=1, anchors=anchors) self._create_valid_ids(container, parent, object_id, 'menu_bar') self.menu_data = menu_bar_data self.bg_color = None self.border_color = None self.shape_type = 'rectangle' self.rgb_tuple = None # type: Union[Tuple[int, int, int], None] self.open_menu = None self._selected_menu = None self._close_opened_menu = False self.rebuild_from_changed_theme_data() self.container_rect = pygame.Rect( self.relative_rect.left + (self.shadow_width + self.border_width), self.relative_rect.top + (self.shadow_width + self.border_width), self.relative_rect.width - 2 * (self.shadow_width + self.border_width), self.relative_rect.height - 2 * (self.shadow_width + self.border_width)) self.menu_bar_container = UIContainer(self.container_rect, manager, starting_height=1, parent_element=self, object_id='#menu_bar_container') # menü butonları için for loop current_y_pos = 0 for menu_key, menu_item in self.menu_data.items(): if menu_key == '#icon': icon_surf = pygame.image.load( os.path.join('litevision', 'res', 'image_examples', 'icon.png')).convert_alpha() self.icon = UIImage( pygame.Rect( (0 + GUI_OFFSET_VALUE + ((48 - 32) // 2), current_y_pos + GUI_OFFSET_VALUE), (32, 32)), icon_surf, self.ui_manager, self.menu_bar_container, self, menu_key) current_y_pos += (48 + GUI_OFFSET_VALUE) continue elif menu_key == '#empty_1' or menu_key == '#empty_2': empty_surf = pygame.Surface((48, 48), pygame.SRCALPHA, masks=pygame.Color('#2F4F4F')) UIImage( pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), empty_surf, self.ui_manager, self.menu_bar_container, self, menu_key) current_y_pos += (48 + GUI_OFFSET_VALUE) continue elif menu_key == '#start_pause': sp_surf = pygame.Surface((48, 48), pygame.SRCALPHA, masks=pygame.Color('#2F4F4F')) sp_icon = pygame.image.load( os.path.join('litevision', 'res', 'image_examples', 'start_icon', 'start.png')).convert_alpha() sp_surf.blit(sp_icon, (0, 0)) self.start_button = UIImage( pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), sp_surf, self.ui_manager, self.menu_bar_container, self, '#start_pause') current_y_pos += (48 + GUI_OFFSET_VALUE) continue elif menu_key == '#rgb_button': rgb_surf = pygame.Surface((48, 48), pygame.SRCALPHA, masks=pygame.Color('#2F4F4F')) rgb_icon = pygame.image.load( os.path.join('litevision', 'res', 'image_examples', 'rgb.png')).convert_alpha() rgb_surf.blit(rgb_icon, (0, 0)) self.rgb_button = UIImage( pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), rgb_surf, self.ui_manager, self.menu_bar_container, self, '#rgb_button') current_y_pos += (48 + GUI_OFFSET_VALUE) continue UIButton(pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), menu_item['display_name'], self.ui_manager, self.menu_bar_container, object_id=menu_key, parent_element=self) current_y_pos += (48 + GUI_OFFSET_VALUE) def unfocus(self): if self.open_menu is not None: self.open_menu.kill() self.open_menu = None if self._selected_menu is not None: self._selected_menu.unselect() self._selected_menu = None def kill(self): self.menu_bar_container.kill() super().kill() def _open_menu(self, event): if self.open_menu is not None: self.open_menu.kill() if event.ui_object_id != '#menu_bar.#start_processing': menu_key = event.ui_object_id.split('.')[-1] menu_size = ((len(self.menu_data[menu_key]['items']) * 20) + 3) item_data = [(item_data['display_name'], item_key) for item_key, item_data in self.menu_data[menu_key] ['items'].items()] menu_rect = pygame.Rect((0, 0), (200, menu_size)) menu_rect.topleft = event.ui_element.rect.topright top_ui_layer = self.ui_manager.get_sprite_group().get_top_layer() self.open_menu = UISelectionList(menu_rect, item_data, self.ui_manager, starting_height=top_ui_layer, parent_element=self, object_id=menu_key + '_items') self.ui_manager.set_focus_set(self) def rebuild_from_changed_theme_data(self): has_any_changed = False bg_color = self.ui_theme.get_colour_or_gradient( 'normal_bg', self.combined_element_ids) if bg_color != self.bg_color: self.bg_color = bg_color has_any_changed = True border_color = self.ui_theme.get_colour_or_gradient( 'normal_border', self.combined_element_ids) if border_color != self.border_color: self.border_color = border_color has_any_changed = True # misc shape_type_str = self.ui_theme.get_misc_data('shape', self.combined_element_ids) if (shape_type_str is not None and shape_type_str in ['rectangle'] and shape_type_str != self.shape_type): self.shape_type = shape_type_str has_any_changed = True if self._check_shape_theming_changed(defaults={ 'border_width': 1, 'shadow_width': 0, 'shape_corner_radius': 0 }): has_any_changed = True if has_any_changed: self.rebuild() def rebuild(self): theming_parameters = { 'normal_bg': self.bg_color, 'normal_border': self.border_color, 'border_width': self.border_width, 'shadow_width': self.shadow_width } if self.shape_type == 'rectangle': self.drawable_shape = RectDrawableShape(self.rect, theming_parameters, ['normal'], self.ui_manager) self.on_fresh_drawable_shape_ready() def process_event(self, event: pygame.event.Event) -> bool: consumed_event = False if (self is not None and event.type == pygame.MOUSEBUTTONDOWN and event.button in [pygame.BUTTON_LEFT, pygame.BUTTON_RIGHT]): scaled_mouse_pos = (int(event.pos[0] * self.ui_manager.mouse_pos_scale_factor[0]), int(event.pos[1] * self.ui_manager.mouse_pos_scale_factor[1])) if self.hover_point(scaled_mouse_pos[0], scaled_mouse_pos[1]): consumed_event = True if event.type == pygame.MOUSEBUTTONUP and event.button == 1: scaled_mouse_pos = self.start_button.ui_manager.calculate_scaled_mouse_position( event.pos) x = scaled_mouse_pos[0] y = scaled_mouse_pos[1] if self.start_button.hover_point(x, y): event_data = { 'user_type': pygame_gui.UI_BUTTON_START_PRESS, 'ui_element': self.start_button, 'ui_object_id': self.start_button.most_specific_combined_id } pygame.event.post( pygame.event.Event(pygame.USEREVENT, event_data)) elif self.rgb_button.hover_point(x, y): event_data = { 'user_type': pygame_gui.UI_BUTTON_START_PRESS, 'ui_element': self.rgb_button, 'ui_object_id': self.rgb_button.most_specific_combined_id } pygame.event.post( pygame.event.Event(pygame.USEREVENT, event_data)) if (event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_BUTTON_ON_HOVERED and event.ui_element in self.menu_bar_container.elements and self.open_menu != None): if self._selected_menu is not None: self._selected_menu.unselect() self._selected_menu = event.ui_element self._selected_menu.select() self._open_menu(event) if (event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_BUTTON_START_PRESS and event.ui_element in self.menu_bar_container.elements and event.ui_object_id != '#menu_bar.#start_pause' and event.ui_object_id != '#menu_bar.#rgb_button'): if self._selected_menu is not None: self._selected_menu.unselect() self._selected_menu = event.ui_element self._selected_menu.select() self._open_menu(event) return consumed_event def update(self, time_delta): super().update(time_delta) if self.menu_bar_container.layer_thickness != self.layer_thickness: self.layer_thickness = self.menu_bar_container.layer_thickness
def Main(cls): game_running = False engine_running = True speed_x = 5 speed_y = 5 player_pos_x = (MiPiGUI.g_screen_x * MiPiSettings.playerx_to_editor) player_pos_y = (MiPiGUI.g_screen_y * MiPiSettings.playery_to_editor) npc_pos_x = (MiPiGUI.g_screen_x * MiPiSettings.npcx_to_editor) npc_pos_y = (MiPiGUI.g_screen_y * MiPiSettings.npcy_to_editor) MiPiSettings.enemy_x = 800 / 2 MiPiSettings.enemy_y = 600 / 2 e_moverandx = 0 e_moverandy = 0 editableContent = False edMouseX = 0 edMouseY = 0 inputx = 0 inputy = 0 m_forwards = 'moving forwards' m_backwards = 'moving backwards' m_up = 'moving up' m_down = 'moving down' currentposition = '' Render.Shapes.CreateTriangle() MiPiPhysics.Player.BoxCollider2D(enginescreen, Render.GREEN, 30, 30, 60, 60) while engine_running: for event in pygame.event.get(): if event.type == pygame.QUIT: engine_running = False enginescreen.fill(Render.LIGHTCOLOR) MiPiGUI.GUI.EditorScreen() MiPiGUI.GUI.MiPiBorders(enginescreen, Render.DARKSHADE, 45, 176, 385, 292, 15) enginescreen.blit(MiPiGUI.editorlabel, MiPiGUI.editorborder) enginescreen.blit(MiPiGUI.engineborder_north, MiPiGUI.set_engineborder_north) enginescreen.blit(MiPiGUI.engineborder_south, MiPiGUI.set_engineborder_south) # edMouseX, edMouseY = pygame.mouse.get_pos() # MiPiGUI Labels MiPi.EditSprite() # if event.type == pygame.MOUSEMOTION: # print("X: %d, Y: %d" % (edMouseX, edMouseY)) if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_BUTTON_START_PRESS: if event.ui_element == MiPiGUI.play_button: if not MiPiSettings.editor_has_content: print(current_date, editor_error) logging.warning(current_date, editor_error) else: print( current_date, "Gameplay test window has been launched!") engine_running = False game_running = True if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_DROP_DOWN_MENU_CHANGED: if event.text == "Run": print(current_date, "Gamescreen window has been launched!") engine_running = False game_running = True if event.text == "Close": print(current_date, "Application has been closed") engine_running = False game_running = False if event.text == "Import Sprite": MiPiGUI.spritesubmenu.show() # ------------------------ Import Sprite --------------------------------------------------# if event.text == "Player": if platform.system() == MiPiSettings.Windows: MiPiGUI.playermenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select a player sprite", initial_file_path="C:/", allow_existing_files_only=True, visible=True) MiPiSettings.playersprite = True MiPiSettings.editablePlayerSprite = True MiPiSettings.editableNPCSprite = False MiPi.EraseUI() MiPiGUI.spritesubmenu.hide() elif platform.system() == MiPiSettings.Mac: MiPiGUI.playermenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select a player sprite", initial_file_path="~/Desktop", allow_existing_files_only=True, visible=True) MiPiSettings.playersprite = True MiPiSettings.editablePlayerSprite = True MiPiSettings.editableNPCSprite = False MiPiGUI.spritesubmenu.hide() elif platform.system() == MiPiSettings.Linux: MiPiGUI.playermenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select a player sprite", initial_file_path="/bin", allow_existing_files_only=True, visible=True) MiPiSettings.playersprite = True MiPiSettings.editablePlayerSprite = True MiPiSettings.editableNPCSprite = False MiPiGUI.spritesubmenu.hide() else: print(current_date, MiPiSettings.platform_error) logging.warning(current_date, MiPiSettings.platform_error) if event.text == "NPC": MiPiGUI.npcmenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select an npc sprite", initial_file_path="C:/", allow_existing_files_only=True, visible=True) MiPi.UnderDev(MiPiSettings.underdevelopment) MiPiSettings.npcsprite = True MiPiSettings.editableNPCSprite = True MiPiSettings.editablePlayerSprite = False MiPi.EraseUI() MiPiGUI.spritesubmenu.hide() if event.text == "Object": MiPi.UnderDev(MiPiSettings.underdevelopment) MiPiGUI.spritesubmenu.hide() # ------------------------ Import Sprite --------------------------------------------------# # -------------- Import Tilemap -----------------------------------------------------------# if event.text == "Import Tilemap": print(MiPiSettings.underdevelopment) if platform.system() == MiPiSettings.Windows: MiPiGUI.tilemapmenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select a tilemap", initial_file_path="C:/", allow_existing_files_only=True, visible=True) MiPiSettings.tilemap_chosen = True MiPiSettings.tilemap_ready = True elif platform.system() == MiPiSettings.Mac: MiPiGUI.tilemapmenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select a tilemap", initial_file_path="~/Desktop", allow_existing_files_only=True, visible=True) MiPiSettings.tilemap_chosen = True MiPiSettings.tilemap_ready = True elif platform.system() == MiPiSettings.Linux: MiPiGUI.tilemapmenu = pygame_gui.windows.ui_file_dialog.UIFileDialog( rect=pygame.Rect((200, 200), (260, 300)), manager=MiPiGUI.mainframe, window_title="Select a tilemap", initial_file_path="/bin", allow_existing_files_only=True, visible=True) MiPiSettings.tilemap_chosen = True MiPiSettings.tilemap_ready = True else: print(current_date, MiPiSettings.platform_error) logging.warning(current_date, MiPiSettings.platform_error) # -------------- Import Tilemap -----------------------------------------------------------# if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_FILE_DIALOG_PATH_PICKED: # ----------- NPC Sprite Import --------------------------------------------------------------# if MiPiSettings.npcsprite: try: if not MiPiSettings.playersprite_available: print( "Import a player sprite first: <- Replace this with a message box!" ) else: MiPiSettings.npc_path = create_resource_path( event.text) MiPiSettings.npc_img = pygame.image.load( MiPiSettings.npc_path).convert_alpha() npc_rect = MiPiSettings.npc_img.get_rect() aspect_ratio = npc_rect.width / npc_rect.height scalability = False if npc_rect.width > MiPiGUI.max_image_display_dimensions[ 0]: npc_rect.width = MiPiGUI.max_image_display_dimensions[ 0] npc_rect.height = int(npc_rect.width / aspect_ratio) scalability = True if npc_rect.height > MiPiGUI.max_image_display_dimensions[ 1]: npc_rect.height = MiPiGUI.max_image_display_dimensions[ 1] npc_rect.width = int(npc_rect.height * aspect_ratio) scalability = True if scalability: MiPiSettings.npc_img = pygame.transform.smoothscale( MiPiSettings.npc_img, npc_rect.size) # Boundary values are subject to change based on image size and scaling! # Make these values editable in a gui by the user: x range: 80-400 # y range: 215-425 Best default: 80,425 npcinputx = 80 npcinputy = 215 npcx = npcinputx npcy = npcinputy # Get current slider values getnpcspritex = MiPiGUI.npcxlocbar.get_current_value( ) getnpcspritey = MiPiGUI.npcylocbar.get_current_value( ) MiPiGUI.npctextx = str(getnpcspritex) MiPiGUI.npctexty = str(getnpcspritey) MiPiGUI.npcxlocbar.update(delta_time) MiPiGUI.npcylocbar.update(delta_time) npcx = getnpcspritex npcy = getnpcspritey npc_rect.x = npcx npc_rect.y = npcy if npc_rect.x < 80 or npc_rect.x > 400: print( "Value out of range! Setting to default" ) npc_rect.x = 80 if npc_rect.y < 215 or npc_rect.y > 425: print( "Value out of range! Setting to default" ) npc_rect.y = 425 npc_rect.center = (npc_rect.x, npc_rect.y) # UI manager mainframe has now been created after pygame.init() # Thank you MyreMylar(pygame_gui) for your help in spotting this :) # Currently see line 14 of MiPiGUI file for pygame.init() MiPiSettings.import_npc_sprite = UIImage( relative_rect=npc_rect, image_surface=MiPiSettings.npc_img, manager=MiPiGUI.mainframe) MiPiSettings.npcx_to_editor = (npc_rect.x / 400) MiPiSettings.npcy_to_editor = (npc_rect.y / 425) npc_pos_x = (MiPiGUI.g_screen_x * MiPiSettings.npcx_to_editor) npc_pos_y = (MiPiGUI.g_screen_y * MiPiSettings.npcy_to_editor) npc_pos_x = npc_pos_x - MiPiSettings.offset_x npc_pos_y = npc_pos_y - MiPiSettings.offset_y MiPiSettings.npcsprite = False MiPiSettings.editor_has_content = True except pygame.error: pass # --------------------------------------------------------------------------------------------# if MiPiSettings.tilemap_chosen: try: MiPiSettings.tile_path = create_resource_path( event.text) MiPiSettings.tilemap_img = pygame.image.load( MiPiSettings.tile_path).convert_alpha() tilemap_rect = MiPiSettings.tilemap_img.get_rect( ) scalability = False if tilemap_rect.width >= MiPiGUI.max_image_display_dimensions[ 0]: tilemap_rect.width = MiPiGUI.edwidth tilemap_rect.height = MiPiGUI.edheight scalability = True if tilemap_rect.height > MiPiGUI.max_image_display_dimensions[ 1]: tilemap_rect.height = MiPiGUI.tilemap_height tilemap_rect.width = MiPiGUI.tilemap_width scalability = True if tilemap_rect.width <= MiPiGUI.max_image_display_dimensions[ 0]: tilemap_rect.width = MiPiGUI.tilemap_width tilemap_rect.height = MiPiGUI.tilemap_height scalability = True if tilemap_rect.height < MiPiGUI.max_image_display_dimensions[ 1]: tilemap_rect.height = MiPiGUI.tilemap_height tilemap_rect.width = MiPiGUI.tilemap_width scalability = True if scalability: MiPiSettings.tilemap_img = pygame.transform.smoothscale( MiPiSettings.tilemap_img, tilemap_rect.size) tilemap_rect.x = 238 tilemap_rect.y = 321 tilemap_rect.center = (tilemap_rect.x, tilemap_rect.y) MiPiSettings.import_tilemap = UIImage( relative_rect=tilemap_rect, image_surface=MiPiSettings.tilemap_img, manager=MiPiGUI.mainframe) MiPiSettings.tilemap_chosen = False MiPiSettings.tilemap_available = True except pygame.error: pass # ----------- Player Sprite Import -----------------------------------------------------------# if MiPiSettings.playersprite: try: if not MiPiSettings.tilemap_available: print( "Please import a tilemap first! <- Replace this with a message box!" ) if MiPiSettings.playersprite_available: print( "Player sprite available. <- Replace this with a message box!" ) else: MiPiSettings.sprite_path = create_resource_path( event.text) MiPiSettings.player_img = pygame.image.load( MiPiSettings.sprite_path ).convert_alpha() sprite_rect = MiPiSettings.player_img.get_rect( ) aspect_ratio = sprite_rect.width / sprite_rect.height scalability = False if sprite_rect.width > MiPiGUI.max_image_display_dimensions[ 0]: sprite_rect.width = MiPiGUI.max_image_display_dimensions[ 0] sprite_rect.height = int( sprite_rect.width / aspect_ratio) scalability = True if sprite_rect.height > MiPiGUI.max_image_display_dimensions[ 1]: sprite_rect.height = MiPiGUI.max_image_display_dimensions[ 1] sprite_rect.width = int( sprite_rect.height * aspect_ratio) scalability = True if scalability: MiPiSettings.player_img = pygame.transform.smoothscale( MiPiSettings.player_img, sprite_rect.size) # Removes any duplicate copies of player sprites in the editor if MiPiSettings.player_removeduplicates >= 1: MiPiSettings.player_img.fill( Render.TRANSPARENCY) MiPiSettings.player_removeduplicates = 0 # Boundary values are subject to change based on image size and scaling! # Make these values editable in a gui by the user: x range: 80-400 # y range: 215-425 Best default: 80,425 inputx = 80 inputy = 215 x = inputx y = inputy # Get current slider values getspritex = MiPiGUI.playerxlocbar.get_current_value( ) getspritey = MiPiGUI.playerylocbar.get_current_value( ) MiPiGUI.textx = str(getspritex) MiPiGUI.texty = str(getspritey) MiPiGUI.playerxlocbar.update(delta_time) MiPiGUI.playerylocbar.update(delta_time) x = getspritex y = getspritey sprite_rect.x = x sprite_rect.y = y if sprite_rect.x < 80 or sprite_rect.x > 400: print( "Value out of range! Setting to default" ) sprite_rect.x = 80 if sprite_rect.y < 215 or sprite_rect.y > 425: print( "Value out of range! Setting to default" ) sprite_rect.y = 425 sprite_rect.center = (sprite_rect.x, sprite_rect.y) # UI manager mainframe has now been created after pygame.init() # Thank you MyreMylar(pygame_gui) for your help in spotting this :) # Currently see line 14 of MiPiGUI file for pygame.init() MiPiSettings.import_player_sprite = UIImage( relative_rect=sprite_rect, image_surface=MiPiSettings.player_img, manager=MiPiGUI.mainframe) MiPiSettings.playerx_to_editor = ( sprite_rect.x / 400) MiPiSettings.playery_to_editor = ( sprite_rect.y / 425) player_pos_x = ( MiPiGUI.g_screen_x * MiPiSettings.playerx_to_editor) player_pos_y = ( MiPiGUI.g_screen_y * MiPiSettings.playery_to_editor) player_pos_x = player_pos_x - MiPiSettings.offset_x player_pos_y = player_pos_y - MiPiSettings.offset_y MiPiSettings.playersprite_available = True MiPiSettings.playersprite = False MiPiSettings.editor_has_content = True except pygame.error: pass # --------------------------------------------------------------------------------------------# # ------------------- UPDATE PLAYER BUTTON CONTROLS ---------------------------------------------------# if event.user_type == pygame_gui.UI_BUTTON_START_PRESS: if event.ui_element == MiPiGUI.updateplayer_button: print(inprogress) MiPiSettings.import_player_sprite.hide() if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == MiPiGUI.updateplayer_button: change_rect = MiPiSettings.player_img.get_rect() movex = MiPiGUI.playerxlocbar.get_current_value() movey = MiPiGUI.playerylocbar.get_current_value() change_rect.x = movex change_rect.y = movey change_rect.center = (change_rect.x, change_rect.y) MiPiSettings.import_player_sprite = UIImage( relative_rect=change_rect, image_surface=MiPiSettings.player_img, manager=MiPiGUI.mainframe) MiPiSettings.playerx_to_editor = (change_rect.x / 400) MiPiSettings.playery_to_editor = (change_rect.y / 425) player_pos_x = (MiPiGUI.g_screen_x * MiPiSettings.playerx_to_editor) player_pos_y = (MiPiGUI.g_screen_y * MiPiSettings.playery_to_editor) player_pos_x = player_pos_x - MiPiSettings.offset_x player_pos_y = player_pos_y - MiPiSettings.offset_y getspritex = MiPiGUI.playerxlocbar.get_current_value( ) getspritey = MiPiGUI.playerylocbar.get_current_value( ) MiPiGUI.textx = str(getspritex) MiPiGUI.texty = str(getspritey) MiPiGUI.playerxlocbar.update(delta_time) MiPiGUI.playerylocbar.update(delta_time) # ----------------------------------------------------------------------------------------------------# # ------------------- UPDATE NPC BUTTON CONTROLS -----------------------------------------------------# if event.user_type == pygame_gui.UI_BUTTON_START_PRESS: if event.ui_element == MiPiGUI.updatenpc_button: print(inprogress) MiPiSettings.import_npc_sprite.hide() if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == MiPiGUI.updatenpc_button: change_rect_npc = MiPiSettings.npc_img.get_rect() movenpcx = MiPiGUI.npcxlocbar.get_current_value() movenpcy = MiPiGUI.npcylocbar.get_current_value() change_rect_npc.x = movenpcx change_rect_npc.y = movenpcy change_rect_npc.center = (change_rect_npc.x, change_rect_npc.y) MiPiSettings.import_npc_sprite = UIImage( relative_rect=change_rect_npc, image_surface=MiPiSettings.npc_img, manager=MiPiGUI.mainframe) MiPiSettings.npcx_to_editor = (change_rect_npc.x / 400) MiPiSettings.npcy_to_editor = (change_rect_npc.y / 425) npc_pos_x = (MiPiGUI.g_screen_x * MiPiSettings.npcx_to_editor) npc_pos_y = (MiPiGUI.g_screen_y * MiPiSettings.npcy_to_editor) npc_pos_x = npc_pos_x - MiPiSettings.offset_x npc_pos_y = npc_pos_y - MiPiSettings.offset_y getnpcspritex = MiPiGUI.npcxlocbar.get_current_value( ) getnpcspritey = MiPiGUI.npcylocbar.get_current_value( ) MiPiGUI.npctextx = str(getnpcspritex) MiPiGUI.npctexty = str(getnpcspritey) MiPiGUI.npcxlocbar.update(delta_time) MiPiGUI.npcylocbar.update(delta_time) # ----------------------------------------------------------------------------------------------------# if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: engine_running = False # Updates: Tried de-indenting MiPiGUI updates, but this caused instability in all # looped events including gui elements. Also tried setting updates in a method, but # this caused pygame.event to throw an error. So instead, I indented pygame display # updates and everything seems to still work correctly. Will keep an eye on updates. # I did notice that de-indenting update methods will put them outside the main engine's # while loop. For now, just gonna keep them in the while loop unless I can find a # workaround. MiPiGUI.mainframe.process_events(event) MiPiGUI.mainframe.draw_ui(enginescreen) MiPiGUI.mainframe.update(delta_time) pygame.display.flip() pygame.display.update() while game_running: for game in pygame.event.get(): if game.type == pygame.QUIT: pygame.display.set_caption(engine_title) MiPi.Main() game_running = False # The screen gets rendered a color to be tested regardless if a tilemap is ready to be tested. gamescreen.fill(Render.BLUE) # Collider box2D MiPi.DrawBoxCol(box_x, box_y) # Remove this later MiPi.ShowPlayerPos(player_pos_x, player_pos_y) # If the user has placed a tilemap and is ready to test with a tilemap, then blit it to the test screen if MiPiSettings.tilemap_ready: gamescreen.blit( pygame.transform.scale( MiPiSettings.tilemap_img, (MiPiGUI.g_screen_x, MiPiGUI.g_screen_y)), (0, 0)) # Player movement boundaries if player_pos_x > MiPiGUI.g_screen_x - 1: player_pos_x = 0 elif player_pos_x < 0: player_pos_x = MiPiGUI.g_screen_x if player_pos_y > MiPiGUI.g_screen_y - 1: player_pos_y = 0 elif player_pos_y < 0: player_pos_y = MiPiGUI.g_screen_y # Enemy movement boundaries if MiPiSettings.enemy_x > MiPiGUI.g_screen_x - 1: MiPiSettings.enemy_x = 0 elif MiPiSettings.enemy_x < 0: MiPiSettings.enemy_x = MiPiGUI.g_screen_x if MiPiSettings.enemy_y > MiPiGUI.g_screen_y - 1: MiPiSettings.enemy_y = 0 elif MiPiSettings.enemy_y < 0: MiPiSettings.enemy_y = MiPiGUI.g_screen_y e_moverandx = random.randint(1, 3) e_moverandy = random.randint(4, 6) if 1 <= e_moverandx <= 2: MiPiSettings.enemy_x -= MiPiSettings.enemy_speed elif e_moverandx == 3: MiPiSettings.enemy_x += MiPiSettings.enemy_speed if 4 <= e_moverandy <= 5: MiPiSettings.enemy_y -= MiPiSettings.enemy_speed elif e_moverandy == 6: MiPiSettings.enemy_y += MiPiSettings.enemy_speed pygame.key.set_repeat( 1, 10 ) # Not a friendly way of movement while key is held down, but works! # Movement loop if game.type == pygame.KEYDOWN: if game.key == pygame.K_LEFT: player_pos_x -= speed_x print("(<) Left key pressed", currentposition) currentposition = m_backwards if game.key == pygame.K_RIGHT: player_pos_x += speed_x print("(>) Right key pressed", currentposition) currentposition = m_forwards if game.key == pygame.K_UP: player_pos_y -= speed_y print("(^) Up key pressed", currentposition) currentposition = m_up if game.key == pygame.K_DOWN: player_pos_y += speed_y print("(v)Down key pressed", currentposition) currentposition = m_down if game.key == pygame.K_a: player_pos_x -= speed_x print("(a) Left key pressed", currentposition) currentposition = m_backwards if game.key == pygame.K_d: player_pos_x += speed_x print("(d) Right key pressed", currentposition) currentposition = m_forwards if game.key == pygame.K_w: player_pos_y -= speed_y print("(w) Up key pressed", currentposition) currentposition = m_up if game.key == pygame.K_s: player_pos_y += speed_y print("(s) Down key pressed", currentposition) currentposition = m_down # Collisions ------------------------------------ if player_pos_x in range( 170, 200) and player_pos_y in range(170, 200): print('Player is in collision RANGE!') if currentposition == m_forwards and game.key == pygame.K_RIGHT or game.key == pygame.K_d: player_pos_x = 170 speed_x = 0 elif game.key == pygame.K_a: speed_x = 5 player_pos_x -= speed_x elif game.key == pygame.K_LEFT: speed_x = 5 player_pos_x -= speed_x elif game.type == pygame.KEYUP: if game.key == pygame.K_LEFT: player_pos_x -= 0 print("Left key released") if game.key == pygame.K_RIGHT: player_pos_x += 0 print("Right key released") if game.key == pygame.K_UP: player_pos_y -= 0 print("Up key released") if game.key == pygame.K_DOWN: player_pos_y += 0 print("Down key released") if game.key == pygame.K_ESCAPE: pygame.display.set_caption(engine_title) MiPi.Main() game_running = False MiPi.DrawBoxCol(box_x, box_y) MiPi.CheckForCollision(box_x, box_y, player_pos_x) pygame.display.set_caption(game_title) # MiPi.RenderTest(player_pos_x, player_pos_y) MiPi.LoadPlayer(player_pos_x, player_pos_y) MiPi.LoadNPC(npc_pos_x, npc_pos_y) # MiPi.LoadEnemy(MiPiSettings.enemy_x, MiPiSettings.enemy_y) # The below is commented out, because UI is NOT being drawn to the game screen. # If you decide to add pygame_gui UI elements, then please use these! # mainframe.process_events(game) # mainframe.update(delta_time) sysclock.tick(mainFPS) pygame.display.flip() pygame.display.update() return MiPiSettings.player_img, MiPiSettings.sprite_path, \ MiPiSettings.npc_img, MiPiSettings.npc_path, player_pos_x
import pygame as pg import pygame_gui from pygame_gui.elements import UIWindow, UIImage pg.init() screen = pg.display.set_mode((1280, 720)) running = True manager = pygame_gui.UIManager((1280, 720)) clock = pg.time.Clock() window = UIWindow(pg.Rect(50, 50, 800, 500), manager, "test") drawingSurface = pg.Surface((300, 300)) drawingImage = UIImage(pg.Rect(0, 0, 300, 300), drawingSurface, manager, window) while running: screen.fill((50, 50, 50)) for event in pg.event.get(): manager.process_events(event) if event.type == pg.QUIT: running = False time_delta = clock.tick(60) / 1000.0 #drawingImage = UIImage(pg.Rect(0,0,300,300), drawingSurface, manager, window) manager.update(time_delta)
def __init__(self, rect: pygame.Rect, manager, container: Union[IContainerLikeInterface, None] = None, parent: Union[UIElement, None] = None, object_id: Union[str, None] = None, anchors: Union[Dict[str, str], None] = None, menu_bar_data: Dict[str, Dict[str, Union[Dict, str]]] = MENU_BAR_DATA_DICT): super().__init__(rect, manager, container, starting_height=1, layer_thickness=1, anchors=anchors) self._create_valid_ids(container, parent, object_id, 'menu_bar') self.menu_data = menu_bar_data self.bg_color = None self.border_color = None self.shape_type = 'rectangle' self.rgb_tuple = None # type: Union[Tuple[int, int, int], None] self.open_menu = None self._selected_menu = None self._close_opened_menu = False self.rebuild_from_changed_theme_data() self.container_rect = pygame.Rect( self.relative_rect.left + (self.shadow_width + self.border_width), self.relative_rect.top + (self.shadow_width + self.border_width), self.relative_rect.width - 2 * (self.shadow_width + self.border_width), self.relative_rect.height - 2 * (self.shadow_width + self.border_width)) self.menu_bar_container = UIContainer(self.container_rect, manager, starting_height=1, parent_element=self, object_id='#menu_bar_container') # menü butonları için for loop current_y_pos = 0 for menu_key, menu_item in self.menu_data.items(): if menu_key == '#icon': icon_surf = pygame.image.load( os.path.join('litevision', 'res', 'image_examples', 'icon.png')).convert_alpha() self.icon = UIImage( pygame.Rect( (0 + GUI_OFFSET_VALUE + ((48 - 32) // 2), current_y_pos + GUI_OFFSET_VALUE), (32, 32)), icon_surf, self.ui_manager, self.menu_bar_container, self, menu_key) current_y_pos += (48 + GUI_OFFSET_VALUE) continue elif menu_key == '#empty_1' or menu_key == '#empty_2': empty_surf = pygame.Surface((48, 48), pygame.SRCALPHA, masks=pygame.Color('#2F4F4F')) UIImage( pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), empty_surf, self.ui_manager, self.menu_bar_container, self, menu_key) current_y_pos += (48 + GUI_OFFSET_VALUE) continue elif menu_key == '#start_pause': sp_surf = pygame.Surface((48, 48), pygame.SRCALPHA, masks=pygame.Color('#2F4F4F')) sp_icon = pygame.image.load( os.path.join('litevision', 'res', 'image_examples', 'start_icon', 'start.png')).convert_alpha() sp_surf.blit(sp_icon, (0, 0)) self.start_button = UIImage( pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), sp_surf, self.ui_manager, self.menu_bar_container, self, '#start_pause') current_y_pos += (48 + GUI_OFFSET_VALUE) continue elif menu_key == '#rgb_button': rgb_surf = pygame.Surface((48, 48), pygame.SRCALPHA, masks=pygame.Color('#2F4F4F')) rgb_icon = pygame.image.load( os.path.join('litevision', 'res', 'image_examples', 'rgb.png')).convert_alpha() rgb_surf.blit(rgb_icon, (0, 0)) self.rgb_button = UIImage( pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), rgb_surf, self.ui_manager, self.menu_bar_container, self, '#rgb_button') current_y_pos += (48 + GUI_OFFSET_VALUE) continue UIButton(pygame.Rect((0 + GUI_OFFSET_VALUE, current_y_pos), (48, 48)), menu_item['display_name'], self.ui_manager, self.menu_bar_container, object_id=menu_key, parent_element=self) current_y_pos += (48 + GUI_OFFSET_VALUE)
class UIColourPickerDialog(UIWindow): """ A colour picker window that gives us a small range of UI tools to pick a final colour. :param rect: The size and position of the colour picker window. Includes the size of shadow, border and title bar. :param manager: The manager for the whole of the UI. :param initial_colour: The starting colour for the colour picker, defaults to black. :param window_title: The title for the window, defaults to 'Colour Picker' :param object_id: The object ID for the window, used for theming - defaults to '#colour_picker_dialog' :param visible: Whether the element is visible by default. """ def __init__(self, rect: pygame.Rect, manager: IUIManagerInterface, *, initial_colour: pygame.Color = pygame.Color(0, 0, 0, 255), window_title: str = "pygame-gui.colour_picker_title_bar", object_id: Union[ObjectID, str] = ObjectID('#colour_picker_dialog', None), visible: int = 1): super().__init__(rect, manager, window_display_title=window_title, object_id=object_id, resizable=True, visible=visible) minimum_dimensions = (390, 390) if rect.width < minimum_dimensions[ 0] or rect.height < minimum_dimensions[1]: warn_string = ("Initial size: " + str(rect.size) + " is less than minimum dimensions: " + str(minimum_dimensions)) warnings.warn(warn_string, UserWarning) self.set_minimum_dimensions(minimum_dimensions) self.current_colour = initial_colour self.cancel_button = UIButton(relative_rect=pygame.Rect( -10, -40, -1, 30), text='pygame-gui.Cancel', manager=self.ui_manager, container=self, object_id='#cancel_button', anchors={ 'left': 'right', 'right': 'right', 'top': 'bottom', 'bottom': 'bottom' }) self.ok_button = UIButton(relative_rect=pygame.Rect(-10, -40, -1, 30), text='pygame-gui.OK', manager=self.ui_manager, container=self, object_id='#ok_button', anchors={ 'left': 'right', 'right': 'right', 'top': 'bottom', 'bottom': 'bottom', 'right_target': self.cancel_button }) default_sizes = { 'element_spacing': 20, 'channel_spacing': 11, 'channel_height': 29 } current_colour_surface = pygame.surface.Surface((64, 64), flags=pygame.SRCALPHA, depth=32) current_colour_surface.fill(self.current_colour) self.current_colour_image = UIImage( pygame.Rect(default_sizes['element_spacing'], -100, 64, 64), image_surface=current_colour_surface, manager=self.ui_manager, container=self, anchors={ 'left': 'left', 'right': 'left', 'top': 'bottom', 'bottom': 'bottom' }) mini_colour_surf = pygame.surface.Surface((2, 2), flags=pygame.SRCALPHA, depth=32) mini_colour_surf.fill(pygame.Color(0, 0, 0, 255), pygame.Rect(0, 0, 1, 2)) mini_colour_surf.fill(pygame.Color(255, 255, 255, 255), pygame.Rect(1, 1, 1, 1)) hue_colour = pygame.Color(255, 255, 255, 255) hue_colour.hsva = (int(self.current_colour.hsva[0]), 100, 100, 100) mini_colour_surf.fill(hue_colour, pygame.Rect(1, 0, 1, 1)) self.sat_value_square = UIImage( pygame.Rect(default_sizes['element_spacing'], default_sizes['element_spacing'], 200, 200), image_surface=pygame.transform.smoothscale(mini_colour_surf, (200, 200)), manager=self.ui_manager, container=self) self.hue_channel = None self.sat_channel = None self.value_channel = None self.red_channel = None self.green_channel = None self.blue_channel = None self._setup_channels(default_sizes) def _setup_channels(self, default_sizes): # group up setting up the channels, possibly we can make this into a # slimmer method called with just the bits that change like names, position and value range. channel_width = (self.rect.right - self.sat_value_square.rect.right ) - (default_sizes['element_spacing'] * 2) channel_left_start = ((default_sizes['element_spacing'] * 2) + self.sat_value_square.rect.width) acc_channel_top = default_sizes['element_spacing'] self.hue_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='pygame-gui.Hue_H', channel_index=0, initial_value=int(self.current_colour.hsva[0]), value_range=(0, 360), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.sat_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='pygame-gui.Saturation_S', channel_index=0, initial_value=int(self.current_colour.hsva[1]), value_range=(0, 100), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.value_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='pygame-gui.Value_V', channel_index=2, initial_value=int(self.current_colour.hsva[2]), value_range=(0, 100), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.red_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='pygame-gui.Red_R', channel_index=0, initial_value=self.current_colour.r, value_range=(0, 255), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.green_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='pygame-gui.Green_G', channel_index=1, initial_value=self.current_colour.g, value_range=(0, 255), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.blue_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='pygame-gui.Blue_B', channel_index=2, initial_value=self.current_colour.b, value_range=(0, 255), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) def process_event(self, event: pygame.event.Event) -> bool: """ Handles events that this UI element is interested in. In this case we are responding to the colour channel elements being changed, the OK or Cancel buttons being pressed or the user clicking the mouse inside of the Saturation & Value picking square. :param event: The pygame Event to process. :return: True if event is consumed by this element and should not be passed on to other elements. """ consumed_event = super().process_event(event) if event.type == UI_BUTTON_PRESSED and event.ui_element == self.cancel_button: self.kill() if event.type == UI_BUTTON_PRESSED and event.ui_element == self.ok_button: # old event - to be removed in 0.8.0 event_data = { 'user_type': OldType(UI_COLOUR_PICKER_COLOUR_PICKED), 'colour': self.current_colour, 'ui_element': self, 'ui_object_id': self.most_specific_combined_id } pygame.event.post(pygame.event.Event(pygame.USEREVENT, event_data)) # new event event_data = { 'colour': self.current_colour, 'ui_element': self, 'ui_object_id': self.most_specific_combined_id } pygame.event.post( pygame.event.Event(UI_COLOUR_PICKER_COLOUR_PICKED, event_data)) self.kill() if event.type == UI_COLOUR_PICKER_COLOUR_CHANNEL_CHANGED: if event.ui_element in [ self.hue_channel, self.sat_channel, self.value_channel ]: self.current_colour.hsva = (self.hue_channel.current_value, self.sat_channel.current_value, self.value_channel.current_value, 100) self.changed_hsv_update_rgb() self.update_current_colour_image() self.update_saturation_value_square() elif event.ui_element in [ self.red_channel, self.green_channel, self.blue_channel ]: self.current_colour[event.channel_index] = event.value self.changed_rgb_update_hsv() self.update_current_colour_image() self.update_saturation_value_square() if event.type == pygame.MOUSEBUTTONDOWN and event.button == pygame.BUTTON_LEFT: scaled_mouse_pos = self.ui_manager.calculate_scaled_mouse_position( event.pos) if self.sat_value_square.rect.collidepoint(scaled_mouse_pos): relative_click_pos = [ scaled_mouse_pos[0] - self.sat_value_square.rect.left, scaled_mouse_pos[1] - self.sat_value_square.rect.top ] # put in range 0 - 100 and reverse y x_value = int( (relative_click_pos[0] / self.sat_value_square.rect.width) * 100) y_value = int( (relative_click_pos[1] / self.sat_value_square.rect.height) * 100) value = min(100, max(0, x_value)) saturation = min(100, max(0, 100 - y_value)) self.sat_channel.set_value(saturation) self.value_channel.set_value(value) self.current_colour.hsva = (self.hue_channel.current_value, self.sat_channel.current_value, self.value_channel.current_value, 100) self.changed_hsv_update_rgb() self.update_current_colour_image() return consumed_event def update_current_colour_image(self): """ Updates the 'current colour' image when the current colour has been changed. """ current_colour_surface = pygame.surface.Surface((64, 64), flags=pygame.SRCALPHA, depth=32) current_colour_surface.fill(self.current_colour) self.current_colour_image.set_image(current_colour_surface) def update_saturation_value_square(self): """ Updates the appearance of the big square that lets us visually pick the Saturation and Value of our current Hue. This is done by drawing a very small 4x4 pixel square with a pattern like so: [black] [hue at max saturation & value)] [black] [white] And then using the smoothscale transform to enlarge it so that the colours blend smoothly from one to the other. """ mini_colour_surf = pygame.surface.Surface((2, 2), flags=pygame.SRCALPHA, depth=32) mini_colour_surf.fill(pygame.Color(0, 0, 0, 255), pygame.Rect(0, 0, 1, 2)) mini_colour_surf.fill(pygame.Color(255, 255, 255, 255), pygame.Rect(1, 1, 1, 1)) hue_colour = pygame.Color(255, 255, 255, 255) hue_colour.hsva = (int(self.hue_channel.current_value), 100, 100, 100) mini_colour_surf.fill(hue_colour, pygame.Rect(1, 0, 1, 1)) self.sat_value_square.set_image( pygame.transform.smoothscale(mini_colour_surf, (200, 200))) def changed_hsv_update_rgb(self): """ Updates the RGB channels when we've altered the HSV ones. """ self.red_channel.set_value(self.current_colour.r) self.green_channel.set_value(self.current_colour.g) self.blue_channel.set_value(self.current_colour.b) def changed_rgb_update_hsv(self): """ Updates the HSV channels when we've altered the RGB ones. """ self.hue_channel.set_value(int(self.current_colour.hsva[0])) self.sat_channel.set_value(int(self.current_colour.hsva[1])) self.value_channel.set_value(int(self.current_colour.hsva[2]))
class UrizenGuiApp: def __init__(self): pygame.init() pygame.display.set_caption('Urizen 0.2.5') self.opt = GUIOptions() self.gen_state = GeneratorsState() if self.opt.fullscreen: self.window_surface = pygame.display.set_mode( self.opt.resolution, pygame.FULLSCREEN) else: self.window_surface = pygame.display.set_mode( self.opt.resolution, pygame.RESIZABLE) self.background_surface = None self.ui_manager = UIManager( self.opt.resolution, PackageResource('urizen.data.themes', 'gui_theme.json')) self.ui_manager.preload_fonts([{ 'name': 'fira_code', 'point_size': 10, 'style': 'bold' }, { 'name': 'fira_code', 'point_size': 10, 'style': 'regular' }, { 'name': 'fira_code', 'point_size': 10, 'style': 'italic' }, { 'name': 'fira_code', 'point_size': 14, 'style': 'italic' }, { 'name': 'fira_code', 'point_size': 14, 'style': 'bold' }]) self.panel = None self.message_window = None self.active_panel = None self.recreate_ui() self.clock = pygame.time.Clock() self.time_delta_stack = deque([]) self.button_response_timer = pygame.time.Clock() self.running = True def recreate_ui(self): self.ui_manager.set_window_resolution(self.opt.resolution) self.ui_manager.clear_and_reset() self.background_surface = pygame.Surface(self.opt.resolution) self.background_surface.fill( self.ui_manager.get_theme().get_colour('dark_bg')) self.btn_gen_explore = UIButton( pygame.Rect(5, 5, 48, 48), '', manager=self.ui_manager, container=None, object_id='#btn_gen_explore', ) self.btn_gen_search = UIButton( pygame.Rect(5, 58, 48, 48), '', manager=self.ui_manager, container=None, object_id='#btn_gen_search', tool_tip_text='Not yet implemented', ) self.btn_tiles_explore = UIButton( pygame.Rect(5, 111, 48, 48), '', manager=self.ui_manager, container=None, object_id='#btn_tiles_explore', tool_tip_text='Not yet implemented', ) self.btn_tiles_search = UIButton( pygame.Rect(5, 164, 48, 48), '', manager=self.ui_manager, container=None, object_id='#btn_tiles_search', tool_tip_text='Not yet implemented', ) self.main_area = pygame.Rect(5 + 48 + 5, 5, self.opt.W - (5 + 48 + 5 + 5), self.opt.H - (5 + 5)) self.pnl_empty = UIPanel(self.main_area, starting_layer_height=1, manager=self.ui_manager) self.construct_gen_explore() self.construct_gen_search() self.btn_gen_search.disable() self.construct_tiles_explore() self.btn_tiles_explore.disable() self.construct_tiles_search() self.btn_tiles_search.disable() if self.active_panel: self.active_panel.show() def construct_gen_explore(self): #self.gen_explore_bg_surface = pygame.Surface(self.opt.resolution) #self.gen_explore_bg_surface.fill(self.ui_manager.get_theme().get_colour('dark_bg')) self.pnl_gen_explore = UIPanel(self.main_area, starting_layer_height=0, manager=self.ui_manager) self.gen_explore_label = UILabel( pygame.Rect(5, 5, 350, 35), 'Explore generators', self.ui_manager, container=self.pnl_gen_explore, ) self.gen_list = UISelectionList( relative_rect=pygame.Rect(5, 75, 350, self.opt.H - 95), item_list=self.gen_state.get_current_gen_list(), manager=self.ui_manager, container=self.pnl_gen_explore, allow_multi_select=False, object_id='#gen_list', ) self.btn_gen_explore_save_as_png = None self.gen_explore_map_image = None self.gen_explore_image = None self.file_dialog_gen_explore_save_as_png = None self.pnl_gen_explore.hide() def construct_gen_search(self): self.pnl_gen_search = UIPanel(self.main_area, starting_layer_height=0, manager=self.ui_manager) self.pnl_gen_search.hide() def construct_tiles_explore(self): self.pnl_tiles_explore = UIPanel(self.main_area, starting_layer_height=0, manager=self.ui_manager) self.pnl_tiles_explore.hide() def construct_tiles_search(self): self.pnl_tiles_search = UIPanel(self.main_area, starting_layer_height=0, manager=self.ui_manager) self.pnl_tiles_search.hide() def process_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.ui_manager.process_events(event) if event.type == pygame.VIDEORESIZE: self.opt.W = event.w self.opt.H = event.h self.opt.resolution = (event.w, event.h) self.recreate_ui() if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == self.btn_gen_explore: self.pnl_gen_explore.show() self.pnl_gen_search.hide() self.pnl_tiles_explore.hide() self.pnl_tiles_search.hide() self.active_panel = self.pnl_gen_explore elif event.ui_element == self.btn_gen_search: self.pnl_gen_explore.hide() self.pnl_gen_search.show() self.pnl_tiles_explore.hide() self.pnl_tiles_search.hide() self.active_panel = self.btn_gen_search elif event.ui_element == self.btn_tiles_explore: self.pnl_gen_explore.hide() self.pnl_gen_search.hide() self.pnl_tiles_explore.show() self.pnl_tiles_search.hide() self.active_panel = self.btn_tiles_explore elif event.ui_element == self.btn_tiles_search: self.pnl_gen_explore.hide() self.pnl_gen_search.hide() self.pnl_tiles_explore.hide() self.pnl_tiles_search.show() self.active_panel = self.pnl_tiles_search elif event.ui_element == self.btn_gen_explore_save_as_png: self.file_dialog_gen_explore_save_as_png = UIFileDialog( pygame.Rect(self.opt.W // 4, self.opt.H // 4, self.opt.W // 2, self.opt.H // 2), self.ui_manager, window_title='Save as PNG', initial_file_path='map.png', object_id='#file_dialog_gen_explore_save_as_png') if event.user_type == pygame_gui.UI_FILE_DIALOG_PATH_PICKED: if event.ui_element == self.file_dialog_gen_explore_save_as_png: self.gen_explore_image.save(event.text) if event.user_type == pygame_gui.UI_WINDOW_CLOSE: if event.ui_element == self.file_dialog_gen_explore_save_as_png: self.file_dialog_gen_explore_save_as_png = None if event.user_type == pygame_gui.UI_SELECTION_LIST_DOUBLE_CLICKED_SELECTION: if event.ui_element == self.gen_list: if self.gen_state.is_generator(event.text): M = self.gen_state.get_generator(event.text)() surface_w = self.opt.W - 435 surface_h = self.opt.H - 95 self.gen_explore_image = construct_bounded_map_image( M, surface_w, surface_h) image_bytes = self.gen_explore_image.tobytes() im_w, im_h = self.gen_explore_image.size shift_x = (surface_w - im_w) // 2 shift_y = (surface_h - im_h) // 2 if not self.gen_explore_map_image: self.gen_explore_map_image = UIImage( relative_rect=pygame.Rect( 360 + shift_x, 75 + shift_y, im_w, im_h), image_surface=pygame.image.fromstring( image_bytes, self.gen_explore_image.size, self.gen_explore_image.mode), manager=self.ui_manager, container=self.pnl_gen_explore, object_id='#gen_explore_map_image', ) else: self.gen_explore_map_image.set_relative_position( pygame.Rect(360 + shift_x, 75 + shift_y, im_w, im_h)) self.gen_explore_map_image.image = pygame.image.fromstring( image_bytes, self.gen_explore_image.size, self.gen_explore_image.mode) if not self.btn_gen_explore_save_as_png: self.btn_gen_explore_save_as_png = UIButton( pygame.Rect(self.opt.W - 265, 5, 190, 50), 'Save as PNG', manager=self.ui_manager, container=self.pnl_gen_explore, object_id='#btn_gen_explore_save_as_png', starting_height=10, ) else: self.gen_state.change_state(event.text) self.gen_list.set_item_list( self.gen_state.get_current_gen_list()) def run(self): while self.running: time_delta = self.clock.tick() / 1000.0 self.time_delta_stack.append(time_delta) if len(self.time_delta_stack) > 2000: self.time_delta_stack.popleft() # check for input self.process_events() # respond to input self.ui_manager.update(time_delta) # draw graphics self.window_surface.blit(self.background_surface, (0, 0)) self.ui_manager.draw_ui(self.window_surface) pygame.display.update()
def build_gui(self): super().build_gui() panel_rect = Rect( 0, 0, 500, self.display.get_rect().height - (get_param('panel_padding') * 2)) panel_rect.centerx = self.display.get_rect().centerx panel_rect.y = get_param('panel_padding') self.ui_elements['panel'] = UIPanel(panel_rect, 1, self.gui) # all other elements are relative scene_label_rect = Rect(0, 0, 400, get_param('element_height')) scene_label_rect.y = get_param('element_padding') scene_label_rect.centerx = panel_rect.w // 2 # midpoint of the panel self.ui_elements['scene_label'] = UILabel(scene_label_rect, "Generate Random Map", self.gui, self.ui_elements['panel']) # map size label_rect = Rect(0, 0, 150, get_param('element_height')) label_rect.y += scene_label_rect.bottom + get_param('element_padding') dd_rect = Rect(0, 0, 250, get_param('element_height')) dd_rect.y = label_rect.y label_rect.centerx = 125 dd_rect.centerx = 325 self.ui_elements['d_size_label'] = UILabel(label_rect, "Map Size", self.gui, self.ui_elements['panel']) self.ui_elements['dd_map_size'] = UIDropDownMenu( ['64', '128', '256'], '64', dd_rect, self.gui, self.ui_elements['panel']) # Seed label_rect.y += get_param('element_height') + get_param( 'element_padding') ip_rect = Rect(0, 0, 180, get_param('element_height')) ip_rect.centerx = (panel_rect.w // 2) + 30 ip_rect.y = label_rect.y s_btn_rect = Rect(0, 0, 60, get_param('element_height')) s_btn_rect.x = ip_rect.right + get_param('element_padding') s_btn_rect.y = ip_rect.y self.ui_elements['seed_label'] = UILabel(label_rect, 'Map Seed', self.gui, self.ui_elements['panel']) self.ui_elements['input_seed'] = UITextEntryLine( ip_rect, self.gui, self.ui_elements['panel']) self.ui_elements['btn_rnd_seed'] = UIButton(s_btn_rect, 'Random', self.gui, self.ui_elements['panel']) # I want to add two sliders, 1 for mountains and 1 for water, these would be used to control the upper # and lower limits of the height mapping. h_sl_ops = (0, 100) h_sl_sel = 50 label_rect.y += get_param('element_height') + get_param( 'element_padding') h_sl_rect = Rect(0, 0, 200, get_param('element_height')) h_sl_rect.centerx = (panel_rect.w // 2) + get_param('element_padding') + 30 h_sl_rect.y = label_rect.y self.ui_elements['hsl_grass'] = UILabel(label_rect, 'Grass', self.gui, self.ui_elements['panel']) self.ui_elements['hs_grass'] = UIHorizontalSlider( h_sl_rect, h_sl_sel, h_sl_ops, self.gui, self.ui_elements['panel']) label_rect.y += get_param('element_height') + get_param( 'element_padding') h_sl_rect.y = label_rect.y self.ui_elements['hsl_water'] = UILabel(label_rect, 'Water', self.gui, self.ui_elements['panel']) self.ui_elements['hs_water'] = UIHorizontalSlider( h_sl_rect, h_sl_sel, h_sl_ops, self.gui, self.ui_elements['panel']) label_rect.y += get_param('element_height') + get_param( 'element_padding') h_sl_rect.y = label_rect.y self.ui_elements['hsl_mountain'] = UILabel(label_rect, 'Mountain', self.gui, self.ui_elements['panel']) self.ui_elements['hs_mountain'] = UIHorizontalSlider( h_sl_rect, h_sl_sel, h_sl_ops, self.gui, self.ui_elements['panel']) # buttons button_rect = Rect(0, 0, 200, get_param('element_height')) button_rect.centerx = panel_rect.w // 2 button_rect.y = label_rect.bottom + get_param('element_padding') self.ui_elements['btn_preview'] = UIButton(button_rect, "Generate Preview", self.gui, self.ui_elements['panel']) button_rect.w = 200 button_rect.y += get_param('element_height') + get_param( 'element_padding') button_rect.centerx = (panel_rect.w // 2) - 100 self.ui_elements['btn_back'] = UIButton(button_rect, "Back", self.gui, self.ui_elements['panel']) # the apply button always starts off disabled button_rect.centerx = (panel_rect.w // 2) + 100 self.ui_elements['btn_next'] = UIButton(button_rect, "Next", self.gui, self.ui_elements['panel']) pv_rect = Rect(0, 0, 300, 300) pv_rect.centerx = panel_rect.w // 2 pv_rect.y = button_rect.bottom + get_param('element_padding') self.ui_elements['pv_image'] = UIImage(pv_rect, self.pv_img, self.gui, self.ui_elements['panel'])
def __init__(self, rect: pygame.Rect, manager: IUIManagerInterface, *, initial_colour: pygame.Color = pygame.Color(0, 0, 0, 255), window_title: str = "Colour Picker", object_id: str = '#colour_picker_dialog'): super().__init__(rect, manager, window_display_title=window_title, object_id=object_id, resizable=True) minimum_dimensions = (390, 390) if rect.width < minimum_dimensions[ 0] or rect.height < minimum_dimensions[1]: warn_string = ("Initial size: " + str(rect.size) + " is less than minimum dimensions: " + str(minimum_dimensions)) warnings.warn(warn_string, UserWarning) self.set_minimum_dimensions(minimum_dimensions) self.current_colour = initial_colour self.ok_button = UIButton(relative_rect=pygame.Rect( -220, -40, 100, 30), text='OK', manager=self.ui_manager, container=self, object_id='#ok_button', anchors={ 'left': 'right', 'right': 'right', 'top': 'bottom', 'bottom': 'bottom' }) self.cancel_button = UIButton(relative_rect=pygame.Rect( -110, -40, 100, 30), text='Cancel', manager=self.ui_manager, container=self, object_id='#cancel_button', anchors={ 'left': 'right', 'right': 'right', 'top': 'bottom', 'bottom': 'bottom' }) default_sizes = { 'element_spacing': 20, 'channel_spacing': 11, 'channel_height': 29 } current_colour_surface = pygame.Surface((64, 64)) current_colour_surface.fill(self.current_colour) self.current_colour_image = UIImage( pygame.Rect(default_sizes['element_spacing'], -100, 64, 64), image_surface=current_colour_surface, manager=self.ui_manager, container=self, anchors={ 'left': 'left', 'right': 'left', 'top': 'bottom', 'bottom': 'bottom' }) mini_colour_surf = pygame.Surface((2, 2)) mini_colour_surf.fill(pygame.Color(0, 0, 0, 255), pygame.Rect(0, 0, 1, 2)) mini_colour_surf.fill(pygame.Color(255, 255, 255, 255), pygame.Rect(1, 1, 1, 1)) hue_colour = pygame.Color(255, 255, 255, 255) hue_colour.hsva = (int(self.current_colour.hsva[0]), 100, 100, 100) mini_colour_surf.fill(hue_colour, pygame.Rect(1, 0, 1, 1)) self.sat_value_square = UIImage( pygame.Rect(default_sizes['element_spacing'], default_sizes['element_spacing'], 200, 200), image_surface=pygame.transform.smoothscale(mini_colour_surf, (200, 200)), manager=self.ui_manager, container=self) channel_width = (self.rect.right - self.sat_value_square.rect.right ) - (default_sizes['element_spacing'] * 2) channel_left_start = ((default_sizes['element_spacing'] * 2) + self.sat_value_square.rect.width) acc_channel_top = default_sizes['element_spacing'] self.hue_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='H:', channel_index=0, initial_value=int(self.current_colour.hsva[0]), value_range=(0, 360), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.sat_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='S:', channel_index=0, initial_value=int(self.current_colour.hsva[1]), value_range=(0, 100), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.value_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='V:', channel_index=2, initial_value=int(self.current_colour.hsva[2]), value_range=(0, 100), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.red_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='R:', channel_index=0, initial_value=self.current_colour.r, value_range=(0, 255), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.green_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='G:', channel_index=1, initial_value=self.current_colour.g, value_range=(0, 255), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' }) acc_channel_top += (default_sizes['channel_height'] + default_sizes['channel_spacing']) self.blue_channel = UIColourChannelEditor( pygame.Rect(channel_left_start, acc_channel_top, channel_width, default_sizes['channel_height']), manager=self.ui_manager, container=self, name='B:', channel_index=2, initial_value=self.current_colour.b, value_range=(0, 255), anchors={ 'left': 'left', 'right': 'right', 'top': 'top', 'bottom': 'top' })
def run(self): while self.is_running: time_delta = self.clock.tick(60) / 1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: self.is_running = False if (event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_BUTTON_PRESSED and event.ui_element == self.load_button): self.file_dialog = UIFileDialog( pygame.Rect(160, 50, 440, 500), self.ui_manager, window_title='Load Image...', initial_file_path='data/images/', allow_existing_files_only=True) self.load_button.disable() if (event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_FILE_DIALOG_PATH_PICKED): if self.display_loaded_image is not None: self.display_loaded_image.kill() try: image_path = create_resource_path(event.text) loaded_image = pygame.image.load( image_path).convert_alpha() image_rect = loaded_image.get_rect() aspect_ratio = image_rect.width / image_rect.height need_to_scale = False if image_rect.width > self.max_image_display_dimensions[ 0]: image_rect.width = self.max_image_display_dimensions[ 0] image_rect.height = int(image_rect.width / aspect_ratio) need_to_scale = True if image_rect.height > self.max_image_display_dimensions[ 1]: image_rect.height = self.max_image_display_dimensions[ 1] image_rect.width = int(image_rect.height * aspect_ratio) need_to_scale = True if need_to_scale: loaded_image = pygame.transform.smoothscale( loaded_image, image_rect.size) image_rect.center = (400, 300) self.display_loaded_image = UIImage( relative_rect=image_rect, image_surface=loaded_image, manager=self.ui_manager) except pygame.error: pass if (event.type == pygame.USEREVENT and event.user_type == pygame_gui.UI_WINDOW_CLOSE and event.ui_element == self.file_dialog): self.load_button.enable() self.file_dialog = None self.ui_manager.process_events(event) self.ui_manager.update(time_delta) self.window_surface.blit(self.background, (0, 0)) self.ui_manager.draw_ui(self.window_surface) pygame.display.update()
def __init__(self, rect, ui_manager): super().__init__(rect, ui_manager, window_display_title='Everything Container', object_id='#everything_window', resizable=True) self.test_slider = UIHorizontalSlider(pygame.Rect( (int(self.rect.width / 2), int(self.rect.height * 0.70)), (240, 25)), 50.0, (0.0, 100.0), self.ui_manager, container=self) self.slider_label = UILabel( pygame.Rect( (int(self.rect.width / 2) + 250, int(self.rect.height * 0.70)), (27, 25)), str(int(self.test_slider.get_current_value())), self.ui_manager, container=self) self.test_text_entry = UITextEntryLine(pygame.Rect( (int(self.rect.width / 2), int(self.rect.height * 0.50)), (200, -1)), self.ui_manager, container=self) self.test_text_entry.set_forbidden_characters('numbers') current_resolution_string = 'Item 1' self.test_drop_down_menu = UIDropDownMenu( [ 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10', 'Item 11', 'Item 12', 'Item 13', 'Item 14', 'Item 15', 'Item 16', 'Item 17', 'Item 18', 'Item 19', 'Item 20', 'Item 21', 'Item 22', 'Item 23', 'Item 24', 'Item 25', 'Item 26', 'Item 27', 'Item 28', 'Item 29', 'Item 30' ], current_resolution_string, pygame.Rect( (int(self.rect.width / 2), int(self.rect.height * 0.3)), (200, 25)), self.ui_manager, container=self) self.health_bar = UIScreenSpaceHealthBar(pygame.Rect( (int(self.rect.width / 9), int(self.rect.height * 0.7)), (200, 20)), self.ui_manager, container=self) loaded_test_image = pygame.image.load( 'data/images/splat.png').convert_alpha() self.test_image = UIImage(pygame.Rect( (int(self.rect.width / 9), int(self.rect.height * 0.3)), loaded_test_image.get_rect().size), loaded_test_image, self.ui_manager, container=self)
class Game: def __init__(self, session): self.manager = UIManager((800, 600), 'themes/game.json') image = pygame.image.load('assets/background.png') self.background = UIImage(relative_rect=pygame.Rect(0, 0, 800, 600), manager=self.manager, image_surface=image) self.session = session self.allPlayers = pygame.sprite.Group() self.player = Perso(self, self.session) self.allPlayers.add(self.player) self.pressed = {} self.allEnemy = pygame.sprite.Group() self.addScore = 100 self.score = 0 self.level = Niveau(self, self.score) self.panelTop = UIPanel(relative_rect=pygame.Rect(0, 0, 800, 20), starting_layer_height=2, manager=self.manager, object_id="#panel-top") self.labelHealthTitle = UILabel(relative_rect=pygame.Rect( 0, 0, 50, 20), text="Vie :", manager=self.manager, object_id="#label-score", container=self.panelTop) self.labelHealth = UILabel(relative_rect=pygame.Rect(30, 0, 50, 20), text=str(self.player.health), manager=self.manager, object_id="#label-score", container=self.panelTop) self.labelAsset = UILabel(relative_rect=pygame.Rect( 800 - 100, 0, 50, 20), text=str(self.level.assetIsActive[2]), manager=self.manager, object_id="#label-score", container=self.panelTop) self.labelScore = UILabel(relative_rect=pygame.Rect( 0, 600 - 50, 200, 50), text=str(self.score), manager=self.manager, object_id="#label-score") self.playerImage = UIImage(relative_rect=pygame.Rect( (self.player.rect.x, self.player.rect.y), (50, 50)), manager=self.manager, image_surface=self.player.image) self.panel = UIPanel(relative_rect=pygame.Rect((0, 0), (0, 0)), starting_layer_height=3, manager=self.manager, object_id="#panel-game-over") self.labelGameOver = UILabel(relative_rect=pygame.Rect( 400 - 100, 300 - 50, 200, 50), text="Game Over", manager=self.manager, object_id="#label-game-over", container=self.panel) self.buttonMenu = UIButton(relative_rect=pygame.Rect( 400 - 100, 300 + 50, 200, 50), text='Quitter', manager=self.manager, container=self.panel) self.buttonParty = UIButton(relative_rect=pygame.Rect( (400 - 100, 300 + 50 + 80), (200, 50)), text='Recommencer', manager=self.manager, container=self.panel) self.panelPause = UIPanel(relative_rect=pygame.Rect((0, 0), (0, 0)), starting_layer_height=3, manager=self.manager, object_id="#panel-game-over") self.labelPause = UILabel(relative_rect=pygame.Rect( 400 - 100, 300 - 50, 200, 50), text="Pause", manager=self.manager, object_id="#label-game-over", container=self.panelPause) self.buttonSave = UIButton(relative_rect=pygame.Rect( 400 - 100, 300 + 50, 200, 50), text='Sauvegarder et quitter', manager=self.manager, container=self.panelPause) self.buttonQuit = UIButton(relative_rect=pygame.Rect( (400 - 100, 300 + 50 + 80), (200, 50)), text='Quitter', manager=self.manager, container=self.panelPause) self.panelAsset = UIPanel(relative_rect=pygame.Rect((0, 0), (0, 0)), starting_layer_height=3, manager=self.manager, object_id="#panel-game-over") self.labelEquipment = UILabel(relative_rect=pygame.Rect( 400 - 100, 50, 200, 50), text="Pause", manager=self.manager, object_id="#label-game-over", container=self.panelAsset) self.button1 = UIButton(relative_rect=pygame.Rect( 400 - 100, 50 + 50, 200, 50), text="Double l'attaque 10C", manager=self.manager, container=self.panelAsset) self.button2 = UIButton(relative_rect=pygame.Rect( (400 - 100, 120 + 50), (200, 50)), text='3 Missiles 100C', manager=self.manager, container=self.panelAsset) self.button3 = UIButton(relative_rect=pygame.Rect( (400 - 100, 190 + 50), (200, 50)), text='Double Score 20C', manager=self.manager, container=self.panelAsset) self.button4 = UIButton(relative_rect=pygame.Rect( (400 - 100, 260 + 50), (200, 50)), text="Temps d'apparition 50C", manager=self.manager, container=self.panelAsset) self.labelCredit = UILabel(relative_rect=pygame.Rect( 400 - 100, 330 + 50, 200, 50), text=str(self.player.credit), manager=self.manager, object_id="#label-game-over", container=self.panelAsset) self.pause = True def menuGameOver(self): self.panel.set_dimensions((800, 600)) def setLabelHealth(self): self.labelHealth.set_text(str(self.player.health)) def setLabelScore(self): self.labelScore.set_text(str(self.score)) def setLabelAsset(self): self.labelAsset.set_text(str(self.level.assetIsActive[2])) def setLabelCredit(self): self.player.credit += 1 self.labelCredit.set_text(str(self.player.credit)) def getManager(self): return self.manager def updatePosPlayer(self): self.playerImage.set_relative_position( (self.player.rect.x, self.player.rect.y)) def getPause(self): return self.pause def getEvent(self, event): if not self.player.isDead(): if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == self.buttonQuit: pygame.quit() elif event.ui_element == self.buttonSave: self.session.setCredit(self.player.credit) self.session.setScore(self.score) pygame.quit() elif event.ui_element == self.button1: if self.player.credit >= 10 and self.level.assetIsActive[ 0] == False: self.player.credit -= 10 self.player.getSurprise("damage") self.panelAsset.set_dimensions((0, 0)) self.pause = True elif event.ui_element == self.button2: if self.player.credit >= 100 and self.level.assetIsActive[ 0] == False: self.player.credit -= 100 self.player.getSurprise("attack") self.panelAsset.set_dimensions((0, 0)) self.pause = True elif event.ui_element == self.button3: if self.player.credit >= 20 and self.level.assetIsActive[ 0] == False: self.player.credit -= 20 self.player.getSurprise("score") self.panelAsset.set_dimensions((0, 0)) self.pause = True elif event.ui_element == self.button4: if self.player.credit >= 50 and self.level.assetIsActive[ 0] == False: self.player.credit -= 50 self.player.getSurprise("reload") self.panelAsset.set_dimensions((0, 0)) self.pause = True if event.type == KEYDOWN: if event.key == pygame.K_ESCAPE: if self.pause: self.panelPause.set_dimensions((800, 600)) self.pause = False else: self.panelPause.set_dimensions((0, 0)) self.pause = True return self.pause if event.key == pygame.K_RETURN: if self.pause: self.panelAsset.set_dimensions((800, 600)) self.pause = False else: self.panelAsset.set_dimensions((0, 0)) self.pause = True return self.pause if event.key == pygame.K_SPACE: self.player.attack(self.manager) self.pressed[event.key] = True elif event.type == KEYUP: self.pressed[event.key] = False return None else: if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == self.buttonParty: return "restart" elif event.ui_element == self.buttonMenu: pygame.quit() def updatePosEnemy(self, enemy, x, y): enemy.ennemyImage.set_relative_position((x, y)) def spawnEnemy(self, health, x, asset): enemy = Enemy(health, self.manager, x, self, asset) self.updatePosEnemy(enemy, enemy.rect.x, enemy.rect.y) self.allEnemy.add(enemy) def checkColision(self, sprite, group): return pygame.sprite.spritecollide(sprite, group, False, pygame.sprite.collide_mask) def run(self): self.level.generate() self.level.setScore(self.score)
def __init__(self, rect: pygame.Rect, manager: IUIManagerInterface, *, initial_colour: pygame.Color = pygame.Color(0, 0, 0, 255), window_title: str = "pygame-gui.colour_picker_title_bar", object_id: Union[ObjectID, str] = ObjectID('#colour_picker_dialog', None), visible: int = 1): super().__init__(rect, manager, window_display_title=window_title, object_id=object_id, resizable=True, visible=visible) minimum_dimensions = (390, 390) if rect.width < minimum_dimensions[ 0] or rect.height < minimum_dimensions[1]: warn_string = ("Initial size: " + str(rect.size) + " is less than minimum dimensions: " + str(minimum_dimensions)) warnings.warn(warn_string, UserWarning) self.set_minimum_dimensions(minimum_dimensions) self.current_colour = initial_colour self.cancel_button = UIButton(relative_rect=pygame.Rect( -10, -40, -1, 30), text='pygame-gui.Cancel', manager=self.ui_manager, container=self, object_id='#cancel_button', anchors={ 'left': 'right', 'right': 'right', 'top': 'bottom', 'bottom': 'bottom' }) self.ok_button = UIButton(relative_rect=pygame.Rect(-10, -40, -1, 30), text='pygame-gui.OK', manager=self.ui_manager, container=self, object_id='#ok_button', anchors={ 'left': 'right', 'right': 'right', 'top': 'bottom', 'bottom': 'bottom', 'right_target': self.cancel_button }) default_sizes = { 'element_spacing': 20, 'channel_spacing': 11, 'channel_height': 29 } current_colour_surface = pygame.surface.Surface((64, 64), flags=pygame.SRCALPHA, depth=32) current_colour_surface.fill(self.current_colour) self.current_colour_image = UIImage( pygame.Rect(default_sizes['element_spacing'], -100, 64, 64), image_surface=current_colour_surface, manager=self.ui_manager, container=self, anchors={ 'left': 'left', 'right': 'left', 'top': 'bottom', 'bottom': 'bottom' }) mini_colour_surf = pygame.surface.Surface((2, 2), flags=pygame.SRCALPHA, depth=32) mini_colour_surf.fill(pygame.Color(0, 0, 0, 255), pygame.Rect(0, 0, 1, 2)) mini_colour_surf.fill(pygame.Color(255, 255, 255, 255), pygame.Rect(1, 1, 1, 1)) hue_colour = pygame.Color(255, 255, 255, 255) hue_colour.hsva = (int(self.current_colour.hsva[0]), 100, 100, 100) mini_colour_surf.fill(hue_colour, pygame.Rect(1, 0, 1, 1)) self.sat_value_square = UIImage( pygame.Rect(default_sizes['element_spacing'], default_sizes['element_spacing'], 200, 200), image_surface=pygame.transform.smoothscale(mini_colour_surf, (200, 200)), manager=self.ui_manager, container=self) self.hue_channel = None self.sat_channel = None self.value_channel = None self.red_channel = None self.green_channel = None self.blue_channel = None self._setup_channels(default_sizes)
def __init__(self, session): self.manager = UIManager((800, 600), 'themes/game.json') image = pygame.image.load('assets/background.png') self.background = UIImage(relative_rect=pygame.Rect(0, 0, 800, 600), manager=self.manager, image_surface=image) self.session = session self.allPlayers = pygame.sprite.Group() self.player = Perso(self, self.session) self.allPlayers.add(self.player) self.pressed = {} self.allEnemy = pygame.sprite.Group() self.addScore = 100 self.score = 0 self.level = Niveau(self, self.score) self.panelTop = UIPanel(relative_rect=pygame.Rect(0, 0, 800, 20), starting_layer_height=2, manager=self.manager, object_id="#panel-top") self.labelHealthTitle = UILabel(relative_rect=pygame.Rect( 0, 0, 50, 20), text="Vie :", manager=self.manager, object_id="#label-score", container=self.panelTop) self.labelHealth = UILabel(relative_rect=pygame.Rect(30, 0, 50, 20), text=str(self.player.health), manager=self.manager, object_id="#label-score", container=self.panelTop) self.labelAsset = UILabel(relative_rect=pygame.Rect( 800 - 100, 0, 50, 20), text=str(self.level.assetIsActive[2]), manager=self.manager, object_id="#label-score", container=self.panelTop) self.labelScore = UILabel(relative_rect=pygame.Rect( 0, 600 - 50, 200, 50), text=str(self.score), manager=self.manager, object_id="#label-score") self.playerImage = UIImage(relative_rect=pygame.Rect( (self.player.rect.x, self.player.rect.y), (50, 50)), manager=self.manager, image_surface=self.player.image) self.panel = UIPanel(relative_rect=pygame.Rect((0, 0), (0, 0)), starting_layer_height=3, manager=self.manager, object_id="#panel-game-over") self.labelGameOver = UILabel(relative_rect=pygame.Rect( 400 - 100, 300 - 50, 200, 50), text="Game Over", manager=self.manager, object_id="#label-game-over", container=self.panel) self.buttonMenu = UIButton(relative_rect=pygame.Rect( 400 - 100, 300 + 50, 200, 50), text='Quitter', manager=self.manager, container=self.panel) self.buttonParty = UIButton(relative_rect=pygame.Rect( (400 - 100, 300 + 50 + 80), (200, 50)), text='Recommencer', manager=self.manager, container=self.panel) self.panelPause = UIPanel(relative_rect=pygame.Rect((0, 0), (0, 0)), starting_layer_height=3, manager=self.manager, object_id="#panel-game-over") self.labelPause = UILabel(relative_rect=pygame.Rect( 400 - 100, 300 - 50, 200, 50), text="Pause", manager=self.manager, object_id="#label-game-over", container=self.panelPause) self.buttonSave = UIButton(relative_rect=pygame.Rect( 400 - 100, 300 + 50, 200, 50), text='Sauvegarder et quitter', manager=self.manager, container=self.panelPause) self.buttonQuit = UIButton(relative_rect=pygame.Rect( (400 - 100, 300 + 50 + 80), (200, 50)), text='Quitter', manager=self.manager, container=self.panelPause) self.panelAsset = UIPanel(relative_rect=pygame.Rect((0, 0), (0, 0)), starting_layer_height=3, manager=self.manager, object_id="#panel-game-over") self.labelEquipment = UILabel(relative_rect=pygame.Rect( 400 - 100, 50, 200, 50), text="Pause", manager=self.manager, object_id="#label-game-over", container=self.panelAsset) self.button1 = UIButton(relative_rect=pygame.Rect( 400 - 100, 50 + 50, 200, 50), text="Double l'attaque 10C", manager=self.manager, container=self.panelAsset) self.button2 = UIButton(relative_rect=pygame.Rect( (400 - 100, 120 + 50), (200, 50)), text='3 Missiles 100C', manager=self.manager, container=self.panelAsset) self.button3 = UIButton(relative_rect=pygame.Rect( (400 - 100, 190 + 50), (200, 50)), text='Double Score 20C', manager=self.manager, container=self.panelAsset) self.button4 = UIButton(relative_rect=pygame.Rect( (400 - 100, 260 + 50), (200, 50)), text="Temps d'apparition 50C", manager=self.manager, container=self.panelAsset) self.labelCredit = UILabel(relative_rect=pygame.Rect( 400 - 100, 330 + 50, 200, 50), text=str(self.player.credit), manager=self.manager, object_id="#label-game-over", container=self.panelAsset) self.pause = True