From a74151196b36ec82c12f24bd78d640f9f9fd0272 Mon Sep 17 00:00:00 2001 From: Ben Ryder Date: Mon, 20 Sep 2021 20:40:13 +0100 Subject: [PATCH 1/3] GH-29: Fixing pylint issues in top level files. --- constants.py | 70 ++++++++++++++++++++++--------------------- main.py | 32 +++++++++++++------- paths.py | 18 +++++++++++ project/game/model.py | 25 ---------------- project/menus/menu.py | 2 +- 5 files changed, 76 insertions(+), 71 deletions(-) diff --git a/constants.py b/constants.py index 705a00f..868b1eb 100644 --- a/constants.py +++ b/constants.py @@ -1,17 +1,33 @@ -import sys -import subprocess -import paths +""" +A file to export constants used throughout the application. + +This module exports: + VERSION - The game version of the current code. + DISPLAY_NAME - The window title. + DISPLAY_SIZE - The fixed size of the display. + + MAP_SIZE - The x by y size of the game maps, in tiles. + TILE_WIDTH - The width of game tiles in px. + TILE_HEIGHT - The height of game tiles in px. + + MAP_WIDTH - The total map width, worked out from the MAP_SIZE and TILE_WIDTH. + MAP_HEIGHT - The total map height, worked out from the MAP_SIZE and TILE_WIDTH. + MAP_PADDING - An arbitrary value for padding around the map. + + GAME_RECT - The rect value ([x, y, width, height]) of the map, including padding. + ORIGIN - The exact top point of the isometric map. + + COLOURS - A dictionary of colours used throughout the application. + FONTS - A dictionary of font information used in teh application. -# Dev Version Text (Tries for git version, if cant get it, revert to version saved here) -try: - if sys.version_info[0] < 3.5: - version = subprocess.check_output(["git", "describe", "--tags"]).strip() - else: - version = subprocess.run(["git", "describe", "--tags"], stdout=subprocess.PIPE).stdout.decode("utf-8") - assert version != "" -except Exception: # seems to be so dependent on system and versions, easier to do a catch all - version = "v1.1.1" # git not installed, or older lib version, so revert to hardcoded version + UNIT_SPECS - The data for each unit in the game including health, attach, defense etc. + LEVELS - A matrix that manages how city level increases work. +""" +import paths + +# Application version. Should always match repository tag. +VERSION = "v1.1.1" # configuration for pygame.display DISPLAY_NAME = "Conqueror of Empires" @@ -27,11 +43,11 @@ MAP_HEIGHT = TILE_HEIGHT*MAP_SIZE[1] MAP_PADDING = 20 # space between map and edge of game surface. -width = MAP_WIDTH + MAP_PADDING*2 -height = MAP_HEIGHT + TILE_HEIGHT + MAP_PADDING*2 -x = -MAP_WIDTH/2 -y = -MAP_PADDING -GAME_RECT = [x, y, width, height] # x, y change with scroll anyway +WIDTH = MAP_WIDTH + MAP_PADDING * 2 +HEIGHT = MAP_HEIGHT + TILE_HEIGHT + MAP_PADDING * 2 +X = -MAP_WIDTH / 2 +Y = -MAP_PADDING +GAME_RECT = [X, Y, WIDTH, HEIGHT] # x, y change with scroll anyway ORIGIN = [GAME_RECT[2]/2 - TILE_HEIGHT + MAP_PADDING, MAP_PADDING] # top map point @@ -59,18 +75,6 @@ "small": 12}, "colour": COLOURS["white"]} -# Game Data -TILE_DATA = { - "s": [0, 0, 0], - "w": [0, 0, 0], - "g": [0, 0, 0], - "f": [100, 20, 5], - "m": [10, 100, 20], - "o": [10, 100, 50], - "c": [100, 50, 25], # default of settlement store (level 1) -} - - UNIT_SPECS = { "scout": { "max_health": 10, @@ -124,9 +128,8 @@ }, } -# each item is level, each item in level is sub-level. -# item: len() = number of sub-levels to next level, value is ap cost to reach sub level/ len() = 0 means max level -# city level starts at 1, to reference level must do city_level - 1. +# Levels Matrix +# each list item represents a level, each item within a level list represents a sub-level. LEVELS = [ [2, 2, 2], # 1 to 2 [2, 2, 2, 2], # 2 to 3 @@ -135,6 +138,5 @@ [], # 5 is max ] - # Cleanup unneeded to not pollute namespace. -del x, y, width, height, MAP_PADDING +del X, Y, WIDTH, HEIGHT, MAP_PADDING diff --git a/main.py b/main.py index 0453ffe..7af1c76 100755 --- a/main.py +++ b/main.py @@ -1,20 +1,30 @@ #!/usr/bin/env python3 +""" +The main entry point for the application. +""" + import logging -logging.basicConfig(filename='main.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s') +from project import control -try: +# Setting up logging +logging.basicConfig( + filename='main.log', + filemode='w', + format='%(name)s - %(levelname)s - %(message)s' +) - import project.control as control - def main(): - controller = control.ApplicationController() - controller.run() +def main(): + """ The main function to instantiate and run the application controller. """ + controller = control.ApplicationController() + controller.run() - if __name__ == "__main__": - main() -except Exception as e: - logging.exception("caught at main") - raise e # personal choice, still want to see error in IDE +if __name__ == "__main__": + try: + main() + except Exception as error: + logging.exception("caught at main") + raise error # personal choice, still want to see error in IDE diff --git a/paths.py b/paths.py index a22a4c8..4b4ffc1 100644 --- a/paths.py +++ b/paths.py @@ -1,3 +1,21 @@ +""" +A constants file to export file paths used in the application. +This includes data and asset paths. + +This module exports: + dataPath - The base folder that stores game data such as maps, game saves etc. + assetPath - The base folder that stores game assets. + gamePath - The folder that stores saved games. + mapPath - The folder that stores map files. + fontPath - The folder that stores font files used in the application. + imagePath - The base path that stores image assets used in the application. + tilePath - The folder that stores map tile images. + unitPath - The folder that stores unit images. + uiPath - The folder that stores general images related to the application UI. + uiMenuPath - The folder that stores UI images specifically for the menus. + uiGamePath - The folder that stores UI images specifically for use in the game. +""" + import os dataPath = os.getcwd() + os.sep + "data" + os.sep diff --git a/project/game/model.py b/project/game/model.py index dc6457d..f93d949 100644 --- a/project/game/model.py +++ b/project/game/model.py @@ -289,7 +289,6 @@ class Tile: def __init__(self, save_data): self.type = save_data["type"] self.position = save_data["position"] - # self.wood, self.stone, self.metal = constants.TILE_DATA[tile_type] def get_save_data(self): return { @@ -303,30 +302,6 @@ def get_type(self): def get_position(self): return self.position - # def take_wood(self, amount=1): # defaults, left for future in case decide change. - # if self.wood > 0: - # self.wood = self.wood - amount - # if self.wood < 0: - # self.wood = 0 # ensures resource is fully used, but cant go negative. - # return True - # return False - # - # def take_stone(self, amount=1): - # if self.stone > 0: - # self.stone = self.stone - amount - # if self.stone < 0: - # self.stone = 0 - # return True - # return False - # - # def take_metal(self, amount=1): - # if self.metal > 0: - # self.metal = self.metal - amount - # if self.metal < 0: - # self.metal = 0 - # return True - # return False - class City: def __init__(self, model_link, save_data): diff --git a/project/menus/menu.py b/project/menus/menu.py index c520b63..07b8a5d 100644 --- a/project/menus/menu.py +++ b/project/menus/menu.py @@ -195,7 +195,7 @@ def __init__(self, GUI): self.rect[0] + 5, self.rect[1] + 130) self.version = pygame_gui.Text( - constants.version, + constants.VERSION, constants.FONTS["sizes"]["medium"], constants.FONTS["colour"], constants.FONTS["main"], self.rect[0] + 5, self.rect[1] + self.rect[3] - 20) From ba5c0b653c4cfe6fe5b89a18963189e8f1b75e59 Mon Sep 17 00:00:00 2001 From: Ben Ryder Date: Mon, 20 Sep 2021 22:24:46 +0100 Subject: [PATCH 2/3] GH-29: Adding pylint config and initial progress on pylint fixes for the pygame_gui package. Deleted unused pygame_gui.Cursor element. --- .pylintrc | 7 +++++++ pygame_gui/__init__.py | 14 +++++++++++++- pygame_gui/button.py | 40 +++++++++++++++++++++++++++++++++++++++- pygame_gui/checkbox.py | 36 +++++++++++++++++++++++++++++++++++- pygame_gui/cursor.py | 10 ---------- pygame_gui/image.py | 22 ++++++++++++++++++++++ pygame_gui/panel.py | 39 +++++++++++++++++++++++++++++++++++++++ 7 files changed, 155 insertions(+), 13 deletions(-) create mode 100644 .pylintrc delete mode 100644 pygame_gui/cursor.py diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..94f5b11 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,7 @@ +[MASTER] + +# Custom pylint overrides for the project +disable= + too-many-arguments, + too-many-instance-attributes, + too-few-public-methods diff --git a/pygame_gui/__init__.py b/pygame_gui/__init__.py index ee474ae..371cfd6 100644 --- a/pygame_gui/__init__.py +++ b/pygame_gui/__init__.py @@ -1,8 +1,20 @@ +""" +A custom set of general UI elements. + +Classes: + Text + Image + Button + Checkbox + Entry + Panel + TextButton +""" + from pygame_gui.text import * from pygame_gui.image import * from pygame_gui.button import * from pygame_gui.checkbox import * from pygame_gui.entry import * -from pygame_gui.cursor import * from pygame_gui.panel import * from pygame_gui.text_button import * diff --git a/pygame_gui/button.py b/pygame_gui/button.py index 54a269a..ea60cd2 100644 --- a/pygame_gui/button.py +++ b/pygame_gui/button.py @@ -1,9 +1,25 @@ +""" +A module holding the pygame_gui Button class. + +Classes: + Button +""" + import pygame import pygame_gui.image class Button: + """ The Button class which changes display when hovered and runs a function when clicked. """ def __init__(self, rest_image, hover_image, x, y): + """ + Parameters: + rest_image - The default image which is used for the button. + hover_image - The image to use when the button is being hovered over. + x - The x position to use for the button, in px. + y - The y position to use for the button, in px + """ + self.rest_image = pygame_gui.Image(rest_image, x, y) self.hover_image = pygame_gui.Image(hover_image, x, y) self.rect = self.rest_image.image.get_rect() @@ -12,21 +28,43 @@ def __init__(self, rest_image, hover_image, x, y): self.function = None def set_function(self, function): + """ + Used to set the function to be run when the button is clicked. + + Parameters: + function - Should be callable as a function. + """ + self.function = function def mouse_over(self): + """ Checks if the current mouse position is within the button's area. """ if self.rect.collidepoint(pygame.mouse.get_pos()): return True return False def check_clicked(self): + """ + Uses Button.mouse_over to determine if the mouse is within the button's area. + If the mouse is within the button then Button.function will be ran if set. + + NOTE: It is assumed that this will be run while testing a pygame.MOUSEBUTTONDOWN event. + """ + if self.mouse_over(): if self.function is not None: self.function() return True return False - + def draw(self, display): + """ + Draws the button to the given pygame display. + + Parameters: + display - A pygame.display instance. + """ + if self.mouse_over(): self.hover_image.draw(display) else: diff --git a/pygame_gui/checkbox.py b/pygame_gui/checkbox.py index 35586e1..670b902 100644 --- a/pygame_gui/checkbox.py +++ b/pygame_gui/checkbox.py @@ -1,9 +1,27 @@ +""" +A module holding the pygame_gui Checkbox class. + +Classes: + Checkbox +""" + import pygame import pygame_gui.image class Checkbox: + """ The Checkbox class which when clicked will toggle a Checkbox.active property. """ def __init__(self, rest_image, hover_image, active_image, active_hover_image, x, y): + """ + Parameters: + rest_image - The default image which is used for an in-active checkbox. + hover_image - The hover image to use for an in-active checkbox. + active_image - The image to use when the checkbox is active (checked). + active_hover_image - The hover image to show when the checkbox is active (checked). + x - The x position to use for the checkbox, in px. + y - The y position to use for the checkbox, in px + """ + self.rest_image = pygame_gui.Image(rest_image, x, y) self.hover_image = pygame_gui.Image(hover_image, x, y) self.active_image = pygame_gui.Image(active_image, x, y) @@ -14,17 +32,33 @@ def __init__(self, rest_image, hover_image, active_image, active_hover_image, x, self.active = False def mouse_over(self): + """ Checks if the current mouse position is within the checkboxes area. """ + if self.rect.collidepoint(pygame.mouse.get_pos()): return True return False def check_clicked(self): + """ + Uses Checkbox.mouse_over to determine if the mouse is within the checkboxes area. + If the mouse is within the checkbox then Checkbox.active will be set to not Checkbox.active. + + NOTE: It is assumed that this will be run while testing a pygame.MOUSEBUTTONDOWN event. + """ + if self.mouse_over(): self.active = not self.active return True return False - + def draw(self, display): + """ + Draws the checkbox to the given pygame display. + + Parameters: + display - A pygame.display instance. + """ + if self.mouse_over(): if self.active: self.active_hover_image.draw(display) diff --git a/pygame_gui/cursor.py b/pygame_gui/cursor.py deleted file mode 100644 index 9295cd3..0000000 --- a/pygame_gui/cursor.py +++ /dev/null @@ -1,10 +0,0 @@ -import pygame - - -class Cursor: - def __init__(self, imageref): - pygame.mouse.set_visible(False) - self.image = pygame.image.load(imageref).convert_alpha() - - def draw(self, surface): - surface.blit(self.image, pygame.mouse.get_pos()) diff --git a/pygame_gui/image.py b/pygame_gui/image.py index 6d33337..9ce41ce 100644 --- a/pygame_gui/image.py +++ b/pygame_gui/image.py @@ -1,12 +1,34 @@ +""" +A module holding the pygame_gui Image class. + +Classes: + Image +""" + import pygame class Image: + """ An Image class to hold and display a pygame.image instance. """ def __init__(self, image_ref, x, y): + """ + Parameters: + image_ref - A file path to the image to load and use. + x - The x position to use for the image, in px. + y - The y position to use for the image, in px. + """ + self.image = pygame.image.load(image_ref).convert_alpha() self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y def draw(self, display): + """ + Blit the image to the given pygame display. + + Parameters: + display - A pygame.display instance. + """ + display.blit(self.image, self.rect.topleft) diff --git a/pygame_gui/panel.py b/pygame_gui/panel.py index 87f385e..2e7f005 100644 --- a/pygame_gui/panel.py +++ b/pygame_gui/panel.py @@ -1,26 +1,65 @@ +""" +A module holding the pygame_gui Panel class. + +Classes: + Panel +""" + import pygame class Panel: + """ + A Panel class used to display a simple rectangle 'panel' element. + """ def __init__(self, rect, transparency, colour): + """ + Parameters: + rect - A pygame.Rect compatible declaration such as [x, y, width, height]. + transparency - An alpha value 0 to 255 used to set the Panel opacity. + colour - A valid pygame colour in the form (red, green blue). + """ + self.rect = pygame.Rect(rect) self.colour = colour self.transparency = transparency self.surface = self.make_surface() def reset_rect(self, rect): + """ + Reset the Panel.rect value using the new rect value supplied. + + Parameters: + rect - Should be a valid pygame.Rect argument. + """ + self.rect = pygame.Rect(rect) self.surface = self.make_surface() def reset_width(self, width): + """ + Reset the Panel.rect.width value using the new width value supplied. + + Parameters: + width - The new width as an integer. + """ + self.rect.width = width self.surface = self.make_surface() def make_surface(self): + """ Create a surface that is used when displaying the Panel itself. """ surface = pygame.Surface([self.rect[2], self.rect[3]]) surface.set_alpha(self.transparency) return surface def draw(self, display): + """ + Blit the panel surface to the given pygame display. + + Arguments: + display - A pygame.display instance. + """ + self.surface.fill(self.colour) display.blit(self.surface, [self.rect[0], self.rect[1]]) From 83b2c13528e9d52054aabe8578ad2664a1d590f0 Mon Sep 17 00:00:00 2001 From: Ben Ryder Date: Thu, 23 Sep 2021 22:05:22 +0100 Subject: [PATCH 3/3] GH-29: Finishing pylint fixes for pygame_gui package. --- .pylintrc | 3 +- pygame_gui/__init__.py | 2 +- pygame_gui/entry.py | 83 ++++++++++++++++++++++++++++++++++++--- pygame_gui/text.py | 41 ++++++++++++++++++- pygame_gui/text_button.py | 52 ++++++++++++++++++++++-- 5 files changed, 167 insertions(+), 14 deletions(-) diff --git a/.pylintrc b/.pylintrc index 94f5b11..ce390d1 100644 --- a/.pylintrc +++ b/.pylintrc @@ -4,4 +4,5 @@ disable= too-many-arguments, too-many-instance-attributes, - too-few-public-methods + too-few-public-methods, + duplicate-code diff --git a/pygame_gui/__init__.py b/pygame_gui/__init__.py index 371cfd6..8dd3a08 100644 --- a/pygame_gui/__init__.py +++ b/pygame_gui/__init__.py @@ -1,5 +1,5 @@ """ -A custom set of general UI elements. +A custom set of general UI elements that rely on external image assets for display. Classes: Text diff --git a/pygame_gui/entry.py b/pygame_gui/entry.py index d713faa..3ae8f55 100644 --- a/pygame_gui/entry.py +++ b/pygame_gui/entry.py @@ -1,13 +1,37 @@ +""" +A module holding the pygame_gui Entry class. + +Classes: + Entry +""" + import pygame import pygame_gui.text import pygame_gui.image class Entry: + """ The Entry class which allows users to enter text input. """ def __init__(self, rest_image, hover_image, rest_focused_image, hover_focused_image, initial_text, text_size, text_colour, text_font, text_padx, text_pady, sticky, x, y): + """ + Parameters: + rest_image - The default image which is used for the entry. + hover_image - The image to use when the entry is being hovered over. + rest_focused_image - The image to show when the entry is focused. + hover_focused_image - The image to show when the entry is focused and being hovered. + initial_text - The initial text to pre-populate the entry with. + text_size - The desired size of the text. + text_colour - The desired colour of the text, as a tuple (r, g, b). + text_font - The desired font for the text. + text_padx - The x padding that should be applied around the text. + text_pady - The y padding that should be applied around the text. + sticky - A boolean representing if text should remain when entry re-clicked. + x - The x position to use for the entry, in px. + y - The y position to use for the entry, in px + """ self.rest_image = pygame_gui.Image(rest_image, x, y) self.hover_image = pygame_gui.Image(hover_image, x, y) @@ -20,22 +44,35 @@ def __init__(self, rest_image, hover_image, self.text_padx = text_padx self.text_pady = text_pady self.active = False - self.sticky = sticky # sticky if text should remain when entry re-clicked on. + self.sticky = sticky self.text = pygame_gui.Text(initial_text, text_size, text_colour, text_font, self.rect.x+self.text_padx, self.rect.y+self.text_pady) - self.backspace = False # allows for continuous backspace. (as long as handle_event_up() is also called) - self.backspace_delay = 7 # READ ME!! - works as delayed by x frames, for higher frame rates increase delay. + # backspace allows for continuous backspace. (as long as handle_event_up() is also called) + self.backspace = False + # backspace_delay works as delayed by x frames, for higher frame rates increase delay. + self.backspace_delay = 7 self.backspace_counter = 0 def get_text(self): + """ Return the current text entered into the entry. """ + return self.text.text def mouse_over(self): + """ Checks if the current mouse position is within the entry's area. """ + if self.rect.collidepoint(pygame.mouse.get_pos()): return True return False def check_clicked(self): + """ + Uses Entry.mouse_over to determine if the mouse is within the entry's area. + If it is then the entry will become active, if not the entry will deactivate. + + NOTE: It is assumed that this will be run while testing a pygame.MOUSEBUTTONDOWN event. + """ + if self.mouse_over(): self.active = True if not self.sticky: @@ -45,22 +82,49 @@ def check_clicked(self): self.backspace = False def handle_event(self, event): + """ + Handle the given KEYDOWN event. Used to process text entry. + + Parameters: + event - A pygame.event instance of type KEYDOWN. + + NOTE: It is assumed that this will be run while testing a pygame.KEYDOWN event. + """ + if self.active: key_uni = event.unicode key_str = pygame.key.name(event.key) if key_str == "backspace": self.backspace = True # deletes characters in draw() - elif key_str == "space" and self.text.graphic_text.get_width() < self.rect[2] - self.text_padx*3: + elif ( + key_str == "space" + and self.text.graphic_text.get_width() < self.rect[2] - self.text_padx*3 + ): self.text.change_text(self.text.text + " ") else: - if self.text.graphic_text.get_width() < self.rect[2]-self.text_padx*3 and key_uni.isprintable(): - if pygame.key.get_mods() & pygame.KMOD_CAPS or pygame.key.get_mods() & pygame.KMOD_SHIFT: + if ( + self.text.graphic_text.get_width() < self.rect[2]-self.text_padx*3 + and key_uni.isprintable() + ): + if ( + pygame.key.get_mods() & pygame.KMOD_CAPS + or pygame.key.get_mods() & pygame.KMOD_SHIFT + ): self.text.change_text(self.text.text+key_uni.upper()) else: self.text.change_text(self.text.text+key_uni.lower()) def handle_event_up(self, event): + """ + Handle the given pygame.KEYUP event. Used to detect the backspace lifting. + + Parameters: + event - A pygame.event instance of type KEYUP. + + NOTE: It is assumed that this will be run while testing a pygame.KEYUP event. + """ + if self.active: key_str = pygame.key.name(event.key) @@ -68,6 +132,13 @@ def handle_event_up(self, event): self.backspace = False def draw(self, display): + """ + Draws the entry to the given pygame display. + + Parameters: + display - A pygame.display instance. + """ + # Delete character if suppose to. (done here as definitely called every game loop) if self.backspace: if self.backspace_counter >= self.backspace_delay: diff --git a/pygame_gui/text.py b/pygame_gui/text.py index 73206cc..28f8882 100644 --- a/pygame_gui/text.py +++ b/pygame_gui/text.py @@ -1,11 +1,29 @@ +""" +A module holding the pygame_gui Text class. + +Classes: + Text +""" + import pygame class Text: + """ The Text class which can be used to create a font and display text. """ def __init__(self, text, size, colour, font, x, y): + """ + Parameters: + text - The text to display. + size - The font size to use. + colour - The colour to use when rendering the text. + font - The font to use for the text, supplied as a path to a font file. + x - The x position for the text, in px. + y - The y position for the text, in px. + """ + self.text = text - self.x = x - self.y = y + self.x = x # pylint: disable=invalid-name + self.y = y # pylint: disable=invalid-name self.size = size self.colour = colour self.font = font @@ -13,21 +31,40 @@ def __init__(self, text, size, colour, font, x, y): self._config_text() def _config_font(self): + """ Used internally to configure the required font. """ + try: self.graphic_font = pygame.font.Font(self.font, self.size) except OSError: # can't read font file. self.graphic_font = pygame.font.SysFont(self.font, self.size) def _config_text(self): + """ Used internally to render the required text using the current font. """ + self.graphic_text = self.graphic_font.render(self.text, True, self.colour) self.rect = self.graphic_text.get_rect().move(self.x, self.y) def get_rect(self): + """ Return the rect of the current text rendered. """ + return self.rect def change_text(self, text): + """ + Update the displayed text to the new text supplied. + + Parameters: + text - The new text to display. + """ self.text = text self._config_text() def draw(self, display): + """ + Blit the text to the given pygame display. + + Parameters: + display - A pygame.display instance. + """ + display.blit(self.graphic_text, [self.x, self.y]) diff --git a/pygame_gui/text_button.py b/pygame_gui/text_button.py index 952d4a8..4bb6ed2 100644 --- a/pygame_gui/text_button.py +++ b/pygame_gui/text_button.py @@ -1,13 +1,35 @@ +""" +A module holding the pygame_gui TextButton class. + +Classes: + TextButton +""" + import pygame import pygame_gui.text class TextButton: - def __init__(self, rect, start_transparency, hover_transparancy, + """ The TextButton which acts like the Button class but doesn't use image assets. """ + def __init__(self, rect, start_transparency, hover_transparency, text, text_size, text_color, text_font): + """ + Parameters: + rect - A valid parameter for pygame.Rect. Determines the size & position of the button. + start_transparency - The initial transparency for the button. + hover_transparency - The transparency to give the button on hover. + text - The text to display within the button. + text_size - The size of the text. + text_color - The text colour to use. Given as an rgb tuple. + text_font - The font to use for the text, supplied as a path to a font file. + """ + self.rect = pygame.Rect(rect) - self.text = pygame_gui.Text(text, text_size, text_color, text_font, self.rect.x, self.rect.y) + self.text = pygame_gui.Text( + text, text_size, text_color, text_font, + self.rect.x, self.rect.y + ) # Moving text to center in button padding_x = (self.rect.width - self.text.rect.width) / 2 padding_y = (self.rect.height - self.text.rect.height) / 2 @@ -15,25 +37,47 @@ def __init__(self, rect, start_transparency, hover_transparancy, self.text.y += padding_y self.panel = pygame_gui.Panel(self.rect, start_transparency, (0, 0, 0)) - self.hover_panel = pygame_gui.Panel(self.rect, hover_transparancy, (0, 0, 0)) + self.hover_panel = pygame_gui.Panel(self.rect, hover_transparency, (0, 0, 0)) self.function = None def set_function(self, function): + """ + Used to set the function to be run when the button is clicked. + + Parameters: + function - Should be callable as a function. + """ + self.function = function def mouse_over(self): + """ Checks if the current mouse position is within the button's area. """ if self.rect.collidepoint(pygame.mouse.get_pos()): return True return False def check_clicked(self): + """ + Uses TextButton.mouse_over to determine if the mouse is within the button's area. + If the mouse is within the button then TextButton.function will be ran if set. + + NOTE: It is assumed that this will be run while testing a pygame.MOUSEBUTTONDOWN event. + """ + if self.mouse_over(): if self.function is not None: self.function() return True return False - + def draw(self, display): + """ + Draw the text button to the given pygame display. + + Parameters: + display - A pygame.display instance. + """ + if self.mouse_over(): self.hover_panel.draw(display) else: