PyGame基础知识-Making Games with Python & Pygame

来源:互联网 发布:网络智能家居 编辑:程序博客网 时间:2024/05/18 03:27

1. 例子
例1. 创建一个空窗口

import pygame, sys #退出用到了sysfrom pygame.locals import * #容易使用locals中的变量,但如果模块过多,容易产生混乱pygame.init()#初始化,必须在使用pygame的其他函数之前调用DISPLAYSURF = pygame.display.set_mode((400, 300))#创建一个pygame.Surface对象,操作此对象实现绘图。pygame.display.set_caption('Hello Pygame World!')#标题while True: # 主循环,重复做三件事情:处理event,更新游戏状态,显示游戏状态。     for event in pygame.event.get():#获取上一次调用get()之后的事件队列          if event.type == QUIT:#QUIT这种事件常量来源于pygame.locals               pygame.quit()#init()的逆过程               sys.exit()     pygame.display.update()#将Surface object绘制到屏幕上

函数:如foo()或者somemodule.foo()。
方法:与对象相关,用以改变对象,如object.foo()。
构造函数:与函数一样,只是会返回一个对象,通常首字母大写(因此自己代码中的函数首字母通常小写)。


例2.绘制图形
import pygame, sysfrom pygame.locals import *pygame.init()# set up the windowDISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)#Surface 对象代表了一个2d的矩形画布,调用update()后会显示在屏幕上。32代表使用32颜色值。pygame.display.set_caption('Drawing')# set up the colors#颜色是三元元组(RGB)或四元元组(RGB+alpha value,即透明度,只能用在convert_alpha()返回的surface对象上)BLACK = (  0,   0,   0)#等价BLACK =pygame.Color(0, 0, 0),也就是说颜色对象是一个元组WHITE = (255, 255, 255)RED   = (255,   0,   0)GREEN = (  0, 255,   0)BLUE  = (  0,   0, 255)# draw on the surface objectDISPLAYSURF.fill(WHITE)#填充背景色pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)#宽度,如果没有或者是0,则填充整个图形。pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120))pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4)pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0)pygame.draw.ellipse(DISPLAYSURF, RED, (300, 200, 40, 80), 1)pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50))pixObj = pygame.PixelArray(DISPLAYSURF)#将画布转化为矩阵,可以通过坐标来获取像素值或者修改像素,此函数会将画布锁定,导致不能执行其他的draw操作。pixObj[380][280] = BLACKpixObj[382][282] = BLACKpixObj[384][284] = BLACKpixObj[386][286] = BLACKpixObj[388][288] = BLACKdel pixObj#解除画布的锁定。# run the game loopwhile True:    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()    pygame.display.update()


例3.显示图片
import pygame, sysfrom pygame.locals import *pygame.init()FPS = 30 # frames per second settingfpsClock = pygame.time.Clock()#配合fpsClock.tick(FPS),控制刷新频率,如果执行过快,则会等待一段时间,再进行下一次刷新# set up the windowDISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)pygame.display.set_caption('Animation')WHITE = (255, 255, 255)catImg = pygame.image.load('cat.png')#创建图片catx = 10caty = 10direction = 'right'while True: # the main game loop    DISPLAYSURF.fill(WHITE)    if direction == 'right':        catx += 5        if catx == 280:            direction = 'down'    elif direction == 'down':        caty += 5        if caty == 220:            direction = 'left'    elif direction == 'left':        catx -= 5        if catx == 10:            direction = 'up'    elif direction == 'up':        caty -= 5        if caty == 10:            direction = 'right'    DISPLAYSURF.blit(catImg, (catx, caty))#将一个surface(这里是Image)显示(复制)到另外一个Surface的指定位置,此时Surface不能处于锁定状态    for event in pygame.event.get():        if event.type == QUIT:            pygame.quit()            sys.exit()    pygame.display.update()    fpsClock.tick(FPS)#必须放在最后,这样才能根据程序执行的时间和刷新频率计算需要等待的时间。



