pygame常识&技巧(1)

pygame-1.9.1release/docs/tut/chimp/ChimpLineByLine.html

1)pygame中有些模块有时是无效的,当无效时,其值为None,可以通过如下方法判断

if not pygame.font: print 'Warning, fonts disabled'

2)Surface.set_colorkey

设置Surface的透明色。当把 这个Surface blit到令一个Surface时候,和这个透明色颜色相同的像素会变成透明。具体使用方法参照API

3)如果是找不到音乐文件是,可以返回一个NoneSound,保证程序正常执行。

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer:
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error, message:
        print 'Cannot load sound:', wav
        raise SystemExit, message
    return sound
4)可以用矩形自带的方法执行move,判断是否在矩形内等

newpos = self.rect.move((self.move, 0))
Rect.contains

5)取得Display的sruface

screen = pygame.display.get_surface()


pygame-1.9.1release/docs/tut/newbieguide.html

1)对surface始终使用convert或者convert_alpha,除非你想控制surface内部的像素格式
这两个函数会将surface的像素格式进行调整,以便于在blit的时候可以用最快的速度进行拷贝。

这意味着在加载一个图片时等创建surface时,最好用如下的方式
pygame.image.load(file).convert()

2)只update脏矩形,update的方法有以下三种。
pygame.display.update() - This updates the whole window (or the whole screen for fullscreen displays).
pygame.display.flip() - This does the same thing, and will also do the right thing if you're using doublebuffered hardware acceleration, which you're not, so on to...
pygame.display.update(a rectangle or some list of rectangles) - This updates just the rectangular areas of the screen you specify.
在游戏大的时候,一定要用第三种,只更新脏矩形,通常做法是做一个list,在每帧的刷新中只更新 the_dirty_rectangles,具体步骤如下
Blit a piece of the background over the sprite's current location, erasing it.xAppend the sprite's current location rectangle to a list called dirty_rects.
Move the sprite.
Draw the sprite at it's new location.
Append the sprite's new location to my dirty_rects list.
Call display.update(dirty_rects)

实机操作过程中可以做一个函数,或者类专门用来维护更新这个脏矩形列表。

3)Managing the event subsystem

有两种方法来实现事件检知各有用途
  一)实时检知
pygame.mouse.get_pos()  or  pygame.key.get_pressed() . 。。
这个可以用来判断是否同时两个按键被按下
if (key.get_pressed[K_t] and key.get_pressed[K_f]):

二)队列系统
这个可以保存所有未处理的事件。

4)ColorKey Vs Alpha

Alpha可以设置透明程度,并作用到每一个像素,而ColorKey则表明某一特殊颜色完全透明

这两个比较容易混淆,ColorKey是在surface中blit的时候告诉surface哪一种颜色是用来透过的,即所有的colorkey在blit时不进行copy

alpha
a.RGB即是代表红、绿、蓝三个通道的颜色,所以有3个通道,这3个通道显示的是当前图片三原色的比例.
b.Alpha通道是一个8位的灰度通道,该通道用256级灰度来记录图像中的透明度信息,定义透明、不透明和半透明区域,其中黑表示全透明,白表示不透明,灰表示半透明。
c.RGB通道是颜色通道,Alpha通道是透明度通道

你可能感兴趣的:(pygame常识&技巧(1))