Exemple #1
1
def main():
    """Main program loop"""
    
    pygame.init()
    screen = pygame.display.set_mode(opt.window_size)
    
    sys_font = Font(get_default_font(), opt.font_size)
    clock = Clock()
    
    manager = YarsManager()

    running = True
    
    while running:
        #limit framerate and prepare FPS display text
        clock.tick(opt.max_framerate)
        fps = clock.get_fps()
        fps_text = sys_font.render("FPS: {0:.1f}".format(fps), False, opt.white)
        
        if event.get(pygame.QUIT):
            sys.exit()

        running = manager.handle_events(event.get(), key.get_pressed())
        manager.update()

        screen.fill(opt.black)
        manager.draw(screen)
        screen.blit(fps_text, fps_text.get_rect(top = 0, right = opt.width))
        pygame.display.update()
		
    sys.exit()
class Text(object):
    def __init__(self,
                 text=None,
                 color=None,
                 batch=None,
                 size=None,
                 background=None):
        self.font_obj = Font('freesansbold.ttf', 28 if not size else size)
        self.text = text if text else ""
        self.color = color if color else RED
        self.batch = batch
        self.background = background
        self.sprite = Sprite(
            self.font_obj.render(self.text, True, self.color, self.background),
            self.batch)
        self.draw = self.sprite.draw

    def update(self, text):
        self.text = text
        self.sprite.surface = self.font_obj.render(self.text, True, self.color,
                                                   self.background)

    def set_center(self, x_pos, y_pos=None):
        self.sprite.set_center(x_pos, y_pos)

    def get_rect(self):
        return self.sprite.rect
Exemple #3
0
def game_over(screen, game_settings):

        screen_rect = screen.get_rect()
        screen.fill((213, 213, 213))
        
        #Create title splash
        title_font = Font(None, 72)
        title_text = 'game over'.upper()
        title_surface = title_font.render(title_text, True, (255, 15, 35))
        title_rect = title_surface.get_rect()

        #Create score splash
        score_font = Font(None, 60)
        score_text = 'Score: {scr}'.format(scr = game_settings.score)
        score_surface = title_font.render(score_text, True, (255, 15, 35))
        score_rect = score_surface.get_rect()

        #Position surfaces
        title_rect.centerx = screen_rect.centerx
        title_rect.centery = 150

        score_rect.centerx = screen_rect.centerx
        score_rect.centery = 250

        screen.blit(title_surface, title_rect)
        screen.blit(score_surface, score_rect)
        pygame.display.flip()
        pygame.time.wait(10000)
        return False
Exemple #4
0
class LcarsText(LcarsWidget):
    """Text that can be placed anywhere"""
    def __init__(self,
                 colour,
                 pos,
                 message,
                 size=1.0,
                 background=None,
                 handler=None):
        self.colour = colour
        self.background = background
        self.font = Font("assets/swiss911.ttf", int(19.0 * size))

        self.renderText(message)
        # center the text if needed
        if (pos[1] < 0):
            pos = (pos[0], 400 - self.image.get_rect().width / 2)

        LcarsWidget.__init__(self, colour, pos, None, handler)

    def renderText(self, message):
        if (self.background == None):
            self.image = self.font.render(message, True, self.colour)
        else:
            self.image = self.font.render(message, True, self.colour,
                                          self.background)

    def setText(self, newText):
        self.renderText(newText)
    def __init__(self, x, y, width, height, msg, size=16, 
            text_colour=base.BLACK, bg_colour=base.WHITE, 
            highlight_text=base.WHITE, highlight_bg=base.BLACK,
            offset_x=0, offset_y=0, bold=False):

        self.normal = pygame.Surface((width, height))
        self.normal.fill(bg_colour)

        font = Font(_FONT, size)
        font.set_bold(bold)
        font_width, font_height = font.size(msg)
        font_x = (width - font_width) / 2
        font_y = (height - font_height) / 2

        self.normal.blit(font.render(msg, False, text_colour), 
                                    (font_x, font_y))

        self.highlighted = pygame.Surface((width, height))
        self.highlighted.fill(highlight_bg)
        self.highlighted.blit(font.render(msg, False, highlight_text), 
                                        (font_x, font_y))

        self.offset_x = offset_x
        self.offset_y = offset_y
        
        self.force_highlight = False
        self.disabled = False
        PicassoAsset.__init__(self, self.normal, x, y)
def start_change_name():
    global process_mode, name_sprites, change_name_close, change_name_window, change_name_ok, change_name_error
    global change_name_error_font, change_name_font, change_name_line, change_name_NAME

    process_mode = 'changeName'
    change_name_NAME = ''

    name_sprites = Group()

    change_name_window = NameWindow()
    change_name_ok = NameOkButton()
    change_name_close = NameCloseButton()
    name_sprites.add(change_name_window)
    name_sprites.add(change_name_ok)
    name_sprites.add(change_name_close)

    name_sprites.draw(main_screen)

    change_name_error_font = Font(font, 25)
    change_name_error = change_name_error_font.render(
        'Имя может содержать только латинские буквы и цифры', 0, font_color)

    change_name_font = Font(font, 50)
    change_name_line = change_name_font.render('', 0, font_color)

    pygame.display.flip()
Exemple #7
0
    def get_song_elements(self, screen):
        width = 400
        height = 40
        divider = 50
        x = cfg.WIDTH // 2 - width // 2
        y = 50
        font = Font(None, 30)
        text_render = []

        text_render.append(
            font.render("yanaginagi - Haru Modoki", True, (255, 255, 255)))
        text_render.append(font.render("0", True, (255, 255, 255)))
        text_render.append(
            font.render("Giga-P - hibikase", True, (255, 255, 255)))
        self.song = pygame.draw.rect(screen, "red", (x, y, width, height))
        self.song1 = pygame.draw.rect(screen, "red",
                                      (x, y + divider, width, height))
        self.song2 = pygame.draw.rect(screen, "red",
                                      (x, y + divider * 2, width, height))

        x += 100
        y += 10
        for i in text_render:
            screen.blit(i, i.get_rect(topleft=(x, y)))
            y += divider
Exemple #8
0
class ScoreCounter(Sprite):
    def __init__(self, player, score, screen, font_name, size, color):
        super(ScoreCounter, self).__init__()
        self.screen = screen
        self.score = score
        self.color = color
        self.font = Font(font_name, size)
        self.image = self.font.render(str(self.score), True, self.color)
        self.rect = self.image.get_rect()
        self.player = player
        self.increased = False

    def update(self):
        if self.increased:
            self.image = self.font.render(str(self.score), True, self.color)
            self.rect = self.image.get_rect()
            self.increased = False
        self.rect.midtop = (self.player.rect.centerx,
                            self.player.rect.centery + 7)

    def blitime(self):
        self.screen.blit(self.image, self.rect)

    def score_kill(self, victim):
        self.score += victim.config.value
        self.increased = True
