예제 #1
0
    def __init__(self, terminal):
        """Initialize the class."""
        super().__init__(terminal)

        self._puzzle = random.choice(Puzzle.puzzles)

        self._completed = False
        self._exited = False
        self._board = Board(self._puzzle.board_def, self._BOARD_MAX_WIDTH,
                            self._BOARD_MAX_HEIGHT)
        self._start_time = None
        self._time_secs = None

        screen_rect = pygame.display.get_surface().get_rect()
        self._board_pos = (int((screen_rect[2] / 2) - (self._board.width / 2)),
                           self._BOARD_Y)

        self._status_font = load_font(self._FONT, self._STATUS_FONT_SIZE)
        self._timer_font = load_font(self._FONT, self._TIMER_FONT_SIZE)
        end_font = load_font(self._FONT, self._END_FONT_SIZE)
        self._game_over_texts = [
            end_font.render("Game over!!", True, (255, 255, 255)),
            end_font.render("Press R to retry, or Q to quit", True,
                            (255, 255, 255)),
        ]
        self._game_won_texts = [
            end_font.render("Game completed!!", True, (255, 255, 255)),
            end_font.render("Press R to retry, or Q to quit", True,
                            (255, 255, 255)),
        ]
예제 #2
0
 def start(self):
     """Start the program."""
     self._fontname, self._cypher = random.choice(Decrypt._FONTS)
     load_font(self._fontname, Decrypt._TEXT_SIZE)
     self._dec_string = ''.join([
         random.choice(list(self._cypher.keys())) for _ in range(
             random.randrange(Decrypt._MIN_LENGTH, Decrypt._MAX_LENGTH + 1))
     ])
     self._enc_string = ''.join([self._cypher[e] for e in self._dec_string])
     self._terminal.output([
         '<s {}><f {}>{}'.format(Decrypt._TEXT_SIZE, self._fontname,
                                 self._enc_string)
     ])
예제 #3
0
    def __init__(self, time_in_s, warning_secs):
        self._timeleft = time_in_s * 1000
        self._timer_font = load_font(CountdownTimer._TIMER_FONT,
                                     CountdownTimer._TIMER_SIZE)
        self._timer_large_font = load_font(CountdownTimer._TIMER_FONT,
                                           CountdownTimer._TIMER_LARGE_SIZE)
        self._warning_secs = warning_secs

        # Are we currently flashing the timer, and if so what time did it start
        self._flash_start = None

        # The times at which the timer should be large and flashing!
        self._flash_times = [warning_secs, 15, 5, 4, 3, 2, 1]
예제 #4
0
    def __init__(self,
                 item_id,
                 pos,
                 text,
                 text_size,
                 colour=(255, 255, 255),
                 selected_colour=(255, 255, 255),
                 align=util.Align.CENTER):
        """Initialize the class."""
        self.item_id = item_id
        self._pos = pos

        font = load_font(constants.TERMINAL_FONT, text_size)
        self._text = font.render(text, True, colour)
        self._selected_text = font.render(text, True, selected_colour)

        # Handle alignment
        text_width = self._text.get_rect()[2]
        surface_width = pygame.display.get_surface().get_rect()[2]
        if align == util.Align.LEFT:
            self._pos = (0, self._pos[1])
        elif align == util.Align.CENTER:
            self._pos = (int((surface_width / 2) - (text_width / 2)),
                         self._pos[1])
        else:
            self._pos = (surface_width - text_width, self._pos[1])
