How to use the pygame.font function in pygame

To help you get started, we’ve selected a few pygame examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Tuxemon / Tuxemon / tests / interactive / test_iter_text.py View on Github external
import pygame
import this
from tuxemon.core.components.ui import draw

if __name__ == "__main__":
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    font = pygame.font.Font(pygame.font.get_default_font(), 20)
    fg = 255, 245, 64
    bg = 35, 35, 35
    text = "".join([this.d.get(c, c) for c in this.s])
    running = True

    while running:
        for rect, surface in draw.iter_render_text(text, font, fg, bg, screen.get_rect()):
            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    running = False

            if not running:
                break

            screen.blit(surface, rect)
            pygame.display.flip()
github bitcraft / PyTMX / apps / test_pygame.py View on Github external
"""
        # first we make a temporary surface that will accommodate the entire
        # size of the map.
        # because this demo does not implement scrolling, we render the
        # entire map each frame
        temp = pygame.Surface(self.renderer.pixel_size)

        # render the map onto the temporary surface
        self.renderer.render_map(temp)

        # now resize the temporary surface to the size of the display
        # this will also 'blit' the temp surface to the display
        pygame.transform.smoothscale(temp, surface.get_size(), surface)

        # display a bit of use info on the display
        f = pygame.font.Font(pygame.font.get_default_font(), 20)
        i = f.render('press any key for next map or ESC to quit',
                     1, (180, 180, 0))
        surface.blit(i, (0, 0))
github geek-ai / MAgent / python / magent / renderer / pygame_renderer.py View on Github external
pygame.init()
        pygame.display.init()

        if resolution is None:
            info = pygame.display.Info()
            resolution = info.current_w, info.current_h

        clock = pygame.time.Clock()
        
        if full_screen:
            canvas = pygame.display.set_mode(resolution, pygame.DOUBLEBUF | pygame.FULLSCREEN, 0)
        else:
            canvas = pygame.display.set_mode(resolution, pygame.DOUBLEBUF, 0)

        pygame.display.set_caption('MAgent Renderer Window')
        text_formatter = pygame.font.SysFont(None, text_size, True)
        banner_formatter = pygame.font.SysFont(None, banner_size, True)
        bigscreen_formatter = pygame.font.SysFont(None, bigscreen_size, True)

        map_size, groups, static_info = server.get_info()
        view_position = [map_size[0] / 2 * grid_size - resolution[0] / 2, 
                         map_size[1] / 2 * grid_size - resolution[1] / 2]
        frame_id = 0

        walls  = static_info['wall']

        old_data = None
        new_data = None

        need_static_update = True
        #show_grid = False
        animation_progress = 0
github nikist97 / Python-DataStructures / Applications / nPuzzleAnimation.py View on Github external
def main(initial):
    pygame.init()
    pygame.font.init()
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption('N-Puzzle')

    n = len(initial)
    grid_width = n**0.5
    generator = iter(n_puzzle(initial))
    running = True
    clock = pygame.time.Clock()
    board = Board(int(size[0] / grid_width), grid_width, black, red)

    while running:
        screen.fill(white)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
github Faylixe / pygame_vkeyboard / samples / custom_renderer.py View on Github external
#!/usr/bin/python

""" Simple keyboard usage using AZERTY layout. """

import pygame
from pygame.locals import *
from pygame_vkeyboard import *

def consumer(text):
    print(repr('Current text state: %s' % text))

WHITE = (255, 255, 255)
BACKGROUND = (0, 0, 0, 150)
FONT = pygame.font.SysFont('arial', 40)


class TransparentRenderer(VKeyboardRenderer):

    def draw_background(self, surface, position, size):
        pygame.draw.rect(surface, (0, 0, 0, 150), position + size)
    
    def draw_character_key(self, surface, key, special=False):
        pygame.draw.rect(surface, WHITE, key.position + (key.size, key.size), 1)
        surface.blit(FONT.render(key.value, 1, WHITE, None), key.position)

if __name__ == "__main__":
    pygame.init()
    window = pygame.display.set_mode((600, 400))
    layout = VKeyboardLayout(VKeyboardLayout.AZERTY)
    keyboard = VKeyboard(window, consumer, layout, renderer=TransparentRenderer())
github furas / python-examples / pygame / button-hover / example-1.py View on Github external
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):

        self.text = text
        self.command = command
        
        self.image_normal = pygame.Surface((width, height))
        self.image_normal.fill(GREEN)

        self.image_hovered = pygame.Surface((width, height))
        self.image_hovered.fill(RED)

        self.image = self.image_normal
        self.rect = self.image.get_rect()

        font = pygame.font.Font('freesansbold.ttf', 15)
        
        text_image = font.render(text, True, WHITE)
        text_rect = text_image.get_rect(center = self.rect.center)
        
        self.image_normal.blit(text_image, text_rect)
        self.image_hovered.blit(text_image, text_rect)

        # you can't use it before `blit` 
        self.rect.topleft = (x, y)

        self.hovered = False
        #self.clicked = False
github horstjens / ThePythonGameBook / pygame / template004_sprites_collision_detection.py View on Github external
def write(background, text, x=50, y=150, color=(0,0,0),
          fontsize=None, center=False):
        """write text on pygame surface. """
        if fontsize is None:
            fontsize = 24
        font = pygame.font.SysFont('mono', fontsize, bold=True)
        fw, fh = font.size(text)
        surface = font.render(text, True, color)
        if center: # center text around x,y
            background.blit(surface, (x-fw//2, y-fh//2))
        else:      # topleft corner is x,y
            background.blit(surface, (x,y))
github hanyazou / TelloPy / tellopy / examples / keyboard_and_video.py View on Github external
def main():
    pygame.init()
    pygame.display.init()
    pygame.display.set_mode((1280, 720))
    pygame.font.init()

    global font
    font = pygame.font.SysFont("dejavusansmono", 32)

    global wid
    if 'window' in pygame.display.get_wm_info():
        wid = pygame.display.get_wm_info()['window']
    print("Tello video WID:", wid)

    drone = tellopy.Tello()
    drone.connect()
    drone.start_video()
    drone.subscribe(drone.EVENT_FLIGHT_DATA, flightDataHandler)
    drone.subscribe(drone.EVENT_VIDEO_FRAME, videoFrameHandler)
    drone.subscribe(drone.EVENT_FILE_RECEIVED, handleFileReceived)
    speed = 30
github bitsauce / Carla-ppo / CarlaEnv / carla_env.py View on Github external
reward_fn (function):
                Custom reward function that is called every step.
                If None, no reward function is used.
            encode_state_fn (function):
                Function that takes the image (of obs_res resolution) from the
                observation camera and encodes it to some state vector to returned
                by step(). If None, step() returns the full image.
            fps (int):
                FPS of the sensors
            spawn_point (int):
                Index of the spawn point to use (spawn point 1 of Town07 is a good starting point)
        """

        # Initialize pygame for visualization
        pygame.init()
        pygame.font.init()
        width, height = viewer_res
        if obs_res is None:
            out_width, out_height = width, height
        else:
            out_width, out_height = obs_res
        self.display = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.clock = pygame.time.Clock()

        # Setup gym environment
        self.seed()
        self.action_space = gym.spaces.Box(np.array([-1, 0]), np.array([1, 1]), dtype=np.float32) # steer, throttle
        self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(*obs_res, 3), dtype=np.float32)
        self.metadata["video.frames_per_second"] = fps
        self.spawn_point = spawn_point
        self.encode_state_fn = (lambda x: x) if not callable(encode_state_fn) else encode_state_fn
        self.reward_fn = (lambda x: 0) if not callable(reward_fn) else reward_fn
github Photonsters / PhotonFileEditor / PopupDialog.py View on Github external
def __init__(self, pyscreen, pos, title="Message Dialog",message="Read this carefully... \n ...before entering Ok!", dfontname=defFontName, dfontsize=defFontSize):
        """ Saves all values to internal variables and calculates some extra internal vars. """
        self.pyscreen = pyscreen
        #self.parentRedraw=parentRedraw
        self.winrect=GRect(pos[0], pos[1], 300, 160)
        self.title=title
        self.message=message
        self.font = pygame.font.SysFont(dfontname, dfontsize)

        # Calculate extra variables
        dummy, textheight = self.font.size("MinimalText")
        self.titleheight=textheight +self.margins.y+self.margins.height
        self.footerTop = self.winrect.y + self.winrect.height - self.margins.height - self.footerHeight

        # Add GUI.Label
        self.label=Label(pyscreen,text=message,fontname=dfontname,fontsize=dfontsize,rect=GRect(),autoheight=False,center=True,backcolor=self.formcolor,autowrap=True)
        self.controls.append(self.label)

        # (Re)calculate remaining variables
        self.reposControls()