当前位置:编程学习 > 网站相关 >>

Python:pygame游戏编程之旅一(Hello World)

按照上周计划,今天开始学习pygame,学习资料为http://www.pygame.org/docs/,学习的程序实例为pygame模块自带程序,会在程序中根据自己的理解加入详细注释,并对关键概念做说明。

  一、pygame版本的hello world程序。

代码:


[python]
#!/usr/bin/python  
# -*- coding:utf-8 -*-  
 
import sys 
 
#导入pygame模块,第8行的作用是简化你的输入,如不用在event前再加上pygame模块名  
import pygame 
from pygame.locals import * 
 
def hello_world(): 
    #任何pygame程序均需要执行此句进行模块初始化  
    pygame.init() 
     
    #设置窗口的模式,(680,480)表示窗口像素,及(宽度,高度)  
    #此函数返回一个Surface对象,本程序不使用它,故没保存  
    pygame.display.set_mode((680, 480)) 
     
    #设置窗口标题  
    pygame.display.set_caption('Hello World!') 
     
    #循环,直到接收到窗口关闭事件  
    while True: 
         
        #处理事件  
        for event in pygame.event.get(): 
            #接收到窗口关闭事件  
            if event.type == QUIT: 
                #退出  
                pygame.quit() 
                sys.exit() 
        #将Surface对象上帝绘制在屏幕上          
        pygame.display.update() 
 
if __name__ == "__main__": 
    hello_world() 
     
#!/usr/bin/python
# -*- coding:utf-8 -*-

import sys

#导入pygame模块,第8行的作用是简化你的输入,如不用在event前再加上pygame模块名
import pygame
from pygame.locals import *

def hello_world():
    #任何pygame程序均需要执行此句进行模块初始化
    pygame.init()
   
    #设置窗口的模式,(680,480)表示窗口像素,及(宽度,高度)
    #此函数返回一个Surface对象,本程序不使用它,故没保存
    pygame.display.set_mode((680, 480))
   
    #设置窗口标题
    pygame.display.set_caption('Hello World!')
   
    #循环,直到接收到窗口关闭事件
    while True:
       
        #处理事件
        for event in pygame.event.get():
            #接收到窗口关闭事件
            if event.type == QUIT:
                #退出 www.zzzyk.com
                pygame.quit()
                sys.exit()
        #将Surface对象上帝绘制在屏幕上       
        pygame.display.update()

if __name__ == "__main__":
    hello_world()
    测试:


\


几点需要重点理解的地方:

  1、无限循环

         几乎每个pygame程序均需要它,在它中可以做以下事件:

            a、处理事件

            b、更新游戏状态

            c、在屏幕上绘图

        如下图:

 
\


 

2、pygame.event.get()

      用来获取各种键盘及鼠标事件。

   

 摘自 Socrates的专栏
 

补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,