Example #1
0
class ChatInputWindow:
    
    def __init__(self, x, y, width=600, font_size=15):
        self.input = TextInput(font_family='dpcomic.ttf',
                               antialias=False,
                               max_string_length=width//font_size - 4)
                               
        self.font_size = font_size

        self.surf = pg.Surface((width, font_size*3)).convert_alpha()
        self.surf.fill((88, 88, 88, 88))

        self.visible = False
        
        self.pos = x, y

    def update_surf(self):
        self.surf.fill((88, 88, 88, 88))

        self.surf.blit(
            self.input.font_object.render(
                '#', False, self.input.text_color), (self.font_size, self.font_size))
        
        self.surf.blit(self.input.get_surface(), (3*self.font_size, self.font_size))

    def update(self, events):
        for event in events:
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_t and not self.visible:
                    self.visible = True
                    return
        if self.visible and self.input.update(events):
            self.parse(self.input.get_text())
            self.input.clear_text()
            self.visible = False
    
    def parse(self, text):
        if not text.startswith('/'):
            print(text)  # Just print text
        else:
            cmd(text[1:])  # Execute command

    def draw(self, screen):
        if self.visible:
            self.update_surf()
            screen.blit(self.surf, self.pos)
def ask_player_for_username(screen, stats):
    fontsize = 35
    inputfield = TextInput(
        "USERNAME",
        font_family="Ariel",
        text_color=pygame.Color("white"),
        cursor_color=pygame.Color("red"),
        font_size=fontsize,
    )
    username = None
    myfont = pygame.font.SysFont("sans serif", fontsize)
    message = Message(
        (550, 550),
        "Type your name & press Enter",
        font=myfont,
        color=pygame.Color("green"),
    )

    while True:
        draw_background_image(screen)
        draw_saveusername_page(screen)
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                stats.close_asteroids_timer()
                sys.exit()

        if inputfield.update(events):
            username = inputfield.get_text()
            break

        screen.blit(
            inputfield.get_surface(),
            (650, 500),
        )
        message.blitme(screen)
        pygame.display.update()
    return username
Example #3
0
def menu_screen(screen, clock):

    # declaring important variables
    color_choice = 0
    option_flag = 0
    prison_choice = 0
    random_hint = random.randint(0, 7)  # displays random quote
    high_score, high_time = read_highscore()
    timer = 0
    global mute, friction, first
    # playing start sound jail
    pygame.mixer.music.load(os.path.join(assets_directory, "start.wav"))
    pygame.mixer.music.play(-1)
    pygame.mixer.music.set_volume(1)

    # settings and player name
    settings_manager = Settings_Manager()
    is_editing_name = False
    edit_name_start_button = ImgButton(pygame, screen,
                                       (34, scr_height - 70, 32, 32),
                                       edit_start_img)
    edit_name_end_button = ImgButton(pygame, screen,
                                     (34, scr_height - 70, 32, 32),
                                     edit_end_img)
    name_input = TextInput('',
                           text_color=(255, 255, 255),
                           cursor_color=(255, 255, 255),
                           font_and_size=message_text1)

    # display start image

    while timer <= 180 and first:
        timer += 1
        screen.blit(start_img_resized, (0, 0))
        draw_walls(screen, wall_brick_width, wall_brick_height)
        disp_text(screen, "Will You Make It Out... Alive?",
                  (old_div(scr_width, 2), 100), start_horror_text, peace_green)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                os._exit(0)
        pygame.display.update()
        clock.tick(FPS)

    first = 0
    pygame.mixer.music.stop()
    pygame.mixer.music.load(os.path.join(assets_directory, "start_screen.ogg"))
    pygame.mixer.music.play(-1)
    pygame.mixer.music.set_volume(2)

    while True:

        if not mute:
            pygame.mixer.music.pause()
        else:
            pygame.mixer.music.unpause()
        # time passed
        delta_time = old_div(clock.get_time(), 10)
        mouse_x, mouse_y = pygame.mouse.get_pos()
        # checking for events
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    option_flag = (option_flag + 1) % 2
                if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    option_flag = (option_flag - 1) % 2
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    color_choice = (color_choice + 3) % 4
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    color_choice = (color_choice + 1) % 4
                if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
                    return option_flag, color_choice, mute  # return index of color in striker_colors

                if event.key == pygame.K_ESCAPE:
                    os._exit(0)
            if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed(
            )[0]:
                if mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 100 and mouse_y > 70:
                    mute = not mute
                    mute = mute
            if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed(
            )[0]:
                if mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 200 and mouse_y > 170:
                    write_highscore(0, 0, 0, 0, 0)
                    high_score, high_time = read_highscore()
            if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed(
            )[0]:
                if mouse_x < 284 and mouse_x > 114 and mouse_y < 336 and mouse_y > 318:
                    prison_choice = 0
                    friction = 0.01
            if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed(
            )[0]:
                if mouse_x < 527 and mouse_x > 325 and mouse_y < 336 and mouse_y > 318:
                    prison_choice = 1
                    friction = 0.018
            if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed(
            )[0]:
                if mouse_x < 797 and mouse_x > 584 and mouse_y < 336 and mouse_y > 318:
                    prison_choice = 2
                    friction = 0.025
            if event.type == pygame.QUIT:
                os._exit(0)

            # checking for button clicks
            if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
                if is_editing_name:
                    if edit_name_end_button.check_click(event.pos):
                        settings_manager.settings_data[
                            'player_name'] = name_input.get_text()
                        settings_manager.save_settings_to_file()
                        is_editing_name = False
                else:
                    if edit_name_start_button.check_click(event.pos):
                        settings_manager.settings_data['player_name'] = ""
                        name_input.clear_text()
                        is_editing_name = True

            # fedd name input box with events
            name_input.update(events)

        screen.fill(black)  # black background, to be changed later
        draw_walls(screen, wall_brick_width, wall_brick_height)

        # display moving ball
        menu_ball.menu_screen_move(delta_time)
        menu_ball.check_collide_wall()
        menu_ball.check_collide_palette()
        menu_ball.draw(screen)

        # display quote
        # displaying random hint
        disp_text(screen, "\"" + hint_message[random_hint % 7] + "\"",
                  (old_div(scr_width, 2), old_div(scr_height, 4) + 20),
                  quote_text, orange)

        # display title
        disp_text(screen, "Brk",
                  (old_div(scr_width, 2) - 70, old_div(scr_height, 2) - 240),
                  game_title_text_large, orange)
        disp_text(screen, "OUT",
                  (old_div(scr_width, 2) + 100, old_div(scr_height, 2) - 240),
                  game_title_text_small, white)

        disp_text(screen, "YOUR PRISON",
                  (old_div(scr_width, 2), old_div(scr_height, 2) - 80),
                  prison_text_big, blood_red)

        if prison_choice == 0:
            disp_text(
                screen, "HOME",
                (old_div(scr_width, 2) - 250, old_div(scr_height, 2) - 24),
                prison_text1, blue)
        else:
            disp_text(
                screen, "HOME",
                (old_div(scr_width, 2) - 250, old_div(scr_height, 2) - 24),
                prison_text, yellow)

        if prison_choice == 1:
            disp_text(
                screen, "DUNGEON",
                (old_div(scr_width, 2) - 25, old_div(scr_height, 2) - 24),
                prison_text1, blue)
        else:
            disp_text(
                screen, "DUNGEON",
                (old_div(scr_width, 2) - 25, old_div(scr_height, 2) - 24),
                prison_text, yellow)

        if prison_choice == 2:
            disp_text(
                screen, "TARTARUS",
                (old_div(scr_width, 2) + 240, old_div(scr_height, 2) - 24),
                prison_text1, blue)
        else:
            disp_text(
                screen, "TARTARUS",
                (old_div(scr_width, 2) + 240, old_div(scr_height, 2) - 24),
                prison_text, yellow)

        disp_text(screen, "HIGHSCORE", (130, 65), start_screen_number, white)
        disp_text(screen, high_score, (130, 105), start_screen_number1, white)
        disp_text(screen, high_time[:2] + ":" + high_time[2:4], (130, 140),
                  start_screen_number1, white)

        if mute:
            screen.blit(unmute_img, (scr_width - 100, 70))
        else:
            screen.blit(mute_img, (scr_width - 100, 70))
        screen.blit(help_img, (scr_width - 100, 120))
        screen.blit(reset_img, (scr_width - 100, 170))
        # display menu
        # display "Let's Play"
        if option_flag == 0:
            disp_text(screen, "Let's Escape",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 60),
                      menu_item_text_selected, silver)
        else:
            disp_text(screen, "Let's Escape",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 60),
                      menu_item_text, grey)

        # display white boundary around color palette
        pygame.draw.rect(screen,
                         white, (old_div(scr_width, 2) - 200,
                                 old_div(scr_height, 2) + 100, 400, 100), 3)
        pygame.draw.rect(screen,
                         white, (old_div(scr_width, 2) - 192,
                                 old_div(scr_height, 2) + 108, 384, 84), 2)

        # display color palette
        if color_choice == 0:
            pygame.draw.rect(screen, light_green,
                             (old_div(scr_width, 2) - 190,
                              old_div(scr_height, 2) + 110, 80, 80))
        else:
            pygame.draw.rect(screen, green,
                             (old_div(scr_width, 2) - 185,
                              old_div(scr_height, 2) + 115, 70, 70))

        if color_choice == 1:
            pygame.draw.rect(screen,
                             light_red, (old_div(scr_width, 2) - 90,
                                         old_div(scr_height, 2) + 110, 80, 80))
        else:
            pygame.draw.rect(screen,
                             red, (old_div(scr_width, 2) - 85,
                                   old_div(scr_height, 2) + 115, 70, 70))

        if color_choice == 2:
            pygame.draw.rect(screen, light_magenta,
                             (old_div(scr_width, 2) + 10,
                              old_div(scr_height, 2) + 110, 80, 80))
        else:
            pygame.draw.rect(screen,
                             magenta, (old_div(scr_width, 2) + 15,
                                       old_div(scr_height, 2) + 115, 70, 70))

        if color_choice == 3:
            pygame.draw.rect(screen, light_blue,
                             (old_div(scr_width, 2) + 110,
                              old_div(scr_height, 2) + 110, 80, 80))
        else:
            pygame.draw.rect(screen, blue,
                             (old_div(scr_width, 2) + 115,
                              old_div(scr_height, 2) + 115, 70, 70))

        # display "I'm Scared"
        if option_flag == 1:
            disp_text(screen, "I'm Scared",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 240),
                      menu_item_text_selected, silver)
        else:
            disp_text(screen, "I'm Scared",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 240),
                      menu_item_text, grey)

        # display message
        if mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 100 and mouse_y > 70:
            if mute:
                disp_text(
                    screen, "Click To Mute",
                    (old_div(scr_width, 2), old_div(scr_height, 2) + 300),
                    message_text, yellow)
            else:
                disp_text(
                    screen, "Click To Unmute",
                    (old_div(scr_width, 2), old_div(scr_height, 2) + 300),
                    message_text, yellow)
        elif mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 150 and mouse_y > 120:
            disp_text(screen, "Click For Help",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 300),
                      message_text, yellow)
        elif mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 200 and mouse_y > 170:
            disp_text(screen, "Click To Reset Highscore",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 300),
                      message_text, yellow)
        elif option_flag == 0:
            disp_text(screen, "Press Enter To Play",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 300),
                      message_text, yellow)
        elif option_flag == 1:
            disp_text(screen, "Press Enter To Quit Game",
                      (old_div(scr_width, 2), old_div(scr_height, 2) + 300),
                      message_text, yellow)

        # display player name
        disp_text_origin(
            screen,
            settings_manager.settings_data['player_name'],
            (80, scr_height - 70),
            message_text1,
            white,
        )
        if is_editing_name:
            edit_name_end_button.draw()
        else:
            edit_name_start_button.draw()

        if is_editing_name:
            screen.blit(name_input.get_surface(), (80, scr_height - 70))

        pygame.display.update()
        clock.tick(FPS)
