Screenshot Code

If you want people to look at your game, screenshots are what most pique people's attention.

It's sometimes possible to take screenshots using a generic screen grab tool, but that's not always the case, and it's not always quick and easy. It's best to set up a specific key you can press to take screenshots quickly and easily (I invariably use F12).

Fortunately doing this from Python code is pretty formulaic.

Pygame

Pygame can directly save a surface as an image. The code to do this just needs to be dropped into your event handling.



import datetime

import pygame



def screenshot_path():
    return datetime.datetime.now().strftime('screenshot_%Y-%m-%d_%H:%M:%S.%f.png')


...



# in your event loop

if event.type == KEYDOWN:
    if event.key == K_F12:
        pygame.image.save(screen_surface, screenshot_path())




Pyglet

In OpenGL, you have to read back the colour buffer to an image and save that. As you generally don't want the colour buffer's alpha channel to be saved if it has one, there are a couple of OpenGL calls to force every pixel to be read as opaque. Pyglet can handle reading and saving the colour buffer though.



import datetime

from pyglet import gl

from pyglet.window import key



def screenshot_path():
    return datetime.datetime.now().strftime('screenshot_%Y-%m-%d_%H:%M:%S.%f.png')


...



def on_key_press(symbol, modifiers):
    """This is your registered on_key_press handler.

    window is the pyglet.window.Window object to grab.
    """
    if symbol == key.F12:
        gl.glPixelTransferf(gl.GL_ALPHA_BIAS, 1.0)  # don't transfer alpha channel
        image = pyglet.image.ColorBufferImage(0, 0, window.width, window.height)
        image.save(screenshot_path())
        gl.glPixelTransferf(gl.GL_ALPHA_BIAS, 0.0)  # restore alpha channel transfer

Comments

Comments powered by Disqus