例4. 显示文字

fontObj = pygame.font.Font('freesansbold.ttf', 32)#创建字体对象(字体名称和大小)textSurfaceObj = fontObj.render('Hello world!', True, GREEN, BLUE)#渲染为Surface Object。内容,背景色,前景色。True是抗锯齿textRectObj = textSurfaceObj.get_rect()#获取矩形Surface 对象textRectObj.center = (200, 150)......DISPLAYSURF.blit(textSurfaceObj, textRectObj)#显示(复制)到DISPLAYSURF上

例5. 声音

import pygameimport timepygame.mixer.init()#运行之前需要初始化soundObj = pygame.mixer.Sound('beeps.wav')#创建声音对象soundObj.play()#程序会立刻执行下一条指令time.sleep(1) # wait and let the sound play for 1 secondsoundObj.stop()# Loading and playing a sound effect:soundObj = pygame.mixer.Sound('beepingsound.wav')soundObj.play() # Loading and playing background music:pygame.mixer.music.load(backgroundmusic.mp3')pygame.mixer.music.play(-1, 0.0)#-1指无数次循环,从0.0开始# ...some more of your code goes here...pygame.mixer.music.stop()


例6. 断言
assert condition “message“#如果condition不成立,崩溃,显示”message“


例7.事件
Python的事件队列最多容纳127个事件对象,如果满了,新的事件就不能进入队列。
如果取出的对象自己不能处理,则通过post方法将对象放回队列。
def checkForQuit():    for event in pygame.event.get(QUIT): # get all the QUIT events        terminate() # terminate if any QUIT events are present    for event in pygame.event.get(KEYUP): # get all the KEYUP events        if event.key == K_ESCAPE:            terminate() # terminate if the KEYUP event was for the Esc key        pygame.event.post(event) # put the other KEYUP(不是K_ESCAPE) event objects back


例8. main函数
main函数:让你使用局部变量(减少全局变量),还可以导入程序中的单个函数用以测试。
总之是利于代码重用。
def main():......if __name__ == '__main__':    main()#一个.py文件,如果是自身在运行,那么他的__name__值就是"__main__",这个时候执行py中的main函数;#如果它是被别的程序导入的(作为一个模块),比如:#import re#那么,他的__name__就不是"__main__"了,这个时候不会执行main函数,会由主调用函数决定执行那个函数。

例9. 时间
>>> import time>>> time.time()1320460242.118#the moment the time.time() function was called was a little over 1,320,460,242 seconds since midnight of January 1st, 1970. 

2. 语法知识
......

3. 编程习惯
1. 适当使用常量:
     10. WINDOWWIDTH = 640 # size of window's width in pixels
便于修改程序,便于理解程序。

2.使用常量代替字符串:
      DONUT = 'donut'
如果程序写为:if shape == DUNOT:,会报错,而if shape == 'dunot':不会报错。
2. 让代码更整洁,如:
#                            R     G     B
GRAY           = (100, 100, 100)
NAVYBLUE = ( 60,  60, 100)
3. Crash Early and Crash Often! 尽早发现bug

4. 使用不变量如tuple比list的可读性更强,而且略快。

5. Explicit is Better Than Implicit:To make your code more readable, it is better to have your code be explicit (that is, clearly state something even if it might be obvious) rather than implicit (that is, leaving it up to the person reading code to know how it works without outright telling them).

6. Basically, using global variables might make it easier to write your program but they generally make it harder to debug.
Limiting the number of global variables is a good way to keep the code simple and easier to debug. 
Writing code that is readable is a very important skill.
7. 代码可读性更重要:Nobody Cares About a Few Bytes.Nobody Cares About a Few Million Nanoseconds.

参考:
Making Games with Python & Pygame(1~6章):http://inventwithpython.com/pygame/index.html

pygame的文档:http://www.pygame.org/docs/

原创粉丝点击