Granithor, Lord of 13K LAN - dS (granitor) wrote in granill,
Granithor, Lord of 13K LAN - dS
granitor
granill

testsprite.py - Code dump test




#!/usr/bin/env python
# like the testsprite.c that comes with sdl, this pygame version shows
# lots of sprites moving around.
# modified by gran (granill.livejournal.com) - v 2a has an
# OnScreen Display (OSD) for the Framerate counter,
# which you can activate/update with the "f" key.
# sorry for people without keyboards, I'll work on that
# if/when I get a GP2X or whatever.
# note: requires two files from a "data" subdirectory,
# I'll document them in detail better or generate == images.


import pygame, sys, os
from pygame.locals import *
from random import randint
from time import time
import pygame.joystick

##import FastRenderGroup as FRG
import pygame.sprite as FRG

if "-psyco" in sys.argv:
try:
import psyco
psyco.full()
except Exception:
print "No psyco for you! psyco failed to import and run."


# use this to use update rects or not.
# If the screen is mostly full, then update rects are not useful.
update_rects = True
if "-update_rects" in sys.argv:
update_rects = True
if "-noupdate_rects" in sys.argv:
update_rects = False

use_static = False
if "-static" in sys.argv:
use_static = True


use_FastRenderGroup = False
if "-FastRenderGroup" in sys.argv:
update_rects = True
use_FastRenderGroup = True


flags = 0
if "-flip" in sys.argv:
flags ^= DOUBLEBUF

if "-fullscreen" in sys.argv:
flags ^= FULLSCREEN

if "-sw" in sys.argv:
flags ^= SWSURFACE

use_rle = True

if "-hw" in sys.argv:
flags ^= HWSURFACE
use_rle = False


screen_dims = [640, 480]

if "-height" in sys.argv:
i = sys.argv.index("-height")
screen_dims[1] = int(sys.argv[i+1])

if "-width" in sys.argv:
i = sys.argv.index("-width")
screen_dims[0] = int(sys.argv[i+1])

if "-alpha" in sys.argv:
use_alpha = True
else:
use_alpha = False

print "Screen dimensions (for pygame window) are: ", screen_dims

class Thingy(FRG.DirtySprite):
images = None
def __init__(self):
FRG.DirtySprite.__init__(self)
self.image = Thingy.images[0]
self.rect = self.image.get_rect()
self.rect.x = randint(0, screen_dims[0])
self.rect.y = randint(0, screen_dims[1])
self.vel = [randint(-1, 1), randint(-1, 1)]
self.dirty = 2

def update(self):
for i in [0, 1]:
nv = self.rect[i] + self.vel[i]
if nv >= screen_dims[i] or nv < 0:
self.vel[i] = -self.vel[i]
nv = self.rect[i] + self.vel[i]
self.rect[i] = nv

class Static(FRG.DirtySprite):
images = None
def __init__(self):
FRG.DirtySprite.__init__(self)
self.image = Static.images[0]
self.rect = self.image.get_rect()
self.rect.x = randint(0, 3*screen_dims[0]/4)
self.rect.y = randint(0, 3*screen_dims[1]/4)


def update_fps( fr, et, st ):
end = et
dt = et - st
if dt > 1:
fps = float( fr / ( ( et - st ) ) )
fs = "Current mean average speed: %3.1f FPS." % fps
else:
fps = 0.0
fs = "Sorry, too early to estimate FPS rate!"
return fs

class Stext: # status text
def __init__(self, screen, pos = ( 0, 0 ), font = None):
pygame.font.init() # since we're doing it piecewise
self.font = pygame.font.Font(font, 32) #TODO: code size a bit less hard
self.bmp = screen
self.pos = pos
self.color = ( 16, 16, 240) # blue... ish
self.bg = ( 0xC0, 0xC0, 0xC0 ) # grey, I think
self.aa = False
self.img = None
def strout(self, text = "Sample Text Printed."):
img = self.font.render(text, self.aa, self.color, self.bg)
r = self.bmp.blit(img, self.pos)
self.img = img
return r
def repaint(self): # call this when it gets over-written
if self.img != None:
r = self.bmp.blit(self.img, self.pos)
return r # add this to a drect list, if used
else:
return None # no rect to change.
def disappear(self): # call to disappear the status bar
self.img = None
## def clear(self): # blank the bar but keep it visible
## pass # NYI, do it sometimg
## self.strout("?NYI: Stext.clear(self)!")



def main():
global update_rects, flags
#pygame.init()
pygame.display.init()



#if "-fast" in sys.argv:

screen = pygame.display.set_mode(screen_dims, flags)

status_bar = Stext(screen, (32,32) )
## status_bar.strout() # test

# this is mainly for GP2X, so it can quit.
pygame.joystick.init()
num_joysticks = pygame.joystick.get_count()
if num_joysticks > 0:
stick = pygame.joystick.Joystick(0)
stick.init() # now we will receive events for the joystick


screen.fill([0,0,0])
pygame.display.flip()
try:
sprite_surface = pygame.image.load(os.path.join("data", "asprite.bmp"))
sprite_surface2 = pygame.image.load(os.path.join("data", "static.png"))
except pygame.error:
pygame.display.quit() # for W32 within IDE
print "?Unable to load important data, so I'm gone."
raise SystemExit

if use_rle:
sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY|RLEACCEL)
sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY|RLEACCEL)
else:
sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY)
sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY)

if use_alpha:
sprite_surface = sprite_surface.convert_alpha()
sprite_surface2 = sprite_surface2.convert_alpha()
else:
sprite_surface = sprite_surface.convert()
sprite_surface2 = sprite_surface2.convert()

Thingy.images = [sprite_surface]
if use_static:
Static.images = [sprite_surface2]

if len(sys.argv) > 1:
try:
numsprites = int(sys.argv[-1])
except:
numsprites = 100
else:
numsprites = 100
sprites = None
if use_FastRenderGroup:
sprites = FRG.LayeredDirty()
else:
if update_rects:
sprites = pygame.sprite.RenderUpdates()
else:
sprites = pygame.sprite.Group()

for i in xrange(0, numsprites):
if use_static and i%2==0:
sprites.add(Static())
sprites.add(Thingy())

done = False
frames = 0
start = time()

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill([0,0,0])


while not done:
if not update_rects:
screen.fill([0,0,0])

if update_rects:
sprites.clear(screen, background)
sprites.update()

rects = sprites.draw(screen)

r = status_bar.repaint()
if r != None:
rects.append(r)

if update_rects:
pygame.display.update(rects)
else:
pygame.display.flip()


for event in pygame.event.get():
if event.type in [QUIT, JOYBUTTONDOWN]:
done = True
elif event.type == KEYDOWN:
if event.key == K_f: # update FPS counter OSD
fs = update_fps(frames+1, time(), start)
##print fs
status_bar.strout(fs)
elif event.key == K_ESCAPE:
print "ESCape key pressed, so goodbye!"
done = True
else:
name = pygame.key.name(event.key)
pong = "You pressed \"%s\", which is meaningless to me." % name
status_bar.strout(pong)

frames += 1
end = time()
print "FPS: %f" % (frames / ((end - start)))

if __name__ == "__main__":
main()

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded 

  • 0 comments