if pg.get_sdl_version()[0] < 2: raise SystemExit("This example requires pygame 2 and SDL2.") from pygame._sdl2 import Window, Texture, Image, Renderer data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "data") def load_img(file): return pg.image.load(os.path.join(data_dir, file)) pg.display.init() pg.key.set_repeat(10, 10) win = Window("asdf", resizable=True) renderer = Renderer(win) tex = Texture.from_surface(renderer, load_img("alien1.gif")) class Something(pg.sprite.Sprite): def __init__(self, img): pg.sprite.Sprite.__init__(self) self.rect = img.get_rect() self.image = img self.rect.w *= 5 self.rect.h *= 5 img.origin = self.rect.w / 2, self.rect.h / 2
for driver in get_drivers(): print(driver) import random answer = messagebox("I will open two windows! Continue?", "Hello!", info=True, buttons=('Yes', 'No', 'Chance'), return_button=0, escape_button=1) if answer == 1 or (answer == 2 and random.random() < .5): import sys sys.exit(0) win = Window('asdf', resizable=True) renderer = Renderer(win) tex = Texture(renderer, load_img('alien1.gif')) running = True x, y = 250, 50 clock = pygame.time.Clock() backgrounds = [(255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255)] bg_index = 0 renderer.draw_color = backgrounds[bg_index] win2 = Window('2nd window', size=(256, 256), always_on_top=True) win2.opacity = 0.5
def main(): os.environ['SDL_RENDER_SCALE_QUALITY'] = '2' example_data = os.path.join(os.path.dirname(__file__), 'data', '') examples = { 'Radiantly Red': dict(color=(220, 0, 0), colors=(-100, 0, 0), circle=3, scale=5, duration=5000, rotate=25, variance=10), 'Blistering Blue': dict(color=(0, 0, 255), move=(8, 0), fade=200, spread=25, duration=200), 'Vividly Violet': dict(color=(238, 130, 238), colors=(-30, -30, -30), move=(10, 10), rotate=5, scale=5, duration=3000), 'Garishly Green': dict(color=(0, 100, 0), colors=(0, -50, 0), scale=20, duration=5000, variance=33), 'Whispy White': dict(color=(255, 255, 255), fade=100, circle=10, variance=5, duration=9000) } default = dict(color=(255, 255, 0), move=(5, 2), rotate=4, duration=3000) example_list = list(examples.keys()) kwargs = dict( x.split('=', 1)[:2] for x in [arg for arg in sys.argv[1:] if '=' in arg]) for k, v in kwargs.items(): if ',' in v: v = eval(f'({v})') else: try: v = float(v) except: try: v = int(v) except: pass kwargs[k] = v params = {'text': 'Dancing Font!', 'color': (255, 255, 255)} params.update(**kwargs) pg.init() clock = pg.time.Clock() window = kwargs.get('window', (900, 600)) window = Window("TextureFont test", size=window) center = 450 renderer = Renderer(window, vsync=True) size = kwargs.get('size', 60) font = kwargs.get('font', 'font.ttf') tfont = TextureFont(renderer, example_data + font, int(size)) patch1 = (52, 52, 52, 52), (0, 0, 320, 172) patch2 = (40, 40, 40, 40), (0, 177, 320, 223) patch3 = (40, 40, 40, 40), (0, 404, 320, 160) texture = load_texture(renderer, example_data + 'nine.png') nine = NinePatch(texture, *patch3) if len(sys.argv) > 1: window.size = tfont.width(params['text']) * 1.25, tfont.height * 1.25 center = window.size[0] // 2 y = int(tfont.height * .125) selected = 0 running = True while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False elif event.type == pg.KEYDOWN: if event.key == pg.K_UP: selected -= 1 if selected < 0: selected = len(examples) - 1 elif event.key == pg.K_DOWN: selected += 1 if selected >= len(examples): selected = 0 else: running = False renderer.draw_color = (0, 0, 0, 255) renderer.clear() x, y = pg.mouse.get_pos() nine.draw(pg.Rect(10, 10, x - 10, y - 10)) if len(sys.argv) > 1: tfont.animate(x=center, y=y, center=True, **params) else: y = 20 for i, item in enumerate(example_list): if i == selected: tfont.animate(item, center, y, center=True, **examples[item]) else: tfont.animate(item, center, y, center=True, **default) y += tfont.height * 1.25 renderer.present() clock.tick(30)
import random answer = messagebox( "I will open two windows! Continue?", "Hello!", info=True, buttons=("Yes", "No", "Chance"), return_button=0, escape_button=1, ) if answer == 1 or (answer == 2 and random.random() < 0.5): import sys sys.exit(0) win = Window("asdf", resizable=True) renderer = Renderer(win) tex = Texture.from_surface(renderer, load_img("alien1.gif")) running = True x, y = 250, 50 clock = pg.time.Clock() backgrounds = [(255, 0, 0, 255), (0, 255, 0, 255), (0, 0, 255, 255)] bg_index = 0 renderer.draw_color = backgrounds[bg_index] win2 = Window("2nd window", size=(256, 256), always_on_top=True) win2.opacity = 0.5
def sprites(): pg.init() clock = pg.time.Clock() window = Window("Renderpyg Example", size=WINDOW_RESOLUTION) renderer = Renderer(window, vsync=True) """ We will draw into a buffer texture to allow easy resolution changes It will also make it easier to apply screen transitions and similar effects later When using pygame._sdl2.video you do not call pygame.display.setmode() Therefore calling surface.convert() or surface.convert_alpha() will throw an error When you create a Texture that needs alpha blending you must set its blend mode Alpha blending will be set automatically when loading from an image with transparency, such as PNG Remember to use the buffer size instead of the window size when drawing onto the offscreen buffer This will allow you to scale the screen to any window or fullscreen desktop size """ buffer = Texture(renderer, RENDER_RESOLUTION, target=True) buffer.blend_mode = 1 screensize = buffer.get_rect() """ You can set fullscreen when creating the window by using Window(title, size, desktop_fullscreen=True) I prefer creating a window before going to fullscreen to avoid strange window placement that occurs if you exit fullscreen later on. """ FULLSCREEN = False if FULLSCREEN: window.set_fullscreen(True) """ Font features in pygame are design for blitting to a surface, not for GPU rendering It is possible to create a streaming texture and then using texture.update() to update the texture from a pygame surface, but accessing GPU memory is slow and this should be done sparingly. Therefore I created a simple TextureFont class. We will use the animation feature of this class for a little extra fun. We will also create some sprites and let them animate too. Also, for this example we use a Character class to move and rotate individual characters across the screen. This is very similar to how you will handle sprites later. """ tfont = TextureFont(renderer, FONT, FONT_SIZE) sprite = Sprite((renderer, EXAMPLE_DATA + 'aliens.png'), 7, 8, by_count=True) group = pg.sprite.Group() animations = [ keyrange(0, 7, 200), keyrange(7, 14, 200), keyrange(14, 21, 200), keyrange(28, 35, 200) ] for _ in range(SPRITE_COUNT): spr = Sprite(sprite.images) spr.set_pos(randrange(0, RENDER_RESOLUTION[0]), randrange(0, RENDER_RESOLUTION[1])) spr.set_animation(random.choice(animations), -1) spr.velocity = pg.Vector2(randrange(-10, 11), randrange(-10, 11)) if randrange(10) < 2: spr.rotation = randrange(-10, 11) group.add(spr) """ Here starts a simple game loop Press SPACE to toggle between a large window, a small window, and fullscreen Press ENTER to add more characters to the screen At the beginning of each frame we must set the renderer target to our buffer Texture All the following draw calls will be drawn to the buffer instead of the screen After all of our drawing, we reset the target and draw the buffer onto the screen """ timer = pg.time.get_ticks() delta = 0 running = True while running: renderer.target = buffer for event in pg.event.get(): if event.type == pg.QUIT: running = False elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: running = False elif event.key == pg.K_SPACE: if FULLSCREEN: FULLSCREEN = False window.size = WINDOW_RESOLUTION window.set_windowed() elif window.size == WINDOW_RESOLUTION: window.size = SMALL_RESOLUTION else: FULLSCREEN = True window.size = WINDOW_RESOLUTION window.set_fullscreen(True) #Must set the draw color before clearing the scren or drawing lines and rectt renderer.draw_color = (0, 0, 0, 255) renderer.clear() """ Draw the background image if available. By default Texture.draw() will fill the renderer unless you supply a destination Rect texture.draw( dstrect=Rect(x, y, width, height) ) """ group.update(delta) group.draw() tfont.animate(**FONT_PARAMS) # Setting renderer.target = None will make following draw calls render to the underlying window # Since we don't provide a dstrect it will fill the renderer renderer.target = None buffer.draw() renderer.present( ) # all draw calls occur and the screen is updated here delta = clock.tick(FRAMES_PER_SECOND)
raise SystemExit('This example requires pygame 2 and SDL2.') import os data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'data') from pygame._sdl2 import (Window, Texture, Image, Renderer) def load_img(file): return pygame.image.load(os.path.join(data_dir, file)) pygame.display.init() pygame.key.set_repeat(10, 10) win = Window('asdf', resizable=True) renderer = Renderer(win) tex = Texture.from_surface(renderer, load_img('alien1.gif')) class Something(pygame.sprite.Sprite): def __init__(self, img): pygame.sprite.Sprite.__init__(self) self.rect = img.get_rect() self.image = img self.rect.w *= 5 self.rect.h *= 5 img.origin = self.rect.w / 2, self.rect.h / 2
self.exit_status = 1 while self.running: self.handle_input() self.draw() return self.exit_status if __name__ == '__main__': import os.path import glob pygame.init() pygame.font.init() window = Window("pytmx map viewer", size=(600, 600)) renderer = Renderer(window, vsync=True) ctx = GameContext(window, renderer) logging.basicConfig(level=logging.DEBUG) logger.info(pytmx.__version__) # loop through a bunch of maps in the maps folder try: for filename in glob.glob(os.path.join('apps', 'data', '*.tmx')): logger.info("Testing %s", filename) renderer.clear() if not SimpleTest(ctx, filename).run(): break except:
def main(): import os from .tfont import TextureFont example_data = os.path.join(os.path.dirname(__file__), 'data', '') pg.init() window = Window('Testing', (1600, 900)) renderer = Renderer(window) #tilemap = load_tmx(renderer, path+'tilemap.tmx') clock = pg.time.Clock() running = True camera = pg.Vector2() center = True scale = 1 tfont = TextureFont(renderer, None, 48) loaded_map = load_tilemap_string(map_data) loaded_cells = load_tileset(renderer, example_data + 'tiles.png', 64, 64) tilemap = Tilemap(loaded_map, loaded_cells) tilemap.update_tilemap(loaded_map, 0) tilemap.add_layer(loaded_map) scaling = 0 mode = 0 while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: running = False elif event.key == pg.K_f: window_mode = window_mode + 1 if window_mode < 3 else 1 if window_mode == 1: window.size = WINDOW_RESOLUTION window.set_windowed() elif window_mode == 2: window.size = SMALL_RESOLUTION else: window.set_fullscreen(True) elif event.key == pg.K_t: mode = not mode elif event.type == pg.MOUSEMOTION: x, y = pg.mouse.get_rel() if pg.mouse.get_pressed()[0]: camera.x -= x * 2 camera.y -= y * 2 elif event.type == pg.MOUSEBUTTONUP: if event.button == 3: center = not center elif event.button == 4: scaling += 0.001 elif event.button == 5: scaling -= 0.001 scale += scaling render_tilemap(tilemap, camera, scale, center=center, clamp=True, smooth=True) tfont.draw(f'cam: {camera}, center: {center}, {scale}', 10, 10) tfont.draw(printfo, 10, 60) renderer.present() renderer.draw_color = (255, 0, 0, 0) renderer.clear() clock.tick(5)