Example #4
0
class Game(object):
    """The game instance."""
    def __init__(self):
        # Create the clock
        self.clock = pygame.time.Clock()

        # Create the game window
        self.window = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
        pygame.display.set_caption('Wikipedia Bingo')

        # Default game options (changed on start screen)
        self.limit = 5
        self.board_size = 5

    def run(self):
        """Run the game until it quits."""
        self.running = True
        while self.running:
            # Display the start screen
            self.start_screen()
            # Start screen quit

            # Display the main screen
            self.main_screen()
            # Main screen quit

        # Exit
        self.terminate()

    def start_screen(self):
        """Create the start screen."""
        self.loop_stage = True

        # Define buttons
        self.buttons = {}
        # Options
        self.buttons['start'] = Button('START', TEXTCOLOR, TILECOLOR,
                                       WINDOWWIDTH / 2 - 125,
                                       WINDOWHEIGHT - 100)
        self.buttons['start'].action = self.next_stage

        self.buttons['quit'] = Button('QUIT', TEXTCOLOR, TILECOLOR,
                                      WINDOWWIDTH / 2 + 25, WINDOWHEIGHT - 100)
        self.buttons['quit'].action = self.terminate

        # Difficulty
        self.buttons['limit3'] = Button('Hard', TEXTCOLOR, TILECOLOR,
                                        WINDOWWIDTH / 2 + 100, 500)
        self.buttons['limit3'].action = self.set_limit_to_3
        self.buttons['limit3_sel'] = Button('Hard', TEXTCOLOR, WHITE,
                                            WINDOWWIDTH / 2 + 100, 500)
        self.buttons['limit3_sel'].action = self.set_limit_to_3

        self.buttons['limit5'] = Button('Medium', TEXTCOLOR, TILECOLOR,
                                        WINDOWWIDTH / 2 - 50, 500)
        self.buttons['limit5'].action = self.set_limit_to_5
        self.buttons['limit5_sel'] = Button('Medium', TEXTCOLOR, WHITE,
                                            WINDOWWIDTH / 2 - 50, 500)
        self.buttons['limit5_sel'].action = self.set_limit_to_5

        self.buttons['limit7'] = Button('Easy', TEXTCOLOR, TILECOLOR,
                                        WINDOWWIDTH / 2 - 200, 500)
        self.buttons['limit7'].action = self.set_limit_to_7
        self.buttons['limit7_sel'] = Button('Easy', TEXTCOLOR, WHITE,
                                            WINDOWWIDTH / 2 - 200, 500)
        self.buttons['limit7_sel'].action = self.set_limit_to_7

        # Board size
        self.buttons['3x3'] = Button('3x3', TEXTCOLOR, TILECOLOR,
                                     WINDOWWIDTH / 2 - 200, 600)
        self.buttons['3x3'].action = self.set_board_size_to_3x3
        self.buttons['3x3_sel'] = Button('3x3', TEXTCOLOR, WHITE,
                                         WINDOWWIDTH / 2 - 200, 600)
        self.buttons['3x3_sel'].action = self.set_board_size_to_3x3

        self.buttons['5x5'] = Button('5x5', TEXTCOLOR, TILECOLOR,
                                     WINDOWWIDTH / 2 - 50, 600)
        self.buttons['5x5'].action = self.set_board_size_to_5x5
        self.buttons['5x5_sel'] = Button('5x5', TEXTCOLOR, WHITE,
                                         WINDOWWIDTH / 2 - 50, 600)
        self.buttons['5x5_sel'].action = self.set_board_size_to_5x5

        self.buttons['7x7'] = Button('7x7', TEXTCOLOR, TILECOLOR,
                                     WINDOWWIDTH / 2 + 100, 600)
        self.buttons['7x7'].action = self.set_board_size_to_7x7
        self.buttons['7x7_sel'] = Button('7x7', TEXTCOLOR, WHITE,
                                         WINDOWWIDTH / 2 + 100, 600)
        self.buttons['7x7_sel'].action = self.set_board_size_to_7x7

        while self.loop_stage:
            # Get events
            events = pygame.event.get()

            # Check clicks
            for event in events:
                if event.type == loc.MOUSEBUTTONUP:
                    # check if the user clicked on an option button
                    for button_name in self.buttons:
                        button = self.buttons[button_name]
                        if button.rect.collidepoint(event.pos):
                            button.action()

            # Check for exit
            self.check_for_quit(events)

            # Draw the board
            self.draw_start_screen()

            # Tick the FPS clock
            self.clock.tick(FPS)

    def draw_start_screen(self):
        """Draw the start screen."""
        self.window.fill(BGCOLOR)
        # Draw the name
        # txt = 'Wikipedia Bingo!'
        # surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 855, 60)
        # self.window.blit(surf, rect)

        # Draw the logo
        img = pygame.image.load('WIKIPEDIA_BINGO_small.png')
        rect = img.get_rect()
        rect.center = (WINDOWWIDTH / 2, 200)
        self.window.blit(img, rect)

        # Draw the instructions
        txt = 'INSTRUCTIONS'
        surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 100, 200)
        self.window.blit(surf, rect)
        with open('instructions.txt') as f:
            text = f.read().split('\n')
        for i, line in enumerate(text):
            textSurf, textRect = make_text(line, MESSAGECOLOR, BGCOLOR, 100,
                                           230 + 20 * i)
            self.window.blit(textSurf, textRect)

        # Draw the buttons
        txt = 'OPTIONS'
        surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 890, 400)
        self.window.blit(surf, rect)

        txt = 'Chose difficulty:'
        surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 850, 450)
        self.window.blit(surf, rect)
        txt = 'Chose board size:'
        surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 850, 550)
        self.window.blit(surf, rect)
        for button_name in self.buttons:
            button = self.buttons[button_name]
            # Size pressed
            if self.board_size == 3 and button_name in [
                    '3x3', '5x5_sel', '7x7_sel'
            ]:
                continue
            elif self.board_size == 5 and button_name in [
                    '3x3_sel', '5x5', '7x7_sel'
            ]:
                continue
            elif self.board_size == 7 and button_name in [
                    '3x3_sel', '5x5_sel', '7x7'
            ]:
                continue
            # Limit button pressed
            elif self.limit == 3 and button_name in [
                    'limit3', 'limit5_sel', 'limit7_sel'
            ]:
                continue
            elif self.limit == 5 and button_name in [
                    'limit3_sel', 'limit5', 'limit7_sel'
            ]:
                continue
            elif self.limit == 7 and button_name in [
                    'limit3_sel', 'limit5_sel', 'limit7'
            ]:
                continue
            else:
                self.window.blit(button.surface, button.rect)

        # Draw the leaderboard
        txt = 'HIGH SCORES'
        surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 1500, 200)
        self.window.blit(surf, rect)

        scoreboard = pd.read_csv('leaderboard.csv')
        strings = scoreboard['name'].values
        scores = scoreboard['score'].values
        for i, (name, score) in enumerate(zip(strings[:25], scores[:25])):
            msg = '{: >5.0f}'.format(score)
            textSurf, textRect = make_text(msg, MESSAGECOLOR, BGCOLOR, 1500,
                                           250 + 20 * i)
            self.window.blit(textSurf, textRect)
            msg = '{}'.format(name[:3].upper())
            textSurf, textRect = make_text(msg, MESSAGECOLOR, BGCOLOR, 1600,
                                           250 + 20 * i)
            self.window.blit(textSurf, textRect)

        # Update the dipslay
        pygame.display.update()

    def main_screen(self):
        """Create the main screen."""
        self.loop_stage = True

        # Default user name
        self.name = None

        # Generate a new puzzle
        self.get_starting_board()

        # Create list of red tiles
        self.board_counts = np.zeros((self.board_size, self.board_size))
        self.board_new = np.zeros((self.board_size, self.board_size))

        # Quit button
        self.buttons = {}
        self.buttons['restart'] = Button('RESTART', TEXTCOLOR, TILECOLOR,
                                         WINDOWWIDTH - 150, 30)
        self.buttons['restart'].action = self.next_stage
        self.buttons['quit'] = Button('QUIT', TEXTCOLOR, TILECOLOR,
                                      WINDOWWIDTH - 150, 60)
        self.buttons['quit'].action = self.terminate

        # Create TextInput-object
        self.textinput = TextInput(text_color=TEXTCOLOR,
                                   cursor_color=TEXTCOLOR)

        # Create the message array (starts blank)
        self.message_array = None

        # Initial score.
        self.score = 0

        # Draw the initial board
        self.draw_main_screen()

        while self.loop_stage:
            # Get events
            events = pygame.event.get()

            # Check clicks
            for event in events:
                if event.type == loc.MOUSEBUTTONUP:
                    # check if the user clicked on an option button
                    for button_name in self.buttons:
                        button = self.buttons[button_name]
                        if button.rect.collidepoint(event.pos):
                            button.action()

            # Send events to the text reader
            if self.textinput.update(events):
                # Pressed enter
                user_input = self.textinput.get_text()
                self.textinput.clear_text()

                # Extra commands
                if user_input and user_input[0] == "\ "[0]:
                    command = user_input[1:].lower()
                    if command in ['q', 'quit']:
                        self.terminate()
                    if command == 'add':
                        self.board_counts += 1
                else:
                    # DEBUG
                    print(self.board_words)

                    # Get the article title
                    title = user_input.lower()

                    # Put the title in the top left
                    self.message_array = [title + ':']

                    if not self.game_won():
                        # Reset the new word counter
                        self.board_new = np.zeros(
                            (self.board_size, self.board_size))

                        # Get the wikipedia article
                        validation = Validation(title)
                        try:
                            validation.scrape_wiki()
                            validation.process_wiki()
                            words = validation.token
                            self.score += 1
                            print(self.score)
                        except Exception:
                            self.message_array.append('Article not found')
                            words = []
                            self.score += 1
                            print(self.score)

                        # Remove any words not on the board
                        words = [
                            word.lower() for word in words
                            if word.lower() in self.board_words.flatten()
                        ]

                        # Count the frequencies
                        counter = Counter(words)

                        # Create the message for the top left
                        if len(words) == 0:
                            self.message_array.append('No valid words')

                        for word in sorted(counter,
                                           key=lambda x: counter[x],
                                           reverse=True):
                            x, y = tuple(
                                np.argwhere(
                                    self.board_words == word.lower())[0])
                            current_count = self.board_counts[x][y]
                            limit = self.board_limits[x][y]
                            new_count = current_count + counter[word]

                            # Create the message array for the left hand courner
                            message = '{} ({:.0f})+{:.0f} = {:.0f}/{:.0f}'.format(
                                word, current_count, counter[word], new_count,
                                limit)
                            self.message_array.append(message)

                            # Check if the counter has overflowed
                            new_word = None
                            new_range = None
                            if new_count >= limit:
                                new_count = 0
                                new_word, new_range = self.get_new_word()
                                self.message_array.append(
                                    '  OVERFLOW > {}'.format(new_word))

                            # Save the new count, new word (if needed) and message
                            self.board_counts[x][y] = new_count
                            if new_word:
                                print(new_word)
                                self.board_words[x][y] = new_word
                                self.board_limits[x][y] = new_range
                                self.board_new[x][y] = 1
                    else:
                        # You win!
                        self.scoring_algorithm()

                        if not self.name and len(user_input) > 0:
                            self.name = user_input

                            # Update the leaderboard.
                            new_win = pd.DataFrame(columns=['score', 'name'])

                            new_win.loc[0] = [self.final_score, self.name]
                            leaderboard = pd.read_csv('leaderboard.csv')
                            new_leaderboard = pd.concat([leaderboard, new_win])
                            new_leaderboard = new_leaderboard.sort_values(
                                'score', ascending=False)
                            new_leaderboard.to_csv('leaderboard.csv',
                                                   index=False)

                            return

            # Check for exit
            self.check_for_quit(events)

            # Draw the board
            self.draw_main_screen()

            # Tick the FPS clock
            self.clock.tick(FPS)

    def draw_main_screen(self):
        """Draw the main screen."""
        self.window.fill(BGCOLOR)
        # Draw the board
        for tilex in range(len(self.board_words)):
            for tiley in range(len(self.board_words[0])):
                word = self.board_words[tilex][tiley]

                # Change the BG colour based on the count
                count = self.board_counts[tilex][tiley]
                limit = self.board_limits[tilex][tiley]
                if 0 < count < limit:
                    bgcolour = (255, 255 - count * 255 / limit,
                                255 - count * 255 / limit)
                else:
                    bgcolour = GREEN

                # Change the text colour if it's new
                new = self.board_new[tilex][tiley]
                if new:
                    bgcolour = (60, 185, 100)

                # Draw the tile
                self.draw_tile(tilex, tiley, word, count, limit, TEXTCOLOR,
                               bgcolour)

        left, top = self.get_tile_courner(0, 0)
        width = self.board_size * TILE_WIDTH
        height = self.board_size * TILE_HEIGHT
        pygame.draw.rect(self.window, BORDERCOLOR,
                         (left - 5, top - 5, width + 11, height + 11), 4)

        # Draw the count
        msg = 'COUNT: {:.0f}'.format(self.score)
        surf, rect = make_text(msg, MESSAGECOLOR, BGCOLOR, 5, 5)
        self.window.blit(surf, rect)

        # Draw the message
        if self.message_array:
            for i, msg in enumerate(self.message_array):
                textSurf, textRect = make_text(msg, MESSAGECOLOR, BGCOLOR, 5,
                                               35 + 20 * i)
                self.window.blit(textSurf, textRect)

        # Draw the winning message if you've won
        if self.game_won():
            # Display winning message
            textSurf, textRect = make_text('!! WINNER !!', MESSAGECOLOR,
                                           BGCOLOR, WINDOWWIDTH / 2 - 75, 5)
            self.window.blit(textSurf, textRect)

            # Display score
            self.scoring_algorithm()
            textSurf, textRect = make_text(
                'FINAL SCORE: {:.0f}'.format(self.final_score), MESSAGECOLOR,
                BGCOLOR, WINDOWWIDTH / 2 - 120, 25)
            self.window.blit(textSurf, textRect)

        # Draw the instructions
        if not self.game_won():
            instruct = 'Enter the name of a Wikipedia article:'
            color = MESSAGECOLOR
        else:
            instruct = 'Enter your name to add to the leaderboard (MAX 3 LETTERS):'
            color = (255, 50, 50)
        instructSurf, instructRect = make_text(instruct, color, BGCOLOR, 5,
                                               WINDOWHEIGHT - 60)
        self.window.blit(instructSurf, instructRect)

        # Draw the text box
        self.window.blit(self.textinput.get_surface(), (5, WINDOWHEIGHT - 30))

        # Draw the buttons
        for button_name in self.buttons:
            button = self.buttons[button_name]
            self.window.blit(button.surface, button.rect)

        # Update the dipslay
        pygame.display.update()

    # # # # #  BUTTON FUNCTIONS
    def next_stage(self):
        """Go to the next stage."""
        self.loop_stage = False

    def terminate(self):
        """Quit the game."""
        pygame.quit()
        sys.exit()

    def set_board_size_to_3x3(self):
        """Set the board size."""
        self.board_size = 3

    def set_board_size_to_5x5(self):
        """Set the board size."""
        self.board_size = 5

    def set_board_size_to_7x7(self):
        """Set the board size."""
        self.board_size = 7

    def set_limit_to_3(self):
        """Set the tile limits."""
        self.limit = 3

    def set_limit_to_5(self):
        """Set the tile limits."""
        self.limit = 5

    def set_limit_to_7(self):
        """Set the tile limits."""
        self.limit = 7

    def check_for_quit(self, events):
        """Check for quit events."""
        for event in events:
            if event.type == loc.QUIT:
                # terminate if any QUIT events are present
                self.terminate()
            if event.type == loc.KEYUP and event.key == loc.K_ESCAPE:
                # terminate if the KEYUP event was for the Esc key
                self.terminate()

    def get_starting_board(self):
        """Return a board data structure with tiles in the solved state."""
        words = []
        ranges = []
        for _ in range(self.board_size * self.board_size):
            word, limit = self.get_new_word()
            words.append(word)
            ranges.append(limit)
        self.board_words = np.array(words, dtype=object).reshape(
            (self.board_size, self.board_size))
        self.board_limits = np.array(ranges).reshape(
            (self.board_size, self.board_size))

    def get_new_word(self):
        """Get an unused word from the list of all words."""
        while True:
            target = TargetWord(ALL_WORDS)
            target.word_gen()
            word = target.word.lower()
            target.range_gen()
            limit = self.limit

            try:
                if word not in self.board_words.flatten():
                    break
            except Exception:
                break

        return word, limit

    def get_tile_courner(self, tilex, tiley):
        """Get the coordinates of the top left courner of a tile."""
        xmargin = int((WINDOWWIDTH - (TILE_WIDTH * self.board_size +
                                      (self.board_size - 1))) / 2)
        ymargin = int((WINDOWHEIGHT - (TILE_HEIGHT * self.board_size +
                                       (self.board_size - 1))) / 2)
        left = xmargin + (tilex * TILE_WIDTH) + (tilex - 1)
        top = ymargin + (tiley * TILE_HEIGHT) + (tiley - 1)
        return (left, top)

    def draw_tile(self,
                  tilex,
                  tiley,
                  word,
                  count,
                  limit,
                  txtcolour=TEXTCOLOR,
                  bgcolour=TILECOLOR):
        """Draw a tile at board coordinates tilex and tiley."""
        left, top = self.get_tile_courner(tilex, tiley)
        pygame.draw.rect(self.window, bgcolour,
                         (left, top, TILE_WIDTH, TILE_HEIGHT))

        surf = BASICFONT.render(str(word), True, txtcolour)
        rect = surf.get_rect()
        rect.center = (left + int(TILE_WIDTH / 2), top + int(TILE_HEIGHT / 2))
        self.window.blit(surf, rect)

        txt = '{:.0f}/{:.0f}'.format(count, limit)
        # txt = '{}{}'.format('-' * int(count), '*' * int(limit - count))
        surf = BASICFONT.render(txt, True, txtcolour)
        rect = surf.get_rect()
        rect.center = (left + int(TILE_WIDTH / 2) + 75,
                       top + int(TILE_HEIGHT / 2) + 20)
        self.window.blit(surf, rect)

    def game_won(self):
        """Determine if anyone has won the game."""
        won = False

        # check for winning rows
        for row in self.board_counts:
            if all(row > 0):
                won = True

        # check for winning columns
        for col in self.board_counts.T:
            if all(col > 0):
                won = True

        return won

    def scoring_algorithm(self):
        """
        Scores a player's performance

        Parameters
        ---------
        N : int
            number of wiki articles used to win
        mode : int
            Either 3, 5 or 7 for Easy, Medium and Hard
        grid : int
            Either 3, 5 or 7 for size of grid 3by3, 5by5 and 7by7
        """

        self.final_score = 0
        if self.board_size == 3:
            self.final_score += 2000
        elif self.board_size == 5:
            self.final_score += 4000
        elif self.board_size == 7:
            self.final_score += 6000

        if self.limit == 3:
            self.final_score += 4000
        elif self.limit == 5:
            self.final_score += 6000
        elif self.limit == 7:
            self.final_score += 8000

        self.final_score = int(self.final_score / (self.score + 1))
