diff --git a/src/text_input.py b/src/text_input.py new file mode 100644 index 0000000..64acc25 --- /dev/null +++ b/src/text_input.py @@ -0,0 +1,61 @@ +import pygame + +class TextInput: + def __init__(self, width, height, pos_x, pos_y): + self.rect = pygame.Rect(pos_x, pos_y, width, height) + + self.font = pygame.font.SysFont("Arial", 22) + + # input text + self.text = "" + + self.active = False + + # colors + self.text_color = (255, 255, 255) + self.border_color = (255, 255, 255) + self.active_border_color = (0, 255, 0) + self.background_color = (30, 30, 30) + + def handle_event(self, event): + # check if mouse click event on text input box + if event.type == pygame.MOUSEBUTTONDOWN: + if self.rect.collidepoint(event.pos): + self.active = True + else: + self.active = False + + # check for keyboard input + if event.type == pygame.KEYDOWN and self.active: + # enter will submit and exit input box + if event.key == pygame.K_RETURN: + self.active = False + + # backspace will delete last character + elif event.key == pygame.K_BACKSPACE: + self.text = self.text[:-1] + # other characters will be added to the string + else: + self.text += event.unicode + + def draw(self, screen): + # draw background of input box + pygame.draw.rect(screen, self.background_color, self.rect) + + # change border color depending if input box is active or not + if self.active: + border_color = self.active_border_color + else: + border_color = self.border_color + + # draw border + pygame.draw.rect(screen, border_color, self.rect, 2) + + # draw text + text_surface = self.font.render(self.text, True, self.text_color) + + # show text with indentation + screen.blit(text_surface, (self.rect.x + 10, self.rect.y + 10)) + + def get_text(self): + return self.text