Exemple #9
0
    def draw(win: Surface, font: Font):
        pygame.draw.rect(win, BLACK_SQUARE_COLOR, BOARD_RECT_WITH_MARGIN)
        pygame.draw.rect(win, WHITE_SQUARE_COLOR, BOARD_RECT, 5)
        for i in range(8):  # Ranks
            text_surf: Surface = font.render(f"{8 - i}", True,
                                             WHITE_SQUARE_COLOR)
            text_rect: pygame.Rect = text_surf.get_rect()
            text_rect.center = (BOARD_LEFT - BOARD_MARGIN // 2,
                                BOARD_TOP + SQUARE * i + SQUARE // 2)
            win.blit(text_surf, text_rect)

        for j in range(8):  # Files
            text_surf: Surface = font.render(f"{chr(65 + j)}", True,
                                             WHITE_SQUARE_COLOR)
            text_rect: pygame.Rect = text_surf.get_rect()
            text_rect.center = (BOARD_LEFT + SQUARE * j + SQUARE // 2,
                                BOARD_TOP + 8 * SQUARE + BOARD_MARGIN // 2)
            win.blit(text_surf, text_rect)
        for x in range(8):
            for y in range(8):
                color = BLACK_SQUARE_COLOR if (x +
                                               y) % 2 else WHITE_SQUARE_COLOR
                rect = (BOARD_LEFT + x * SQUARE, BOARD_TOP + y * SQUARE,
                        SQUARE, SQUARE)
                pygame.draw.rect(win, color, rect)
class LcarsText(LcarsWidget):
    def __init__(self, colour, pos, message, size=1.0,
                 background=None, resolution=(480, 320)):
        self.colour = colour
        self.message = message
        self.background = background
        script_dir = dirname(__file__)
        ipath = join(script_dir, '../../assets/swiss911.ttf')
        self.font = Font(ipath, int(19.0 * size))

        self.renderText(message)
        # center the text if needed
        if (pos[1] < 0):
            # Screen specific magic number below! 240 = half width
            pos = (pos[0], resolution[0]/2 - self.image.get_rect().width/2)

        LcarsWidget.__init__(self, colour, pos, None)

    def renderText(self, message):
        if (self.background is None):
            self.image = self.font.render(message, True, self.colour)
        else:
            self.image = self.font.render(message, True,
                                          self.colour, self.background)

    def setText(self, newText):
        self.message = newText
        self.renderText(newText)

    def changeColour(self, colour):
        self.colour = colour
        self.renderText(self.message)
Exemple #11
0
    def __init__(self, manager):
        GameState.__init__(self, manager)

        sys_font = Font(get_default_font(), options.font_size)
        self.message1 = sys_font.render("Andrew's Bitchin' Yars' Revenge Clone",
                                        True, options.white)
        self.message2 = sys_font.render("Press shoot button (space) to start.",
                                        True, options.white)
Exemple #12
0
class Menu:
	def __init__(self, x, y, fontsize, space, color_fg, color_bg, background, titles):
		self.titles = titles
		self.images = []
		self.rects = []
		self.himages = []
		self.color_fg = color_fg
		self.color_bg = color_bg
		self.space = space
		self.background = data.load_image(background)
		self.index = 0
		self.x = x
		self.y = y
		self.font = Font(data.filepath('fonts', 'vera.ttf'), fontsize)
		self.font.set_bold(True)
		self.fonth = Font(data.filepath('fonts', 'vera.ttf'), fontsize+5)
		self.fonth.set_bold(True)
		
	def init(self):
		
		dy = 0
		for title in self.titles:
			image = self.font.render(title, True, self.color_bg)
			himage = self.fonth.render(title, True, self.color_fg)
			rect = image.get_rect()
			rect.move_ip(self.x, self.y + dy)
			dy += rect.height + self.space
			self.images.append(image)
			self.himages.append(himage)
			self.rects.append(rect)
				
	def run(self, screen):
		def blit(screen):
			screen.blit(self.background, (0,0))
			for image, rect in zip(self.images, self.rects):
				if image != self.images[self.index]:
					screen.blit(image, rect)
			screen.blit(self.himages[self.index], self.rects[self.index])
			pygame.display.update()
		
		done = False
		blit(screen)
		while not done:
			for event in pygame.event.get():
				if event.type == QUIT:
					sys.quit()
				if event.type == KEYDOWN:
					if event.key == K_DOWN:
						self.index = min(self.index+1, len(self.images)-1)
						blit(screen)
					if event.key == K_UP:
						self.index = max(self.index-1, 0)
						blit(screen)
					if event.key == K_RETURN:
						done = True
		return self.index
Exemple #13
0
class LcarsText(LcarsWidget):
    """Text that can be placed anywhere"""
    def __init__(
        self,
        colour,
        pos,
        message,
        textSize=None,
        background=None,
        handler=None,
        fontFace=None
    ):  #textSize=.75 & fontFace="assets/OpenSansCondensed-Light.ttf"):
        self.colour = colour
        self.currcolour = colour
        self.background = background
        self.togglevalue = False
        if textSize == None and fontFace == None:
            self.font = _defaulttextfont
        else:
            if textSize == None:
                textSize = .75
            if fontFace == None:
                fontFace = "assets/OpenSansCondensed-Light.ttf"
            self.font = Font(fontFace, int(50.0 * textSize))
        self.renderText(message)
        if (pos[1] < 0):
            pos = (pos[0], (config.RESOLUTION[0] / 2) -
                   self.image.get_rect().width / 2)

        LcarsWidget.__init__(self, colour, pos, None, handler)
        self.beep = Sound("assets/audio/panel/202.wav")

    def renderText(self, message):
        if (self.background == None):
            self.image = self.font.render(message, True, self.colour)
        else:
            self.image = self.font.render(message, True, self.colour,
                                          self.background)

    def setText(self, newText):
        self.renderText(newText)

    def changeColour(self, newColour):
        if self.currcolour != newColour:
            self.applyColour(newColour, self.currcolour)
            self.currcolour = newColour

    def handleEvent(self, event, clock):
        if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)
                and self.visible == True):
            self.beep.play()

        if (event.type == MOUSEBUTTONUP and self.visible == True):
            self.togglevalue = not self.togglevalue

        return LcarsWidget.handleEvent(self, event, clock)
Exemple #14
0
class TextBar(Sprite):
    def __init__(self, text, rect, fontSize):
        Sprite.__init__(self)
        self.font = Font(None, fontSize)
        self.rect = Rect(rect)
        self.image = pygame.surface.Surface((rect[2],
                                             rect[3]))
        self.image = self.font.render(text, 0, TEXTCOLOR)
    def setText(self, text):
        self.image = self.font.render(text, 0, TEXTCOLOR)
Exemple #15
0
class TextBar(Sprite):
    def __init__(self, text, rect, fontSize):
        Sprite.__init__(self)
        self.font = Font(None, fontSize)
        self.rect = Rect(rect)
        self.image = pygame.surface.Surface((rect[2], rect[3]))
        self.image = self.font.render(text, 0, TEXTCOLOR)

    def setText(self, text):
        self.image = self.font.render(text, 0, TEXTCOLOR)
Exemple #16
0
 def update_cloud(
     self
 ):  # adding 'Update avilable' text to cloud when a new version of the game is available
     font = Font(self.__game_env.static.game_font, 14)
     txt_update_surf = font.render(
         ' Update', 1, self.__game_env.static.text_default_color)
     txt_available_surf = font.render(
         ' Available', 1, self.__game_env.static.text_default_color)
     self.surf.blit(txt_update_surf, (12, 13))
     self.surf.blit(txt_available_surf, (5, 23))
     self.__speed = 2