Example #5
0
class Door(sprite.Sprite):
    ''' The Door the player needs to open and answer questions '''

    def __init__(self, question, answer, x, y, part_name) -> None:
        super().__init__()
        self.question = question
        self.answer = answer.lower()
        self.door_done = image.load(join(
            "assets", "door done.png")).convert_alpha()
        self.door_done = transform.scale(self.door_done, (256, 256))
        self.image = image.load(join(
            "assets", "door.png")).convert_alpha()
        self.image = transform.scale(self.image, (256, 256))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.centery = y
        self.asking = False
        self.input = TextInput(text_color=WHITE)
        self.done = False
        self.part_name = part_name
        for a in player.acquired:
            if a['name'] == self.part_name:
                if self.question in a['question']:
                    self.done = True
                    self.image = self.door_done

    def update(self, events) -> None:
        screen.blit(self.image, self.rect)
        if not self.done:
            if self.rect.collidepoint(pygame.mouse.get_pos()) and \
                    pygame.mouse.get_pressed()[0] and not self.asking:
                self.asking = True
                door_open.play()
            else:
                if self.asking and not self.rect.collidepoint(
                    pygame.mouse.get_pos()) and \
                        pygame.mouse.get_pressed()[0]:
                    self.asking = False
                    door_close.play()
            if self.asking:
                self.input.update(events)
                inp = self.input.get_surface()
                inp_rect = inp.get_rect()
                inp_rect.centerx = WIDTH // 2
                inp_rect.y = self.rect.y - 40
                screen.blit(inp, inp_rect)
                q = question_font.render(self.question, True, BLACK)
                screen.blit(q,
                            (WIDTH // 2 - q.get_width() // 2, 50))
                for event in events:
                    if event.type == KEYDOWN:
                        if event.key == K_RETURN:
                            if fuzz.token_sort_ratio(self.answer,
                                                     self.input.get_text()
                                                     ) > 85:
                                self.asking = False
                                self.image = self.door_done
                                self.done = True
                                door_close.play()
                                player.pass_door(self.part_name, self.question)
                            else:
                                wrong_sound.play()