Snippets

Peter Finlayson code to test unsafe blits in pygame

Created by Peter Finlayson
#!/usr/bin/python2

from __future__ import division, print_function

import time

import pygame
from pygame.locals import *

APP_TITLE = "unsafe_blit() test"
SCREEN_SIZE = (1440, 768)
TILE_SIZE = 48


class FPSCounter(object):
    def __init__(self):
        self.last_frame = time.clock()
        self.frame_count = 0

    def tick(self):
        current_time = time.clock()
        delta = current_time - self.last_frame
        self.last_frame = current_time
        self.frame_count += 1
        return 1 / delta

def main():
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE)
    fps = FPSCounter()
    frame_rate = 0

    columns = range(int(SCREEN_SIZE[0] / TILE_SIZE))
    rows = range(int(SCREEN_SIZE[1] / TILE_SIZE))

    sprite = pygame.image.load("hero.png")
    sprite.convert()

    running = True
    while running:
        # process events:
        for event in pygame.event.get():
            # exit events
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key in (pygame.K_ESCAPE, pygame.K_q):
                    running = False

        # draw sprites
        sprite_count = 0
        y_offset = 0
        for y_tile in rows:
            x_offset = 0
            for x_tile in columns:
                screen.blit(sprite, (x_offset, y_offset))
                sprite_count += 1
                x_offset += TILE_SIZE
            y_offset += TILE_SIZE

        # done with frame
        pygame.display.flip()

        frame_rate = fps.tick()
        if fps.frame_count % 15 == 0:
            pygame.display.set_caption("%s - %d sprites - %d FPS" % (APP_TITLE, sprite_count, frame_rate))

        if fps.frame_count >= 600:
            running = False
    print("frame rate:", frame_rate)


if __name__ == "__main__":
    try:
        import cProfile
        cProfile.run("main()", sort="tottime")
    finally:
        pygame.quit()

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.