예제 #5
0
파일: game.py 프로젝트: orangeblock/tetris
 def __init__(me, title="Tetris", res=(800, 600)):
     pygame.display.set_caption(title)
     me.screen = pygame.display.set_mode(res)
     me.w, me.h = res
     me.font = resources.load_font(resources.font_menu)
     me.gameFont = resources.load_font(resources.font_game)
     me.eventkeys = {K_LEFT: 0, K_RIGHT: 0, K_UP: 0, K_DOWN: 0, K_RETURN: 0, K_ESCAPE: 0}  # used for one tap events
     me.keymap = {K_DOWN: 0}  # used for keys that can be held down
     me.sounds = {
         "ROT": resources.load_sound(resources.sound_rot, 0.5),
         "TOUCH": resources.load_sound(resources.sound_touch, 0.7),
         "CLEAR": resources.load_sound(resources.sound_clear, 0.8),
     }
     me.fullscreen = 0
     me.running = True
     me.states = []
     me.pushState(menu.Menu(me))
예제 #6
0
    def __init__(self, mgr, terminal):
        """Initialize the class."""
        self._mgr = mgr
        self._timer = timer.Timer()
        self._terminal = terminal

        font = load_font(LostState._FONT, LostState._MAIN_TEXT_HEIGHT)
        self._login_text = font.render('You have been locked out', True,
                                       constants.TEXT_COLOUR_RED)

        font = load_font(LostState._FONT, LostState._CONTINUE_TEXT_HEIGHT)
        self._continue_text = font.render('Press any key to continue', True,
                                          constants.TEXT_COLOUR_RED)

        self._login_text_coords = util.center_align(
            self._login_text.get_rect().w,
            self._login_text.get_rect().h + self._continue_text.get_rect().h)
        coords = util.center_align(self._continue_text.get_rect().w, 0)
        self._continue_text_coords = (coords[0], self._login_text_coords[1] +
                                      self._login_text.get_rect().h +
                                      LostState._SPACING)
예제 #7
0
    def __init__(self, mgr, entries):
        """Initialize the class."""
        super().__init__()
        self._mgr = mgr

        self._bezel = util.render_bezel(constants.VERSION_STRING)
        self._font = load_font(CLIMenu._TEXT_FONT, CLIMenu._TEXT_SIZE)
        self._selected_index = 0
        self._items = []
        self._cmds = {}

        # Create a '<' image to mark the selected item.
        self._select_marker = self._font.render(' <', True,
                                                CLIMenu._TEXT_COLOUR)
        self._buf = []
        y_coord = CLIMenu._TEXT_START[1]
        for entry in entries:
            # Render all the text up front, so that we can use the resulting
            # surfaces for hit-detection - we store a tuple containing:
            #   - The surface,
            #   - Its coordinates,
            #   - The menu item it represents, if any
            colour = CLIMenu._TEXT_COLOUR
            disabled = False
            if isinstance(entry, CLIMenuItem):
                line = entry.text
                item = entry.item

                if entry.disabled:
                    colour = CLIMenu._DISABLED_COLOUR
                    disabled = True
                else:
                    self._items.append(item)

                    # If this entry should start selected, set the
                    # selected-index appropriately.
                    if entry.selected:
                        self._selected_index = len(self._items) - 1

                    # If there's a command string associated with this item,
                    # render the text and store it in a dictionary mapping the
                    # item ID to the cmd text
                    if entry.cmd:
                        self._cmds[item] = self._font.render(
                            entry.cmd, True, CLIMenu._TEXT_COLOUR)
            else:
                line = entry
                item = None

            text = self._font.render(line, True, colour)
            self._buf.append(
                (text, (CLIMenu._TEXT_START[0], y_coord), item, disabled))
            y_coord += CLIMenu._TEXT_SIZE
예제 #8
0
def render_bezel(label, power_off=False):
    """Render the bezel and label text."""
    if power_off:
        bezel = load_image('media/bezel_off.png')
    else:
        bezel = load_image('media/bezel.png')
    text = load_font('media/fonts/METRO-DF.TTF', 19).render(
        label, True, (60, 60, 60))

    # Copy the bezel surface so we don't overwrite the stored cached surface in
    # the media manager.
    surf = bezel.copy()
    surf.blit(text, text_align(text, (725, 570), Align.CENTER))

    return surf
예제 #9
0
    def __init__(self, programs, prompt='$ ', time=300, depends=None):
        """Initialize the class."""
        # Public attributes
        self.locked = False
        self.id_string = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(4))

        # Current line without prompt. If current line with prompt is required,
        # use get_current_line(True)
        self._current_line = ""
        self._buf = deque(maxlen=Terminal._BUF_SIZE)
        self._prompt = prompt
        self._cmd_history = CommandHistory(self, maxlen=Terminal._HISTORY_SIZE)
        self._font = load_font(Terminal._TEXT_FONT, Terminal._TEXT_SIZE)
        self._has_focus = True

        # Timer attributes
        self._timer = timer.Timer()
        self._countdown_timer = CountdownTimer(time,
                                               Terminal._TIMER_WARNING_SECS)

        # Freeze attributes
        self._freeze_start = None
        self._freeze_time = None

        # Reboot attributes
        self._rebooting = False
        self._reboot_update_time = 0
        self._reboot_buf = deque()

        # Repeat key presses when certain keys are held.
        # Held key is a tuple of (key, key_unicode, start time)
        self._held_key = None
        self._key_last_repeat = None

        # Create instances of the programs that have been registered.
        self._programs = {c: p(self) for c, p in programs.items()}
        self._current_program = None
        self._depends = {} if depends is None else depends

        # Draw the monitor bezel
        self._bezel = render_bezel(self.id_string)
        self._bezel_off = render_bezel(self.id_string, power_off=True)

        self.reboot()
예제 #10
0
    def set_neighbours(self, neighbours):
        self.neighbours = neighbours

        # Count mines!
        self.mines_nearby = len(
            [n for n in neighbours if n.type == Square.Type.MINE])

        # Draw the number on our revealed surface
        if self.mines_nearby > 0:
            font = load_font(self._FONT, int(self.rect[2] * self._FONT_SCALE))
            text = font.render(str(self.mines_nearby), True, (0, 0, 0))

            surface = self._surfaces[Square.State.REVEALED]
            surface_rect = surface.get_rect()
            text_rect = text.get_rect()
            surface.blit(text, (int(surface_rect[2] / 2 - text_rect[2] / 2),
                                int(surface_rect[3] / 2 - text_rect[3] / 2)))
예제 #11
0
    def __init__(self, terminal):
        """Initialize the class."""
        super().__init__(terminal)
        self._completed = False
        self._user_info = random.choice(ImagePassword._USER_INFO)
        self._buttons = []
        self._lock_time = 0
        self._background = pygame.Surface(ImagePassword._BACKGROUND_SIZE)
        self._background.fill(ImagePassword._BACKGROUND_COLOUR)
        header = pygame.Surface(ImagePassword._HEADER_SIZE)
        header.fill(ImagePassword._HEADER_COLOUR)
        self._background.blit(header, ImagePassword._HEADER_POS)

        font = load_font(ImagePassword._HEADER_TEXT_FONT,
                         ImagePassword._HEADER_TEXT_SIZE)
        text = font.render("Select three images", True,
                           ImagePassword._HEADER_TEXT_COLOUR)
        self._background.blit(text, ImagePassword._HEADER_TEXT_POS)

        for coords in ImagePassword._BUTTON_COORDS:
            border_coords = (coords[0] - ImagePassword._BUTTON_BORDER_WIDTH -
                             ImagePassword._BACKGROUND_POS[0],
                             coords[1] - ImagePassword._BUTTON_BORDER_WIDTH -
                             ImagePassword._BACKGROUND_POS[1])
            border_size = (ImagePassword._BUTTON_SIZE +
                           ImagePassword._BUTTON_BORDER_WIDTH * 2)

            border = pygame.Surface((border_size, border_size))
            border.fill(ImagePassword._BUTTON_BORDER_COLOUR)
            self._background.blit(border, border_coords)

        self._correct_overlay = pygame.Surface(
            (ImagePassword._BUTTON_SIZE, ImagePassword._BUTTON_SIZE))
        self._correct_overlay.fill(ImagePassword._GUESSED_OVERLAY_COLOUR)
        self._correct_overlay.set_alpha(ImagePassword._GUESSED_OVERLAY_ALPHA)

        self._flash = pygame.Surface(ImagePassword._BACKGROUND_SIZE)
        self._flash.fill(ImagePassword._BACKGROUND_FLASH_COLOUR)
