@max_1O

Как настроит input_box в pygame?

Здравствуйте. Пишу игру типа alien invasion для самостоятельной практики. Игрок стреляет на флот пришельцев, если хоть один пришелец столкнется с кораблем игрока, или дойдет до края экрана, уменьшается число доступных жизней. Так, когда все жизни израсходованы, на экране должна появится набранные очки за убитых пришельцев, а внизу очков я хотел реализовать input_box в котором игрок мог бы написать свое имя чтобы потом её вывести в списке рекордов. Я смог вывести input_box на экран, но она не реагирует на набор текста. Подскажите, в чем причина, как исправить?

код ниже заработает когда пришельцы доберутся до края или при столкновении с кораблем, при израсходовании всех жизней заработает else
def ship_hit(ship, aliens, bullets, stats, screen, settings, sb, play_button, settings_button, scores_button, exit_button, input_box):
    if stats.ships_left > 0:
        stats.ships_left -= 1

        ship.center_ship()

        aliens.empty()
        bullets.empty()
        create_aliens_fleet(screen, settings, aliens, sb, stats)
    else:
        score_label = Button(screen, "Your score:{}".format(stats.score), screen.get_rect().width, 150) # background for score message
        score_label.rect.center = screen.get_rect().center
        score_label.msg_image_rect.center = score_label.rect.center # positioning score message in center of screen/label
        score_label.draw_button()
        input_box.input_box.top = score_label.msg_image_rect.bottom # positioning input_box under score message
        input_box.text_surface_rect = input_box.text_surface.get_rect()
        input_box.text_surface_rect.center = screen.get_rect().center
        input_box.blitme()
        # calling check_events to check pressed buttons and type text in input_box
        check_events(ship, bullets, screen, settings, stats, play_button, settings_button, scores_button, exit_button, sb, aliens, input_box)
        pygame.display.flip()
        sleep(5) # to give player time for typing, how to make it wait till user presses enter button?
        stats.game_active = False


        sleep(1)

check_events
def check_events(ship, bullets, screen, settings, stats, play_button, settings_button, scores_button, exit_button, sb, aliens, input_box):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_buttons(mouse_x, mouse_y, play_button, settings_button, scores_button, exit_button, stats, sb, screen, settings, aliens)
            if input_box.input_box.collidepoint(event.pos) and stats.ships_left <0: # collision with input_box
                input_box.active = True # Start typing text in input_box
        if event.type == pygame.KEYDOWN:
            if input_box.active:
                if event.key == pygame.K_BACKSPACE:
                    input_box.text = input_box.text[:-1] # clear last symbol from text
                else:
                    input_box.text += event.unicode # print letters
            if stats.game_active:
                # works when game started
                check_keydown_events(event, ship, bullets, screen, settings, stats)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)


class Input_box
import pygame
from pygame import color

class Input_text():

    def __init__(self, screen):
        self.screen = screen
        self.font = pygame.font.Font(None, 48)
        self.input_box = pygame.Rect(0, 0, 140, 32)
        self.color_inactive = pygame.Color('lightskyblue3') # border color when not activated typing
        self.color_active = pygame.Color('dodgerblue2') # border color when activated typing
        self.color = self.color_inactive
        self.active = False
        self.text = ''
        self.text_surface = self.font.render(self.text, True, self.color)

    def blitme(self):
        width = max(200, self.text_surface.get_width()+10) # make input_box wider if text is long
        self.input_box.w = width
        self.screen.blit(self.text_surface, (self.input_box.x+5, self.input_box.y+5))
        pygame.draw.rect(self.screen, self.color, self.input_box, 2)


Заранее спасибо за выделенное время
  • Вопрос задан
  • 46 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы