[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] how to optimize these two function?



these two functions use "set_at" and "get_at" to blit surface, the fist copy a part of a surface to an other with alpha value. the second change all  alpha  value of the pixels in surface except the transparent pixels.
they all work well, but too slow,how to optimize them, I know surarray is a best choice,but it's  so difficult to  me, can any one help me?
 
import os, pdb, sys, pygame
from pygame.locals import *
 
def copy_blit(source, dest, dPos, sRect = None):
    if source.get_alpha():
        if not dest.get_alpha():
            dest.convert_alpha()
    else:
        if dest.get_alpha():
            dest.convert()
    if not sRect:
        sRt = source.get_rect()
    else:
        sRt =  pygame.Rect(sRect)
   
    w = sRt.width
    h  = sRt.height
    sX, sY = sRt.x, sRt.y
    dX,  dY = dPos[0], dPos[1]
    source.lock()
    dest.lock()
    for i  in range(h):
        for j in range(w):
            dest.set_at((dX + j, dY + i), source.get_at((sX+j, sY + i)))
    source.unlock()
    dest.unlock()
 
def change_alpha(surf, alpha):
    if surf.get_alpha() is None:
        surf.set_alpha(alpha)
    else :
        wid = surf.get_width()
        hei = surf.get_height()
        surf.lock()
        for i  in range(hei):
            for j in range(wid):
                c = surf.get_at((j, i))
                if  c[-1] != 0:
                    surf.set_at((j,i), (c[0], c[1], c[2], alpha))
        surf.unlock()