From bf34c0238f2cff103c88b8ed942bb8d9796feafa Mon Sep 17 00:00:00 2001 From: Willem Visagie <66644812+SirClashin1@users.noreply.github.com> Date: Mon, 20 Mar 2023 06:53:52 +0200 Subject: [PATCH] feat; Refactor Code (make code more concise in some places_ (#59) --- GUI/GUI.py | 102 ++++++++++++++++++--------------- GUI/GUIObjects.py | 142 ++++++++++++++++++++++------------------------ main.py | 8 +-- music_player.py | 20 +++---- 4 files changed, 135 insertions(+), 137 deletions(-) diff --git a/GUI/GUI.py b/GUI/GUI.py index 0379936..f89f5c8 100644 --- a/GUI/GUI.py +++ b/GUI/GUI.py @@ -24,19 +24,17 @@ def set_params(self, screen_width: int, screen_height: int, screen: pygame.Surfa # find a font that can draw emojis fonts = pygame.sysfont.get_fonts() - emojis = [font for font in fonts if "emoji" in font] + if emojis := [font for font in fonts if "emoji" in font]: + self.font = pygame.font.SysFont(emojis[0], 60) + self.button_font = pygame.font.SysFont(emojis[0], 40) + self.small_font = pygame.font.SysFont(emojis[0], 30) - if emojis == []: + else: print("Didn't find font with emojis") self.font = pygame.font.Font(None, 60) self.button_font = pygame.font.Font(None, 40) self.small_font = pygame.font.Font(None, 30) - else: - self.font = pygame.font.SysFont(emojis[0], 60) - self.button_font = pygame.font.SysFont(emojis[0], 40) - self.small_font = pygame.font.SysFont(emojis[0], 30) - self.button_left = Button(screen_width * .25, screen_height * .9, 200, 60, text="LEFT", font=self.button_font, bg_color=(200, 200, 200), hover_color=(220, 220, 220)) self.button_right = Button(screen_width * .75, screen_height * .9, 200, 60, text="RIGHT", font=self.button_font, bg_color=(200, 200, 200), hover_color=(220, 220, 220)) self.buttons_lst = [self.button_left, self.button_right] @@ -99,12 +97,14 @@ def __seperate_text_to_rows(self, text: str, max_width: int, font_to_use: pygame def __render_text_center(self, texts: list): """Render list of pygame text renders in the center of the screen""" # Get total height of text elements rendered. Sum all text heights and add the spaces between them - total_height = sum([x.get_size()[1] for x in texts]) + self.space_between_text * (len(texts) - 1) - + total_height = sum( + x.get_size()[1] for x in texts + ) + self.space_between_text * (len(texts) - 1) + # Loop through every text element and render it for _i, _text in enumerate(texts): _text_width, _text_height = _text.get_size() - + # Get the position to render it in the center of screen center_x = self.screen_width / 2 - _text_width / 2 center_y = (self.screen_height / 2 - _text_height / 2 + 60 * _i) - total_height / 4 # make all texts centered @@ -116,15 +116,21 @@ def ask_question(self, question: str, left_btn_txt: str, right_btn_txt: str) -> """Ask a question with two answers.\n RETURNS: If pressed left_button: Return True. If pressed right_button: Return False""" if not self.run_gui: - return self.__ask_question_no_gui(question + f" ({left_btn_txt} / {right_btn_txt}) ", left_btn_txt, right_btn_txt, color_before=Fore.GREEN, color_after=Fore.LIGHTMAGENTA_EX) - + return self.__ask_question_no_gui( + f"{question} ({left_btn_txt} / {right_btn_txt}) ", + left_btn_txt, + right_btn_txt, + color_before=Fore.GREEN, + color_after=Fore.LIGHTMAGENTA_EX, + ) + # Initalize texts and buttons text_renders = self.__seperate_text_to_rows(question, self.screen_width - 50, self.font) self.button_left.text = left_btn_txt self.button_right.text = right_btn_txt - + # Basic pygame window loop - while(True): + while True: self.screen.blit(self.background, (0, 0)) # Update buttons @@ -135,15 +141,17 @@ def ask_question(self, question: str, left_btn_txt: str, right_btn_txt: str) -> for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit_func() - + # If left mousebutton clicked, check if clicked on a button - if event.type == pygame.MOUSEBUTTONDOWN: - if pygame.mouse.get_pressed()[0]: - if self.button_left.check_click(): - return True - if self.button_right.check_click(): - return False - + if ( + event.type == pygame.MOUSEBUTTONDOWN + and pygame.mouse.get_pressed()[0] + ): + if self.button_left.check_click(): + return True + if self.button_right.check_click(): + return False + # Render the text self.__render_text_center(text_renders) pygame.display.update() @@ -157,17 +165,16 @@ def text_until_enter(self, text: str): text_renders = self.__seperate_text_to_rows(text, self.screen_width - 50, self.font) enter_text = self.small_font.render("Press Enter to continue", True, (0,0,0)) - while(True): + while True: self.screen.blit(self.background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit_func() - + # Return when enter pressed - if event.type == pygame.KEYDOWN: - if event.key == pygame.K_RETURN: - return + if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: + return # Render the center text self.__render_text_center(text_renders) @@ -187,12 +194,12 @@ def start_screen(self): if not self.run_gui: self.__start_screen_no_gui() return - + text_box_w = 300 text_box_h = 100 name_text_box = TextBox((self.screen_width / 2 - text_box_w / 2, self.screen_height * .7 - text_box_h / 2, text_box_w, text_box_h), font=self.font) - + music_toggle = Toggle(self.screen_width - self.music_toggle_size - 20, 20, "assets/images/MusicOn.png", "assets/images/MusicOff.png", (self.music_toggle_size, self.music_toggle_size)) text = self.font.render("Hi! What is you name?", True, (0,0,0)) @@ -207,22 +214,23 @@ def start_screen(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit_func() - + name_text_box.get_event(event) - if event.type == pygame.MOUSEBUTTONDOWN: - if pygame.mouse.get_pressed()[0]: - music_toggle.check_click(pygame.mouse.get_pos()) - - if music_toggle.get_state() == 1: - pygame.mixer.unpause() - else: - pygame.mixer.pause() - - if event.type == pygame.KEYDOWN: - if event.key == pygame.K_RETURN: - player_name = "".join(name_text_box.buffer) - got_name = True - + if ( + event.type == pygame.MOUSEBUTTONDOWN + and pygame.mouse.get_pressed()[0] + ): + music_toggle.check_click(pygame.mouse.get_pos()) + + if music_toggle.get_state() == 1: + pygame.mixer.unpause() + else: + pygame.mixer.pause() + + if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: + player_name = "".join(name_text_box.buffer) + got_name = True + self.screen.blit(text, (self.screen_width / 2 - text.get_size()[0] / 2, self.screen_height * .85)) music_toggle.draw(self.screen) @@ -254,8 +262,8 @@ def __ask_question_no_gui(self, question: str, first: str, second: str, color_be print("Invalid answer, try again.") def __start_screen_no_gui(self): - name = input(Fore.YELLOW + "Type your name: " + Fore.LIGHTBLUE_EX) - print(Fore.LIGHTGREEN_EX + "Welcome", name, "to this adventure!") + name = input(f"{Fore.YELLOW}Type your name: {Fore.LIGHTBLUE_EX}") + print(f"{Fore.LIGHTGREEN_EX}Welcome", name, "to this adventure!") if self.__ask_question_no_gui("Do you want to play? (yes / no) ", "yes", "no", color_before=Fore.YELLOW, color_after=Fore.LIGHTBLUE_EX): # Yes @@ -264,7 +272,7 @@ def __start_screen_no_gui(self): # No print("See you later! \U0001F600") self.exit_func() - + random.choice(chapters.my_list)() # if self.__ask_question_no_gui("Do you want music? \U0001F3B5 (yes / no) ", "yes", "no", color_before=Fore.YELLOW, color_after=Fore.LIGHTBLUE_EX): # # Yes diff --git a/GUI/GUIObjects.py b/GUI/GUIObjects.py index 1b82b9c..8fa0780 100644 --- a/GUI/GUIObjects.py +++ b/GUI/GUIObjects.py @@ -13,12 +13,8 @@ def __init__(self, x, y, width, height, bg_color=(120,120,120), hover_color=(150 self.bg_color = bg_color self.hover_color = hover_color self.hovering = False - - if font is None: - self.font = pygame.font.Font(None, font_size) - else: - self.font = font + self.font = pygame.font.Font(None, font_size) if font is None else font self.text = text self.text_color = text_color self.font_size = font_size @@ -35,12 +31,11 @@ def draw(self, screen): self.image.fill(self.border_color) pygame.draw.rect(self.image, self.hover_color, (self.border, self.border, self.width-self.border*2, self.height-self.border*2)) + elif self.border == 0: + self.image.fill(self.bg_color) else: - if self.border == 0: - self.image.fill(self.bg_color) - else: - self.image.fill(self.border_color) - pygame.draw.rect(self.image, self.bg_color, (self.border, self.border, self.width-self.border*2, self.height-self.border*2)) + self.image.fill(self.border_color) + pygame.draw.rect(self.image, self.bg_color, (self.border, self.border, self.width-self.border*2, self.height-self.border*2)) #text text = self.font.render(self.text, True, self.text_color) @@ -54,17 +49,16 @@ def draw(self, screen): def check_hover(self, mouse_pos): - if mouse_pos[0] >= self.x and mouse_pos[0] <= self.x+self.width and mouse_pos[1] >= self.y and mouse_pos[1] <= self.y+self.height: - self.hovering = True - else: - self.hovering = False + self.hovering = ( + mouse_pos[0] >= self.x + and mouse_pos[0] <= self.x + self.width + and mouse_pos[1] >= self.y + and mouse_pos[1] <= self.y + self.height + ) def check_click(self): - if self.hovering: - return True - - return False + return bool(self.hovering) class Text_box(): @@ -74,7 +68,7 @@ def __init__(self,x,y,width,height,bg_color=(155,155,155),active_color=(200,200, self.x = x - width / 2 self.y = y - height / 2 self.width = width - self.height = height + self.height = height self.pos = (self.x, self.y) self.size = (width, height) self.image = pygame.Surface((width, height)) @@ -93,20 +87,10 @@ def __init__(self,x,y,width,height,bg_color=(155,155,155),active_color=(200,200, self.placeholder_txt = placeholder_txt self.placeholder_color = placeholder_color self.max_chars = max_chars # -1 is infinite - if self.max_chars < 0: - self.inifnite_chars = True - else: self.inifnite_chars = False + self.inifnite_chars = self.max_chars < 0 def draw(self, screen): - if not self.active: - if self.border == 0: - self.image.fill(self.bg_color) - else: - self.image.fill(self.border_color) - pygame.draw.rect(self.image, self.bg_color, (self.border, self.border, - self.width-self.border*2, self.height-self.border*2)) - - else: + if self.active: if self.border == 0: self.image.fill(self.active_color) else: @@ -114,27 +98,38 @@ def draw(self, screen): pygame.draw.rect(self.image, self.active_color, (self.border, self.border, self.width-self.border*2, self.height-self.border*2)) + elif self.border == 0: + self.image.fill(self.bg_color) + else: + self.image.fill(self.border_color) + pygame.draw.rect(self.image, self.bg_color, (self.border, self.border, + self.width-self.border*2, self.height-self.border*2)) + #rendering text if self.text == "": placeholder_txt = self.font.render(self.placeholder_txt, True, self.placeholder_color) placeholder_txt.set_alpha(100) - text_width = placeholder_txt.get_width() - text_height = placeholder_txt.get_height() - if text_width < self.width-self.border*2: - self.image.blit(placeholder_txt, (2+self.border*2,(self.height-text_height)//2)) - else: - self.image.blit(placeholder_txt, ((self.border*2)+(self.width-text_width-self.border*3),(self.height-text_height)//2)) - + self._extracted_from_draw_21(placeholder_txt) else: text = self.font.render(self.text, False, self.text_color) - text_width = text.get_width() - text_height = text.get_height() - if text_width < self.width-self.border*2: - self.image.blit(text, (2+self.border*2,(self.height-text_height)//2)) - else: - self.image.blit(text, ((self.border*2)+(self.width-text_width-self.border*3),(self.height-text_height)//2)) - + self._extracted_from_draw_21(text) screen.blit(self.image, self.pos) + + # TODO Rename this here and in `draw` + def _extracted_from_draw_21(self, arg0): + text_width = arg0.get_width() + text_height = arg0.get_height() + if text_width < self.width-self.border*2: + self.image.blit(arg0, (2+self.border*2,(self.height-text_height)//2)) + else: + self.image.blit( + arg0, + ( + (self.border * 2) + + (self.width - text_width - self.border * 3), + (self.height - text_height) // 2, + ), + ) def add_text(self, key): @@ -150,45 +145,42 @@ def add_text(self, key): if len(self.text) < self.max_chars or self.inifnite_chars: # Adding numbers - if not self.only_letters: - if key in self.numbers: - text = list(self.text) - if key < 100: - text.append(str(key-48)) - self.text = "".join(text) - - # Spacebar - if key == 32: - text = list(self.text) - text.append(" ") - self.text = "".join(text) - # Dot - elif key == 46: + if not self.only_letters and key in self.numbers: text = list(self.text) - text.append(".") + if key < 100: + text.append(str(key-48)) self.text = "".join(text) - - # Add letters - if not self.only_numbers: - if chr(key).isalpha(): + # Spacebar + if key == 32: + self._extracted_from_add_text_24(" ") + elif key == 46: + self._extracted_from_add_text_24(".") + if chr(key).isalpha(): + if not self.only_numbers: text = list(self.text) text.append(chr(key)) self.text = "".join(text) - # Coma - elif key == 44: - text = list(self.text) - text.append(",") - self.text = "".join(text) - except: + elif key == 44: + if not self.only_numbers: + self._extracted_from_add_text_24(",") + except Exception: # Invalid key print(key, "is invalid key") + # TODO Rename this here and in `add_text` + def _extracted_from_add_text_24(self, arg0): + text = list(self.text) + text.append(arg0) + self.text = "".join(text) + def check_click(self, mouse_pos): - if mouse_pos[0] >= self.x and mouse_pos[0] <= self.x+self.width and mouse_pos[1] >= self.y and mouse_pos[1] <= self.y+self.height: - self.active = True - else: - self.active = False + self.active = ( + mouse_pos[0] >= self.x + and mouse_pos[0] <= self.x + self.width + and mouse_pos[1] >= self.y + and mouse_pos[1] <= self.y + self.height + ) def return_val(self): if self.only_letters: @@ -258,7 +250,7 @@ def process_kwargs(self,kwargs): if kwarg in defaults: defaults[kwarg] = kwargs[kwarg] else: - raise KeyError("InputBox accepts no keyword {}.".format(kwarg)) + raise KeyError(f"InputBox accepts no keyword {kwarg}.") self.__dict__.update(defaults) def get_event(self,event): diff --git a/main.py b/main.py index 11a7f6a..dc7edf7 100644 --- a/main.py +++ b/main.py @@ -20,9 +20,7 @@ # install missing modules required = {"colorama==0.4.6", "pygame==2.2.0"} installed = {pkg.key for pkg in pkg_resources.working_set} -missing = required - installed - -if missing: +if missing := required - installed: python = sys.executable subprocess.check_call([python, "-m", "pip", "install", *missing], stdout=subprocess.DEVNULL) @@ -49,9 +47,9 @@ WINDOW = pygame.display.set_mode((SCR_W, SCR_H)) except Exception as e: RUN_GUI = False - print(f"Running without pygame") + print("Running without pygame") -pygame.display.set_caption("Choose Your Own Adventure") +pygame.display.set_caption("Choose Your Own Adventure") pygame.display.set_icon(pygame.image.load("assets/images/logo.png")) # SET PYGAME WINDOW ICON diff --git a/music_player.py b/music_player.py index 7191273..11b6de8 100644 --- a/music_player.py +++ b/music_player.py @@ -41,7 +41,7 @@ def snakeonthebeach(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Snake On The Beach by Nico Staf") + print(f"{Fore.RED}Currently Playing - Snake On The Beach by Nico Staf") return sound @@ -58,7 +58,7 @@ def aparisiancafe(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - A Parisian Cafe by Aaron Kenny") + print(f"{Fore.RED}Currently Playing - A Parisian Cafe by Aaron Kenny") return sound @@ -76,7 +76,7 @@ def bliss(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Bliss by Luke Bergs") + print(f"{Fore.RED}Currently Playing - Bliss by Luke Bergs") return sound @@ -94,7 +94,7 @@ def happynjoyfulchildren(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Happy and Joyful Children") + print(f"{Fore.RED}Currently Playing - Happy and Joyful Children") return sound @@ -112,7 +112,7 @@ def tropicalsoul(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Tropical Soul by Luke Bergs") + print(f"{Fore.RED}Currently Playing - Tropical Soul by Luke Bergs") return sound @@ -130,7 +130,7 @@ def newlands(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - New Lands by Alex-Productions") + print(f"{Fore.RED}Currently Playing - New Lands by Alex-Productions") return sound @@ -148,7 +148,7 @@ def beachvibes(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Beach Vibes by Luke Bergs") + print(f"{Fore.RED}Currently Playing - Beach Vibes by Luke Bergs") return sound @@ -165,7 +165,7 @@ def tropicalfever(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Tropical Fever by Luke Bergs & LiQWYD") + print(f"{Fore.RED}Currently Playing - Tropical Fever by Luke Bergs & LiQWYD") return @@ -182,7 +182,7 @@ def happyadricanvillage(print_song_name=True): sound.play() if print_song_name: - print(Fore.RED + "Currently Playing - Happy African Village by John Bartmann") + print(f"{Fore.RED}Currently Playing - Happy African Village by John Bartmann") return sound @@ -210,7 +210,7 @@ def music(): start_song(print_song_name = not GUIInstance.run_gui) if not GUIInstance.run_gui: - print(Fore.BLUE + "Music has started") + print(f"{Fore.BLUE}Music has started") # Another function to not print all the stuff when starting new song