Exemple #17
0
def render_center_info(board_render):
    center_info_surface = Surface((250, 250))
    match = board_render.match
    group = LayeredUpdates()

    # Background
    info_rect = Rect(0, 0, 250, 250)
    info_rect.center = board_render.surface.get_rect().center
    pygame.draw.rect(center_info_surface, (0, 0, 0), info_rect)

    current_path = os.path.dirname(os.path.realpath(__file__))
    font_path = os.path.join(
        current_path, "..", "..", "resources", "fonts", "SourceSans3-Semibold.ttf"
    )
    font = Font(font_path, 30)
    large_font = Font(font_path, 42)

    # Round Title
    round_text = "{} {}".format("East" if match.east_prevalent else "South", match.round_number)
    round_surface = font.render(round_text, True, (255, 255, 255))
    round_sprite = Sprite()
    round_sprite.image = round_surface
    round_sprite.rect = round_surface.get_rect()
    round_sprite.rect.center = info_rect.center
    round_sprite.rect.y -= (round_surface.get_rect().height // 2)
    round_sprite.layer = 1
    group.add(round_sprite)

    # Tiles Left in Wall
    tile_count_surface = large_font.render(str(len(match.current_board.wall)), True, (255, 255, 255))
    wall_remaining_sprite = Sprite()
    wall_remaining_sprite.image = tile_count_surface
    wall_remaining_sprite.rect = tile_count_surface.get_rect()
    wall_remaining_sprite.rect.center = info_rect.center
    wall_remaining_sprite.rect.y += (tile_count_surface.get_rect().height // 3)
    wall_remaining_sprite.layer = 1
    group.add(wall_remaining_sprite)

    # Wind Markers
    create_wind_markers(match, info_rect, group)

    # Turn Marker
    create_turn_marker(match, info_rect, group)

    # Riichi Markers
    create_riichi_markers(match, info_rect, group)

    background_sprite = Sprite()
    background_sprite.rect = info_rect
    background_sprite.image = center_info_surface
    background_sprite.layer = 0
    group.add(background_sprite)
    return group
Exemple #18
0
 def print_scores(self):
     self.screen.fill(Color('#153515'))
     self.screen.blit(self.logo, (30, 0))
     self.screen.blit(self.img1, (700, 300))
     self.screen.blit(self.back, (50, 690))
     font = Font('Resources\\font.ttf', 30)
     for i in range(len(self.tabl)):
         s = self.tabl[i]
         label = font.render(s[0], True, (255, 180, 0))
         self.screen.blit(label, (350, 240 + i * 50))
         label = font.render(str(s[1]), True, (255, 210, 0))
         self.screen.blit(label, (600, 240 + i * 50))
     update()
Exemple #19
0
    def __init__(self, x, y, width, height, msg, size=32, 
            text_colour=base.BLACK, bg_colour=base.WHITE, 
            highlight_text=base.WHITE, highlight_bg=base.BLACK):

        font = Font(None, size)
        self.normal = pygame.Surface((width, height))
        self.normal.fill(bg_colour)
        self.normal.blit(font.render(msg, False, text_colour), (0, 0))
    
        self.highlighted = pygame.Surface((width, height))
        self.highlighted.fill(highlight_bg)
        self.highlighted.blit(font.render(msg, False, highlight_text), (0, 0))
        PicassoAsset.__init__(self, self.normal, x, y)
Exemple #20
0
    def __init__(self, drawFont: font.Font, width=750, height=550):
        self.current_page = 0
        self.pages = [Surface((width, height))]
        self.pages[0].fill(colour.WHITE)
        drawArea = rect.Rect(5, 5, width - 5, height - 5)

        wordHorizontalSpacing = 5
        wordVerticalSpacing = 2
        leftMargin = 10
        topMargin = 7
        wordXOffset = leftMargin
        wordYOffset = topMargin
        for line in help_text.split('\n'):
            for word in line.split():

                if word == '[p]':
                    wordXOffset = leftMargin
                    wordYOffset = topMargin
                    self.pages.append(Surface((width, height)))
                    self.pages[-1].fill(colour.WHITE)
                    continue
                renderedWord = drawFont.render(word, True, colour.BLACK)

                if wordXOffset + renderedWord.get_width(
                ) + wordHorizontalSpacing > drawArea.width:
                    wordXOffset = leftMargin
                    wordYOffset += wordVerticalSpacing + renderedWord.get_height(
                    )

                if wordYOffset + renderedWord.get_height(
                ) + wordVerticalSpacing > drawArea.height:
                    wordYOffset = topMargin
                    self.pages.append(Surface((width, height)))
                    self.pages[-1].fill(colour.WHITE)

                self.pages[-1].blit(renderedWord, (wordXOffset, wordYOffset))

                wordXOffset += wordHorizontalSpacing + renderedWord.get_width()

            wordYOffset += drawFont.get_height() + wordVerticalSpacing
            wordXOffset = leftMargin

        for i, v in enumerate(self.pages):
            pageNumberRender = drawFont.render(
                "<- Page %d of %d ->" % (i + 1, len(self.pages)), True,
                colour.BLACK)

            v.blit(pageNumberRender,
                   (v.get_width() - pageNumberRender.get_width() - 3,
                    v.get_height() - pageNumberRender.get_height() - 3))
Exemple #21
0
class Screen:
    """
    The screen manager for a game of Pong.
    """

    WINDOW_TITLE = "PyPong"

    SCREEN_WIDTH = 450
    SCREEN_HEIGHT = 300
    FONT_SIZE = 50

    BACKGROUND_COLOR = (0, 0, 0)
    BACKGROUND_EFFECTS_COLOR = (255, 255, 255)
    OBJECT_COLOR = (0, 255, 20)

    MIDLINE_START = (SCREEN_WIDTH / 2, 0)
    MIDLINE_STOP = (SCREEN_WIDTH / 2, SCREEN_HEIGHT)
    SCORE1_POS = (SCREEN_WIDTH / 4, SCREEN_HEIGHT / 6)
    SCORE2_POS = (SCREEN_WIDTH * 3 / 4, SCREEN_HEIGHT / 6)

    def __init__(self):
        self.screen = self._initialize_window()
        self.font = Font(None, self.FONT_SIZE)

    def _initialize_window(self):
        screen = display.set_mode(self.screen_dimensions())
        display.set_caption(self.WINDOW_TITLE)
        return screen

    def screen_dimensions(self):
        return self.SCREEN_WIDTH, self.SCREEN_HEIGHT

    def render_screen(self, game):
        self._render_background(game.score1, game.score2)
        for game_object in [game.ball, game.paddle1, game.paddle2]:
            draw.rect(self.screen, self.OBJECT_COLOR, game_object)
        display.flip()

    def _render_background(self, score1, score2):
        self.screen.fill(self.BACKGROUND_COLOR)
        draw.line(self.screen, self.BACKGROUND_EFFECTS_COLOR,
                  self.MIDLINE_START, self.MIDLINE_STOP)

        score1_text = self.font.render(str(score1), True,
                                       self.BACKGROUND_EFFECTS_COLOR)
        score2_text = self.font.render(str(score2), True,
                                       self.BACKGROUND_EFFECTS_COLOR)
        self.screen.blit(score1_text, self.SCORE1_POS)
        self.screen.blit(score2_text, self.SCORE2_POS)
Exemple #22
0
    def __init__(self, context: Context):
        Scene.__init__(self, context)
        board_position = (0, 125)
        title_position = (200, 250)
        title = "You didn't achieve your target"
        button_position = (200, 400)
        button_text = "Start again"

        self.background = self.context.assets["board_image"]
        self.background_rect = self.background.get_rect(topleft=board_position)
        font = Font(None, 48)
        self.title = font.render(title, True, Color(255, 255, 255))
        self.title_rect = self.title.get_rect(center=title_position)
        self.button = font.render(button_text, True, Color(255, 255, 255))
        self.button_rect = self.button.get_rect(center=button_position)
Exemple #23
0
def main():
    """The main function of the game.
    Initializes PyGame objects and then enters the game loop
    """
    
    pygame.init()
    screen = pygame.display.set_mode(window_size)
    
    sys_font = Font(get_default_font(), font_size)
    clock = Clock()
    
    #now that pygame is initialized, initialize inherited classes properly
    global enemy_wave, player
    enemy_wave = EnemyGroup(evil_bullets)
    
    player = Player(window_size, ship_filename, ship_speed)
    
    while 1:
        #limit framerate and prepare FPS display text
        clock.tick(max_framerate)
        fps = clock.get_fps()
        fps_text = sys_font.render("FPS: {0:.1f}".format(fps), False, white)
        
        score_text = sys_font.render("SCORE: {}".format(score), False, white)
        lives_text = sys_font.render("MANS: {}".format(lives), False, white)
    
        #check for QUIT event to prevent endless loopage
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            
        #call the game's thinking functions
        check_gameover()
        keyboard()
        evil_bullets.update()
        good_bullets.update()
        enemy_wave.update()
        collisions()
            
        #draw the stuff
        screen.fill(black)
        good_bullets.draw(screen)
        evil_bullets.draw(screen)
        enemy_wave.draw(screen)
        screen.blit(player.image, player.rect)
        screen.blit(score_text, score_text.get_rect(top = 0, left = 0))
        screen.blit(lives_text, lives_text.get_rect(top = 0, centerx = width / 2))
        screen.blit(fps_text, fps_text.get_rect(top = 0, right = width))
        pygame.display.update()
Exemple #24
0
class Subtitle:
    """Subtitle attributes, not as big as title"""
    def __init__(self,
                 bg_color,
                 screen,
                 text,
                 text_size=48,
                 text_color=(0, 255, 0)):
        self.bg_color = bg_color
        self.screen = screen
        self.text = text
        self.text_color = text_color
        self.font = Font('fonts/Retravant Garden.ttf', text_size)
        self.image = None
        self.image_rect = None

    def apply_image(self):
        """Allow for text to be image to display"""
        self.image = self.font.render(self.text, True, self.text_color,
                                      self.bg_color)
        self.image_rect = self.image.get_rect()

    def blitme(self):
        """Display and show on the screen"""
        self.screen.blit(self.image, self.image_rect)
Exemple #25
0
def main():
    """
    use pygame to convert a TTF to BMP
    """
    if len(sys.argv) < 3:
        print("Usage: {} <TTF-file> <size>".format(sys.argv[0]))
        exit(1)

    fname = sys.argv[1]
    fsize = int(sys.argv[2])

    outname = "{}_{}.BMP".format(os.path.splitext(fname)[0], fsize)

    print("Loading font {} in height {}...".format(fname, fsize))
    init()
    f = Font(fname, fsize)

    print("Rendering {} characters '{}'".format(len(RENDER_STRING), RENDER_STRING))
    width = None
    for ch in RENDER_CHARS:
        w, h = f.size(str(ch))
        if width is None:
            width = w
        if w != width:
            print("ERROR: Font is not monospaced!")
            exit(1)

    surface = f.render(RENDER_STRING, False, (255, 255, 255), (0, 0, 0))

    print("Writing rendered characters to '{}'...".format(outname))
    image.save(surface, outname)
Exemple #26
0
    def __init__(self,
                 screen,
                 text=None,
                 x=0,
                 y=0,
                 width=100,
                 height=50,
                 action=None):
        """Initiation of object button"""
        super().__init__()

        #Some defaults
        self.color = (170, 170, 170)
        self.highlight_color = (200, 200, 200)
        self.click_color = (130, 130, 130)
        self.current_color = self.color
        self.border_color = (0, 193, 193)
        self.text = text
        self.text_color = (0, 0, 0)
        self.text_size = 36

        self.screen = screen
        self.rect = pygame.Rect(x, y, width, height)
        self.action = action

        #Set text on button
        if self.text != None:
            f = Font(None, self.text_size)
            self.text_img = f.render(self.text, True, self.text_color)
            self.text_rect = self.text_img.get_rect()
            self.rect.width = self.text_rect.width + self.text_size
            self.rect.height = self.text_rect.height + self.text_size
Exemple #27
0
class CreditsScreen:
    def __init__(self, screen):
        self.bg_color = (0, 0, 0)
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.bowsette = Timer([pygame.image.load('images/player/bowsette1.png'),
                               pygame.image.load('images/player/bowsette2.png'),
                               pygame.image.load('images/player/bowsette3.png'),
                               pygame.image.load('images/player/bowsette4.png')], wait=200)
        self.bowsette_rect = self.bowsette.frames[0].get_rect()
        self.font = Font(None, 32)
        self.text_color = (255, 255, 255)
        self.text = self.font.render('Thank you for playing.', True, self.text_color, self.bg_color)
        self.text_rect = self.text.get_rect()
        self.text_box_color = (255, 255, 255)
        self.text_box = pygame.Rect(0, 0, self.text_rect.width + 5, self.text_rect.height + 5)
        self.text_box.centerx = 510
        self.text_box.centery = 550
        self.text_rect.center = self.text_box.center
        self.bowsette_rect.bottom = 625
        self.bowsette_rect.centerx = self.text_rect.centerx
        self.bg_image = pygame.image.load('images/credits_screen.png')
        # self.bg_image = pygame.transform.scale(self.bg_image, self.screen_rect.size)

    def draw(self):
        self.screen.fill(self.text_box_color, self.text_box)
        self.screen.blit(self.bg_image, self.screen_rect)
        self.screen.blit(self.text, self.text_rect)
        self.screen.blit(self.bowsette.imagerect(), self.bowsette_rect)
 def rect_setup(self, button_width, button_height):
     ''' works out menu button positions and font sizes, iterates down
     from a large size so that it finds the largest size that fits the text
     for all the buttons nicely. Preferably the button strings should vary 
     too much in length'''
     surf_midpoint = (int(0.5 * self.surf_width),
                      int(0.5 * self.surf_height))
     text_size = Menu.INITIAL_TEXT_SIZE
     font = Font(None, text_size)
     rect_list = []
     for i in range(self.num_buttons):
         button_pos = (surf_midpoint[0] - button_width / 2,
                       surf_midpoint[1] +
                       (button_height *
                        (i - self.num_buttons / 2)) * Menu.BUTTON_SPACING)
         rect = Rect(button_pos, (button_width, button_height))
         rect_list.append(rect)
         while (font.size(self.button_strings[i])[0] >=
                (button_width * Menu.FONT_MARGIN)
                or font.size(self.button_strings[i])[1] >=
                (button_height * Menu.FONT_MARGIN)):
             text_size -= 1
             font = Font(None, text_size)
     self.button_rects = rect_list
     self.button_text = [
         font.render(s, 1, BLACK) for s in self.button_strings
     ]
     self.button_text_pos = [(self.button_rects[i].center[0] -
                              self.button_text[i].get_size()[0] / 2,
                              self.button_rects[i].center[1] -
                              self.button_text[i].get_size()[1] / 2)
                             for i in range(self.num_buttons)]
Exemple #29
0
class TextSprite(Sprite):
    def __init__(self, text="", fontname=None, size=32):
        self.font = Font(fontname or pygame.font.get_default_font(), size)

        Sprite.__init__(self, None)
        self.text = text
        self.color = (0, 0, 0)
        self.set_text(text)

    # end of init

    def set_text(self, text, color=None):

        if (self.color != color or text != self.text):
            self.need_draw = True

        self.text = text
        self.color = color or (255, 255, 255)

        if (self.text):
            self.image = self.font.render(text, True, self.color)
        else:
            self.image.fill((255, 255, 255, 0))

        self.rect = self.image.get_rect()
        self.rect.x = self.pos[0]
        self.rect.y = self.pos[1]

    def set_color(self, color):
        self.set_text(self.text, color)
Exemple #30
0
class TotalTime(Sprite):
    """
    """

    FONT_SIZE = 30
    FONT_COLOR = (0, 0, 0)

    def __init__(self, position, background_color):
        super().__init__()

        self.time = 0
        self.font = Font(None, self.FONT_SIZE)
        self.background_color = background_color

        self.image = self._new_image()
        self.rect = self.image.get_rect()
        self.rect.topleft = position

    def update(self, static_groups, collectable_groups, time_delta):
        """
        """
        self.time += time_delta
        self.image = self._new_image()

    def _new_image(self):
        """
        """
        return self.font.render(self._time_string_format(self.time), True,
                                self.FONT_COLOR, self.background_color)

    def _time_string_format(self, time):
        """
        """
        mins, secs = divmod(time // 1000, 60)
        return "{:02}:{:02}".format(mins, secs)
Exemple #31
0
class labelSprite(Sprite):
    def __init__(self,
                 string,
                 offset,
                 fontsize=None,
                 color=(255, 255, 255),
                 *args):

        if fontsize is None:
            fontsize = uiLabelSizeHint

        Sprite.__init__(self, *args)
        self.font = Font(uiLabelFontName, fontsize)
        self.string = string
        self.color = color
        self.offset = offset

    def update(self):

        self.image = self.font.render(self.string, 1,
                                      self.color).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = self.offset

    def text(self, textOut):

        self.string = str(textOut)
Exemple #32
0
class MenuScreen(BaseScreen):

    def init_entities_before(self, surface):
        self.font = Font(None, 30)
        self.textImg = self.font.render(
            'Press SPACE to BEGIN !',
            1,
            (255,255,255)
        )
        surface.blit(self.textImg, (200,200))

    def execute(self, surface):
        if pygame.key.get_pressed()[SPACE] == 1:
            raise ChangeScreenException(1, 'Launch the game!')

    def erase_all_map(self):
        pass

    def draw(self, surface):
        pass
    
    def game_over(self, text, number=None):
        BaseScreen.erase_all_map(self)
        font = Font(None, 30)
        textImg = font.render(text, 1, (255,255,255))
        self.surface.blit(textImg, (200,100))
Exemple #33
0
class Clock(object):
    def __init__(self):
        self.time = 0
        self.last_time = "00:00"
        self.font = Font(None, 24)
        self.font_color = Color("blue")
        self.draw_clock_font(self.last_time)
        self.clock_image = None

    def update(self, delta):
        self.time += delta

    def draw(self, screen):
        minutes = "%02d" % int(self.time / 1000 / 60)
        seconds = "%02d" % int(self.time / 1000 % 60)
        time_string = minutes + ":" + seconds
        if not self.last_time == time_string:
            self.draw_clock_font(time_string)
        img_w = self.clock_img.get_width()
        img_h = self.clock_img.get_height()
        dest = Rect(32, 32, img_w, img_h)
        screen.blit(self.clock_img, dest)

    def draw_clock_font(self, time_string):
        self.clock_img = self.font.render(time_string, True, self.font_color)
Exemple #34
0
 def get_square(self, pos: Tuple[int], fnt: Font) -> bool:
     """
     Return True if the check button was selected and False otherwise. Rewrite the check box using font fnt. If
     the player selected a part of the screen that is not within the 9x9 grid then set selected to None, otherwise
     set selected to a list containing the row and column of the selected square. The selected position is given
     by pos where the first index is the x position and the second is the y position.
     """
     text = fnt.render("Check", 1, (0, 0, 0))
     rect_width = text.get_width() + 20
     rect_height = text.get_height() + 10
     x = self.gap_x + (50 * 3 - rect_width) // 2
     y = self.y_max + (self.gap_y - rect_height) // 2
     if x < pos[0] < x + rect_width and y < pos[1] < y + rect_height:
         # check button selected
         self.selected = None
         return True
     if pos[0] <= self.gap_x or pos[0] >= self.x_max or pos[
             1] <= self.gap_y or pos[1] >= self.y_max:
         # player clicked outside the grid
         self.selected = None
         return False
     # get the coordinates of the selected square
     row = (pos[0] - self.gap_x) // 50
     col = (pos[1] - self.gap_y) // 50
     self.selected = [row, col]
     return False
Exemple #35
0
class Counters(object):
    def __init__(self, pizza_bucks, buck_rate, buck_booster):
        self.loop_count = 0
        self.display_font = Font('assets/pizza_font.ttf', 25)
        self.pizza_bucks = pizza_bucks
        self.buck_rate = buck_rate
        self.buck_booster = buck_booster
        self.bucks_rect = None

    def increment_bucks(self):
        if self.loop_count % self.buck_rate == 0:
            self.pizza_bucks = self.pizza_bucks + self.buck_booster

    def draw_bucks(self, game_window):
        if bool(self.bucks_rect):
            game_window.blit(BACKGROUND,
                             (self.bucks_rect.x, self.bucks_rect.y),
                             self.bucks_rect)

        bucks_surf = self.display_font.render(str(self.pizza_bucks), True,
                                              WHITE)
        self.bucks_rect = bucks_surf.get_rect()
        self.bucks_rect.x = WINDOW_WIDTH - 50
        self.bucks_rect.y = WINDOW_HEIGHT - 50
        game_window.blit(bucks_surf, self.bucks_rect)

    def update(self, game_window):
        self.loop_count = self.loop_count + 1
        self.increment_bucks()
        self.draw_bucks(game_window)
Exemple #36
0
class TextButton(Button):
    def __init__(self, text, font_size, color=(255, 255, 255)):
        Button.__init__(self)
        self.font = Font(None, font_size)
        self.font_color = color
        self.image = self.font.render(text, True, self.font_color)
        self.rect = Rect(0, 0, self.image.get_width(), self.image.get_height())
Exemple #37
0
    def __init__(self, colour, shape, pos, text, handler=None):
        self.handler = handler

        # Load different image for shape
        if (shape == "nav"):
            image = pygame.image.load("assets/nav.png").convert()
        elif (shape == "btn"):
            image = pygame.image.load("assets/button.png").convert()

        size = (image.get_rect().width, image.get_rect().height)
        font = Font("assets/swiss911.ttf", 22)
        textImage = font.render(text, False, colours.BLACK)

        # Change text position
        if (shape == "nav"):
            image.blit(
                textImage,
                (image.get_rect().width - textImage.get_rect().width - 12,
                 image.get_rect().height - textImage.get_rect().height))
        elif (shape == "btn"):
            image.blit(
                textImage,
                (image.get_rect().width - textImage.get_rect().width - 10,
                 image.get_rect().height - textImage.get_rect().height - 5))

        self.image = image
        self.colour = colour
        LcarsWidget.__init__(self, colour, pos, size)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")
Exemple #38
0
class Label(Script):
    def __init__(self, arg):
        self.last_text = None
        self.text = arg.get('text', "")
        self.font = Font("assets/fonts/normal.ttf",
                         arg.get('size', DEFAULT_SIZE))

        self.text_entity = None

    def start(self):
        self.element = self.world.component_for_entity(self.entity, Element)

    def update(self, delta):
        if self.text != self.last_text:
            self.update_text()

    def update_text(self):
        from game.components import Sprite, Transform

        if self.text_entity != None:
            self.world.delete_entity(self.text_entity)
            self.text_entity = None

        self.last_text = self.text

        spr = self.font.render(self.text, False, (0, 0, 0))
        self.text_entity = self.world.create_entity(
            Element({
                'name': self.element.name + "_text",
                'pos': Vector2(self.element.pos.x, self.element.pos.y)
            }), Sprite(spr), Transform({'layer': 25}))
Exemple #39
0
    def __init__(self, manager, score, lives, next_state):
        GameState.__init__(self, manager)

        sys_font = Font(get_default_font(), options.font_size)
        self.score_text = sys_font.render(str(score), True, options.white)
        self.lives_text = sys_font.render(str(lives), True, options.white)

        self.next_state = next_state
Exemple #40
0
class TextInput(Sprite):
    """
    >>> import pygame
    >>> from color_picker import *
    >>> pygame.font.init()

    Set text
    >>> text = "Hello World!"
    >>> testRect = Rect((0,0),(20,20))
    >>> theInput = TextInput(text, testRect)
    >>> theInput.getText()
    'Hello World!'

    Add a character to a string
    >>> theInput.appendChar(103)
    >>> theInput.getText()
    'Hello World!g'

    Delete a character from a string
    >>> theInput.deleteChar()
    >>> theInput.getText()
    'Hello World!'
    """

    def __init__(self, text, rect, fontSize):
        Sprite.__init__(self)
        self.font = Font(None, fontSize)
        self.text = text
        self.rect = Rect(rect)
        self.image = self.font.render(text, 0, TEXTCOLOR2)

    def getText(self):
        return self.text

    def setText(self, text):
        self.text = text
        self.image = self.font.render(self.text, 0, TEXTCOLOR2)

    def appendChar(self, char):
        self.text = self.text + chr(char)
        self.image = self.font.render(self.text, 0, TEXTCOLOR2)
        
    def deleteChar(self):
        self.text = self.text[0:-1]
        self.image = self.font.render(self.text, 0, TEXTCOLOR2)
Exemple #41
0
 def render_text(self, msg):
     font = Font(_FONT, self.size)
     font.set_bold(self.bold)
     new_surface = pygame.Surface((self.width, self.height), 
                     pygame.SRCALPHA, 32)
     msg = msg.strip("\n")
     lines = msg.split("\n")
     longest = max(lines, key=lambda x: len(x))
     
     #new_surface = pygame.Surface((self.width, self.height))
     temp_surface = font.render(longest, False, self.colour)
     msg_width = temp_surface.get_size()[0]
     msg_height = font.get_height() * len(lines)
     msg_x = (new_surface.get_width() - msg_width) / 2
     msg_y = (new_surface.get_height() - msg_height) / 2
     for index, line in enumerate(lines):
         font_surface = font.render(line, False, self.colour)
         new_surface.blit(font_surface, (msg_x, 
                 msg_y + (font.get_height() * index)))
     self.surface = new_surface
Exemple #42
0
class LcarsText(LcarsWidget):
    def __init__(self, colour, pos, message, size=1.0, background=None):
        self.colour = colour
        self.background = background
        self.font = Font("assets/swiss911.ttf", int(19.0 * size))
        
        self.renderText(message)
        # center the text if needed 
        if (pos[1] < 0):
            pos = (pos[0], 400 - self.image.get_rect().width / 2)
            
        LcarsWidget.__init__(self, colour, pos, None)

    def renderText(self, message):        
        if (self.background == None):
            self.image = self.font.render(message, True, self.colour)
        else:
            self.image = self.font.render(message, True, self.colour, self.background)
        
    def setText(self, newText):
        self.renderText(newText)
	def display_message(screen, msg, x_center_delta=0, y_center_delta=0):
		center_x = (Helpers.const["size"]["display_width"] / 2) + x_center_delta
		center_y = (Helpers.const["size"]["display_height"] / 2) + y_center_delta
		msg_font =  Font(None, 30)

		screen_text = msg_font.render(msg, True, Helpers.const["color"]["white"])
		text_rect = screen_text.get_rect()
		text_rect.center = (center_x, center_y)
		
		screen.blit(screen_text, text_rect)
		pygame.display.update(text_rect)
		return text_rect
Exemple #44
0
 def draw_mouse_info(self, message, drawing=False):
     # Empty mouse canvas
     self.mouse_info_canvas.fill(self.background_color)
     
     # Create font and blit onto canvas
     font = Font(None, 22)
     mouse_info = font.render(message, 1, Colour.CHOCOLATE, Colour.BLACK)
     self.mouse_info_canvas.blit(mouse_info, (self.mouse_info_x, self.mouse_info_y))
     
     # If Mouse is dragging, notify
     if drawing:
         ti = Font(None, 30).render("DRAWING",1,Colour.CHOCOLATE, Colour.BLACK)
         self.mouse_info_canvas.blit(ti, (self.mouse_info_x, self.mouse_info_y+20))
Exemple #45
0
def gameover():
    """The gameover loop
    Shows static image until the window is closed
    """
    
    sys_font = Font(get_default_font(), font_size)
    message = sys_font.render("GAME OVER", False, white)
    screen = pygame.display.get_surface()
    screen.blit(message, message.get_rect(centerx = width/2, top = 20))
    pygame.display.update()
    while 1:
        keyboard()
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
Exemple #46
0
	def __init__(self, world_map):
		self.world_map = world_map
		self.group = Group()
		self.energy_bar = EnergyBar(world_map.main_character, 15, 10, self.group)
		self.energy_bar.put(75, 13)
		self.energy_bar = LifeBar(world_map.main_character, 15, 10, self.group)
		self.energy_bar.put(75, 30)
		
		self.rect = Rect(0, 0, SCREEN_W, 40)
		self.background = data.load_image('panel.png')
		font = Font(data.filepath('fonts', 'vera.ttf'), 12)
		#font.set_bold(True)
		self.twister_text = font.render("Twister:", True, (0,0,0))
		self.life_text = font.render("Life:", True, (0,0,0))
		self.world_text = font.render("World: %s" % world_map.name, True, (0,0,0))
		
		class TimeText(Sprite):
			def __init__(self, world_map, *groups):
				Sprite.__init__(self, *groups)
				self.world_map = world_map
			def update(self, *args):
				time = self.world_map.time
				time_str = self.world_map.get_time()
				if time < 60:
					color = (170, 0, 0)
				elif time < 120:
					color = (255, 100, 0)
				else:
					color = (0, 0, 0) 
				self.image = font.render("Time: %s"% time_str , True, color)
				self.rect = self.image.get_rect()
				self.rect.move_ip(500, 0)
				
		TimeText(world_map, self.group)
		self.key = KeyItem(world_map)
		self.key.put(620, 20)
		self.key.remove(self.key.groups())
Exemple #47
0
    def draw_field(self, screen, field, animation):
        from pygame.display import flip
        from pygame.font import Font

        screen.fill((50, 50, 30))
        font = Font(None, 20)
        self.movement_check(field)
        for ctrl_row in range(self.border_from[0], min(self.border_to[0] + 1, field.rows)):
            for ctrl_column in range(self.border_from[1], min(self.border_to[1] + 1, field.columns)):
                parameters = field.map[ctrl_row][ctrl_column][1].image_status()
                pixel = field.map[ctrl_row][ctrl_column][2][0] - self.border_pixel[0] + self.border_width, \
                        field.map[ctrl_row][ctrl_column][2][1] - self.border_pixel[1] + self.border_height
                if parameters[0]:
                    picture = list(field.map[ctrl_row][ctrl_column][1].virtual_image_name())
                    picture.append(self.size)
                    screen.blit(animation.get_image(picture), pixel)
                if parameters[3]:
                    parameters = list(parameters[3:])
                    parameters.append(self.size)
                    screen.blit(animation.get_image(parameters), pixel)
        for dynamic_object in field.objects.values():
            coord = dynamic_object.offset_coord
            if self.border_from[0] <= coord[0] <= self.border_to[0] and self.border_from[1] <= coord[1] <= \
                    self.border_to[1]:
                parameters = field.map[dynamic_object.offset_coord[0]][dynamic_object.offset_coord[1]][1].image_status()
                pixel = field.map[coord[0]][coord[1]][2][0] - self.border_pixel[0] + self.border_width, \
                        field.map[coord[0]][coord[1]][2][1] - self.border_pixel[1] + self.border_height
                if parameters[1]:
                    picture = list(dynamic_object.virtual_image_name())
                    picture.append(self.size)
                    screen.blit(animation.get_image(picture), pixel)
                    if parameters[2]:
                        text = font.render(str(dynamic_object.level), 1, (255, 255, 0))
                        screen.blit(text, pixel)
                        text = font.render(str(dynamic_object.health), 1, (255, 0, 0))
                        screen.blit(text, (pixel[0] + self.size[0] * 0.75, pixel[1]))
        flip()
class Font():
	def __init__(self,font,size):
		self.size = size
		self.font = PygameFont(os.path.dirname(sys.argv[0]) + "/fonts/" + font + ".ttf",size)
	def return_surface(self,label):
		surface = Surface(label.get_size())
		surface.data = image_to_string(label, "RGBA")
		return surface
	def render(self,text,colour):
		colour = fix_colour(colour)
		label = self.font.render(text, True, colour)
		return self.return_surface(label)
	def render_wordwrap(self,text,width,colour,alignment):
		label = render_textrect(text, self.font, width, colour, alignment)
		return self.return_surface(label)
Exemple #49
0
    def __init__(self, colour, pos, text, handler=None):
        self.handler = handler
        image = pygame.image.load("assets/button.png").convert()
        size = (image.get_rect().width, image.get_rect().height)
        font = Font("assets/swiss911.ttf", 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage, 
                   (image.get_rect().width - textImage.get_rect().width - 10,
                    image.get_rect().height - textImage.get_rect().height - 5))

        self.image = image
        self.colour = colour
        LcarsWidget.__init__(self, colour, pos, size)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")
Exemple #50
0
    def draw(self, surface):
       
        h = surface.get_height()
        w = surface.get_width()
        
        board = self.board
        
        if not self.pos:
            return
        
        (x, y) = self.pos
        x *= (board.bw / board.width)
        y *= (board.bh / board.height)
        
        self.radius = ((board.bh if board.bh < board.bw else board.bw) / board.width) / 4
        
        self.apos = (int(x+(self.radius*2)+board.offset[0]), int(y+(self.radius*2)+board.offset[1]))
        
        if self.selected and board.highlight_selected:
            color = (255, 80, 0)
            halo(surface, self.apos, self.radius, color, self.radius/2)
            
        elif self.possible_move and board.highlight_moves:
            color = (128, 255, 255)
            halo(surface, self.apos, self.radius, color, self.radius/2, False)
            
        elif self.empty:
            color = (128, 255, 255)
            circle(surface, self.apos, self.radius, color, 1)
            
        if not self.empty:
            color = (128, 255, 255)
            circle(surface, self.apos, self.radius, color)
        
        
        #draw links to other nodes
        if board.show_grid:
            from pygame.font import Font
            vera = Font('Resources\\fonts\\Vera.ttf',10)
            text_surface = vera.render(str(self.cord), True, (255, 255, 255))
            surface.blit(text_surface, (self.apos[0]+self.radius, self.apos[1]+self.radius))

            for n in self.links:
                if self.links[n].apos:
                    self.draw_link(surface, self.links[n])
        
        return self
Exemple #51
0
    def render(self, window):
        '''(SumTracker, Surface) -> NoneType
        Renders self.player.sum as text, with width, height given by
        generated font.'''
        WHITE = (255, 255, 255)
        BLACK = (0, 0, 0)
        FONT_SIZE = 20

        # Load the font into a Surface
        FONT = Font(None, FONT_SIZE) # Use default font
        SURFACE = FONT.render("{}: {}".format(self.text, self.player.sum), False, WHITE)

        # Clear old sum
        window.fill(BLACK, self.rect)

        # Render the font
        window.blit(SURFACE, self.rect)
Exemple #52
0
class UI(object):
    def __init__(self, grid):
        '''a UI right below the grid'''
        self.pos = (0, grid.rows * grid.row_height)
        self.font = Font(None, 12)
        self.background = pygame.Surface((grid.col_width * grid.cols, 100))
        self.background.fill(Color(255,255,255))

    def draw(self, screen, guys, enemies):
        screen.blit(self.background, self.pos)

        x, y = self.pos
        for (x, desc, list) in [(x, 'cool guy', guys), (x + 200, 'enemy', enemies)]:
            guynum = 0
            for guy in list:
                str = '%s #%s: %s%%' % (desc, guynum + 1, guy.health)
                text = self.font.render(str, True, pygame.Color(0,0,0))
                screen.blit(text, (x, y + guynum * 13))
                guynum += 1
Exemple #53
0
class Drawable(DirtySprite):
    def __init__(self, string, color, location, size):
        DirtySprite.__init__(self)

        self.string = string
        self.color = color
        self.location = location

        self.font = Font(pygame.font.get_default_font(), size)

        self.regen_sprite()

    def _gen_surface(self):
        return self.font.render(self.string, True, self.color)

    def regen_sprite(self):
        self.image = self._gen_surface()
        self.rect = Rect(self.location, self.image.get_size())
        self.dirty = 1
class Menu(Scene):
    """
    The Menu scene

    The main menu of the Microgames game.  From here, you can start a new game,
    change various options, or quit.
    """

    def __init__(self, game):
        Scene.__init__(self, game)
        self.options = options()
        self.options_font = Font(GAME_FONT_FILENAME, OPTIONS_FONT_SIZE)
        self.background, self.rectbg = load_image('title.jpg', 0, 0)
        self.index = 0

    def start(self):
        self.index = 0
        pygame.mixer.music.load('theme.ogg')
        pygame.mixer.music.play(-1, 0)

    def stop(self):
        pygame.mixer.music.stop()
        pass

    def update(self):
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_RETURN:
                    self.options[self.index][1](self)
                elif event.key == K_UP:
                    self.index -= 0 if self.index == 0 else 1
                elif event.key == K_DOWN:
                    self.index += 0 if self.index == len(self.options)-1 else 1

    def _render_options(self, surface):
        surface.blit(self.options_font.render('>', True, C_WHITE),
                (OPTIONS_INIT_X, OPTIONS_INIT_Y + self.index * OPTIONS_Y_DIST))

    def render(self, surface):
        surface.fill(C_BLACK)
        surface.blit(self.background, (self.rectbg.x, self.rectbg.y))
        self._render_options(surface)
Exemple #55
0
 def draw(self):
     if self.dirty():
         self.count = self.territory_asset.territory.armies
         font = Font(None, self.size)
         dimension = font.size(str(self.count) * 2)
         text_diagonal_length = math.sqrt(math.pow(dimension[0] / 2, 2) + math.pow(dimension[1], 2))
         circle_radius = int(math.ceil(text_diagonal_length / 2))
         #print circle_radius
         #print dimension [0]
         self.surface = pygame.Surface([44, 44], pygame.SRCALPHA, 32)
         self.surface = self.surface.convert_alpha()
         pygame.draw.circle(self.surface, base.BLACK, 
                 (circle_radius, circle_radius), 
                 circle_radius)
         pygame.draw.circle(self.surface, base.LIGHT_BROWN, 
                 (circle_radius, circle_radius), 
                 circle_radius - 2)
         font_surface = font.render(str(self.count), False,
                 self.colour).convert()
         self.surface.blit(font_surface, (circle_radius - dimension[0] / 4, circle_radius - dimension[1] / 2))
     return self.surface
Exemple #56
0
    def __init__(self, colour, pos, text, handler=None, rectSize=None):
        if rectSize == None:
            image = pygame.image.load("assets/button.png").convert_alpha()
            size = (image.get_rect().width, image.get_rect().height)
        else:
            size = rectSize
            image = pygame.Surface(rectSize).convert_alpha()
            image.fill(colour)

        self.colour = colour
        self.image = image
        font = Font("assets/swiss911.ttf", 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage, 
                (image.get_rect().width - textImage.get_rect().width - 10,
                    image.get_rect().height - textImage.get_rect().height - 5))
    
        LcarsWidget.__init__(self, colour, pos, size, handler)
        self.applyColour(colour)
        self.highlighted = False
        self.beep = Sound("assets/audio/panel/202.wav")
    def __init__(self, colour, pos, text, handler=None):
        self.handler = handler
        script_dir = dirname(__file__)
        ipath = join(script_dir, '../../assets/betterbutton.png')
        image = pygame.image.load(ipath).convert()
        size = (image.get_rect().width, image.get_rect().height)
        ipath = join(script_dir, '../../assets/swiss911.ttf')
        font = Font(ipath, 19)
        textImage = font.render(text, False, colours.BLACK)
        image.blit(textImage,
                   (image.get_rect().width - textImage.get_rect().width - 10,
                    image.get_rect().height - textImage.get_rect().height - 5))

        self.image = image
        self.colour = colour
        self.size = size
        LcarsWidget.__init__(self, colour, pos, size)
        self.applyColour(colour)
        self.highlighted = False
#        self.beep = Sound("assets/audio/panel/202.wav")
        self.inactiveColor = colour
Exemple #58
0
class ScrollingTextSprite(Sprite):
    """ A sprite making text scroll upwards and disappear after a while. """
    
    
    def __init__(self, txt, centerpos, scroll_height, duration=500,
                 fontsize=30, color=(0, 0, 0), groups=None):
        """ start displaying the dmg at the given rect, 
        and for the given duration 
        """
        
        Sprite.__init__(self, groups)

        self.txt = txt
        self.font = Font(None, fontsize) #default font
        self.image = self.font.render(txt, True, color)
        self.rect = self.image.get_rect(center=centerpos) # center the rect
        
        self.timer = duration
        self.shiftspeed = scroll_height / duration # float, in pixels per millis
        
    
    def __str__(self):
        return '%s at %s - leaves in %dms' % (self.txt, self.rect, self.timer)
            
            
    def update(self, frame_dur):
        """ Update the position of the text:
        - scroll upwards as time goes by, 
        - follow the charactor that received the dmg
        - if the char dies, stop following
        frame_dur = how long it took between 2 ticks
        """
        
        if self.timer <= 0:
            self.kill()
            del self
        else:
            self.timer -= frame_dur
            shift = self.shiftspeed * frame_dur  
            self.rect.move_ip(0, -shift) # shift upwards
Exemple #59
0
    def render(self, window):
        '''(StaticTile, Surface) -> NoneType
        Renders self.img if not None, then renders the trap img if not None,
        then renders self.value in text on top if self.value is not None.'''
        PADDING_W = 20
        PADDING_H = 20
        FONT_SIZE = 20
        WHITE = (255, 255, 255)

        # Render img
        if self.img:
            window.blit(self.img, self.rect)

        # Then render the trap
        if self.trap:
            window.blit(self.trapimg, self.rect)

        if self.wall:
            window.blit(self.wall_img, self.rect)

        # Render the key if there is one
        if self.key:
            window.blit(self.key_img, self.rect)

        # Render the lock if there is one
        if self.lock:
            window.blit(self.lock_img, self.rect)

        if self.exit:
            window.blit(self.exit_img, self.rect)

        # Prepare text for value
        if self.value != None:
            # Load the font into a Surface
            FONT = Font(None, FONT_SIZE) # Use default font
            SURFACE = FONT.render(str(self.value), False, WHITE)
            # Render the font
            window.blit(SURFACE, (self.rect.x + PADDING_W, self.rect.y + PADDING_H))