예제 #12
0
import resources

MAIN_MENU = resources.load_font('Medieval Sharp/MedievalSharp.ttf', 48)
MAIN = resources.load_font('Medieval Sharp/MedievalSharp.ttf', 36)
SMALL = resources.load_font('Medieval Sharp/MedievalSharp.ttf', 24)
MEDIEVAL18 = resources.load_font('Medieval Sharp/MedievalSharp.ttf', 18)
MONOSPACE = resources.load_font("LiberationMono/LiberationMono-Regular.ttf", 18)

예제 #13
0
    def _draw_contents(self):
        """Draw the terminal."""
        if self._rebooting:
            # If we're rebooting, don't draw the prompt
            current_line = ""
        elif self._freeze_time is not None:
            # If terminal freeze is enabled, then update progress bar to
            # indicate how long there is left to wait, using this as the
            # current line.
            done = ((self._timer.time - self._freeze_start) *
                    100) / self._freeze_time
            remain = int((100 - done) * self._PROGRESS_BAR_SIZE / 100)
            current_line = ("[" + "!" * (self._PROGRESS_BAR_SIZE - remain) +
                            " " * remain + "]")
        else:
            current_line = self.get_current_line(True)

        # If program has its own buf, then use it
        if (self._current_program is not None
                and self._current_program.PROPERTIES.alternate_buf):
            buf = self._current_program.buf
        else:
            buf = self._buf

        # Draw the buffer.
        y_coord = Terminal._TEXT_START[1]
        first_line_height = None
        for line in list(itertools.chain([current_line],
                                         buf))[:self._VISIBLE_LINES]:
            # Set defaults before checking whether the line overrides.
            colour = Terminal._TEXT_COLOUR
            size = Terminal._TEXT_SIZE
            fontname = ""

            # Look for any font commands at the start of the line.
            pattern = re.compile(r'<(. [^>]+?)>')
            m = pattern.match(line)
            while m:
                # Don't display the commands
                line = line[len(m.group(0)):]
                cmd, arg = m.group(1).split()
                if cmd == 'c':
                    # Change the colour code.
                    colour = Terminal._TEXT_COLOURS[arg]
                elif cmd == 's':
                    size = int(arg)
                elif cmd == 'f':
                    # Don't load the font yet, as we need to know which
                    # size to load, and the size cmd might come after the
                    # font command
                    fontname = arg

                m = pattern.match(line)

            if fontname:
                font = load_font(fontname, size)
            else:
                font = self._font

            # The height of the rendered text can sometimes be quite different
            # to the 'size' value used. So use the rendered height with a 2
            # pixel padding each side
            line_height = font.size(line)[1] + 4
            if first_line_height is None:
                first_line_height = line_height

            y_coord -= line_height

            text = font.render(line, True, colour)
            pygame.display.get_surface().blit(
                text, (Terminal._TEXT_START[0], y_coord))

        # Determine whether the cursor is on.
        if ((self._current_program is None
             or not self._current_program.PROPERTIES.hide_cursor)
                and not self._rebooting
                and (self._timer.time %
                     (Terminal._CURSOR_ON_MS + Terminal._CURSOR_OFF_MS) <
                     Terminal._CURSOR_ON_MS)):
            first_line_size = self._font.size(current_line)
            pygame.draw.rect(pygame.display.get_surface(),
                             Terminal._TEXT_COLOUR,
                             (Terminal._TEXT_START[0] + first_line_size[0] + 1,
                              Terminal._TEXT_START[1] - first_line_height - 1,
                              Terminal._CURSOR_WIDTH, first_line_size[1]),
                             0 if self._has_focus else 1)