pygame学习笔记1

来源:互联网 发布:mac虚拟机怎么用 编辑:程序博客网 时间:2024/05/29 06:34

学习资料《用python和pygame写游戏-从精通到入门》

来自:http://simple-is-better.com/news/361

上次我们已经搭建好了python的运行环境,现在我们用python的一个库pygame来写一些简单有趣的小程序。


pygame的下载地址:

http://download.csdn.net/detail/v_xchen_v/7695843


要检验PyGame安装是否正确的话,打开IDLE或通过终端运行Python,在Python提示符处输入import pygame,如果回车后没有输出的话你安装成功了。

如果,另一方面,输出了下附类似错误,PyGame没有正确安装。Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pygame


现在我们来写我们的一个Pygame程序吧,让我们狗狗在草原上跑动

找的图片丑了点,见笑。


我们将这两张图片叠加在窗口中,小图随着鼠标移动

代码如下:

dogrun.py

#!/usr/bin/env python
 
background_image_filename = 'ground.jpg'
mouse_image_filename = 'dog.png'
#set the name of imagefile
 
import pygame
#import pygame
from pygame.locals import *
#import normal functions
from sys import exit
#take exit from sys to close program
 
pygame.init()
#init pygame
 
screen = pygame.display.set_mode((640, 480), 0, 32)
#set a window
pygame.display.set_caption("Hello, World!")
#set window title
 
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
#load and translate image
 
while True:
#game main circle
 
    for event in pygame.event.get():
        if event.type == QUIT:
            #take the quit incident and exit
            exit()
 
    screen.blit(background, (0,0))
    #draw background image
 
    x, y = pygame.mouse.get_pos()
    #get mouse location
    x-= mouse_cursor.get_width() / 2
    y-= mouse_cursor.get_height() / 2
    #calculate cursor top keft cornor 
    screen.blit(mouse_cursor, (x, y))
    #draw cursor
 
    pygame.display.update()

    #refresh frame

?
0 0