How to use pygame - 10 common examples

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 Impelon / PyGVisuals / examples / bintree-gui / bintree-gui.py View on Github external
"""
    Validation function for an Entry; limits inputs to numbers smaller than 101

    parameters:     str the text to be set
                    str the current text
                    gui.Entry the entry affected
    return values:  boolean is the operation valid
    """
    return not newtext or (newtext.isdigit() and int(newtext) < 101)

#Setting Display#

w = 900
h = 600

screen = pygame.display.set_mode((w, h), 0, 32)
pygame.display.set_caption("Tree-GUI | Python Game")
pygame.mouse.set_visible(1)
pygame.key.set_repeat(50)

background = pygame.Surface((w, h))
background.fill((255, 255, 255))

#Widgets#

des.getDefaultDesign().border     = brd.CompoundBorder(brd.RoundedBorder(3, 3, (150, 190, 255, 200), 8), brd.RoundedBorder(2, 2, (30, 90, 150), 8))
des.getDefaultDesign().background = (120, 160, 200)
w_w                               = 130
w_h                               = 25

w_bg        = gui.Widget(w * 0.8571428571428571 - w_w // 2 - 20, 10, w_w // 2 + w * 0.14285714285714285, h - 20).setBackground((220, 220, 250))
l           = gui.Label(w * 0.8571428571428571 - w_w // 2, 10, w_w, w_h, "Tree-GUI").setBackground((0, 0, 0, 0)).setForeground((50, 50, 50)).setBorder(brd.Border(0, 0))
github gil9red / SimplePyScripts / pygame__examples / move_circle.py View on Github external
__author__ = 'ipetrash'


# pip install pygame
import pygame


FPS = 60
W = 700  # ширина экрана
H = 300  # высота экрана
WHITE = (255, 255, 255)
BLUE = (0, 70, 225)

pygame.init()
screen = pygame.display.set_mode((W, H))
clock = pygame.time.Clock()

# координаты и радиус круга
x = W // 2
y = H // 2
r = 50

step = 4

game_active = True

while True:
    # Получение всех событий
    for event in pygame.event.get():
        # Проверка события "Выход"
        if event.type == pygame.QUIT:
github alex-petrenko / microtbs-rl / microtbs_rl / envs / micro_tbs.py View on Github external
ui_size = max(100, self.render_resolution // 3)
            screen_w = self.screen_size_world + ui_size
            screen_h = self.screen_size_world
            self.rendering_surface = pygame.Surface((screen_w, screen_h))
            self.font = pygame.font.SysFont(None, self.render_resolution // 32)
            self.ui_surface = pygame.Surface((ui_size, screen_h))
            if mode == 'human':
                self.screen = pygame.display.set_mode((screen_w, screen_h))

        self._render_game_world(self.rendering_surface, self.screen_scale)
        self._render_ui(self.rendering_surface, analytics)
        self._render_layout(self.rendering_surface)

        if mode == 'human':
            self.screen.blit(self.rendering_surface, (0, 0))
            pygame.display.flip()
        elif mode == 'rgb_array':
            return np.transpose(pygame.surfarray.array3d(self.rendering_surface), axes=[1, 0, 2])
        else:
            raise Exception('Unsupported rendering mode')
github horstjens / ThePythonGameBook / pygame / template003_moving_sprites.py View on Github external
self.x = x
        self.y = y
        if color is None: # create random color if no color is given
            color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
        else:
            self.color = color
        if dx is None:
            self.dx = random.random() * 100 - 50 # from -50 to 50
        else:
            self.dx = dx
        if dy is None:
            self.dy = random.random() * 100 - 50
        else:
            self.dy = dy
        # create a rectangular surface for the ball 50x50
        self.image = pygame.Surface((self.width,self.height))    
        # pygame.draw.circle(Surface, color, pos, radius, width=0) # from pygame documentation
        pygame.draw.circle(self.image, color, (radius, radius), radius) # draw blue filled circle on ball surface
        # left blue eye
        pygame.draw.circle (self.image, (0,0,200) , (radius //2 , radius //2), radius// 3)
        # right yellow yey
        pygame.draw.circle (self.image, (255,255,0) , (3 * radius //2  , radius //2), radius// 3)
        # grey mouth
        pygame.draw.arc(self.image, (32,32,32), (radius //2, radius, radius, radius//2), math.pi, 2*math.pi, 1)
        # self.surface = self.surface.convert() # for faster blitting if no transparency is used. 
        # to avoid the black background, make black the transparent color:
        self.image.set_colorkey((0,0,0))
        self.image = self.image.convert_alpha() # faster blitting with transparent color
        #self.image=pygame.image.load("xx.png")
        self.rect= self.image.get_rect()
github jerbly / tutorials / pygamelcd / test1.py View on Github external
'''
Created on Jul 12, 2014

@author: jeremyblythe
'''
import pygame
import os
from time import sleep

os.putenv('SDL_FBDEV', '/dev/fb1')
pygame.init()
lcd = pygame.display.set_mode((320, 240))
lcd.fill((255,0,0))
pygame.display.update()
sleep(1)

pygame.mouse.set_visible(False)

lcd.fill((0,0,0))
pygame.display.update()
github renpy / pygame_sdl2 / old-tests / test_blit_matrix.py View on Github external
def case(src_alpha, dst_alpha, colorkey, alpha):

    if src_alpha:
        src = pygame.Surface((150, 150), pygame.SRCALPHA)
    else:
        src = pygame.Surface((150, 150), 0)

    if dst_alpha:
        dst = pygame.Surface((150, 150), pygame.SRCALPHA)
    else:
        dst = pygame.Surface((150, 150), 0)


    top_pattern(src)
    bottom_pattern(dst)

    if colorkey:
        src.set_colorkey((255, 0, 255, A))

    if alpha:
        src.set_alpha(128)

    dst.blit(src, (0, 0))


    return dst
github kidscancode / gamedev / tutorials / platform-tests / plat-test3.py View on Github external
WIDTH = 800
HEIGHT = 640
FPS = 60

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Run!!!")
clock = pygame.time.Clock()

class Platform(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h, vx, vy):
        super(Platform, self).__init__()
        self.image = pygame.Surface((w, h))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.vx = vx
        self.vy = vy

    def update(self):
        self.rect.x += self.vx
        # shift the player if we hit
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 bitcraft / pyscroll / tests / demo-2x.py View on Github external
def handle_input(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                self.running = False
                break

            elif event.type == KEYDOWN:
                if event.key == K_UP:
                    self.camera_vector[1] -= 100
                elif event.key == K_DOWN:
                    self.camera_vector[1] += 100
                elif event.key == K_LEFT:
                    self.camera_vector[0] -= 100
                elif event.key == K_RIGHT:
                    self.camera_vector[0] += 100
                elif event.key == K_ESCAPE:
                    self.running = False
                    break