pygame学习之对象移动

pygame提供了很多强大的包,使得2D游戏的制作非常简单。

2D游戏一个很重要的方面就是移动对象,然后再贴图。,下面我介绍两种方式,最后一种单独写篇来介绍。(目前我掌握的) :

1、使用pygame.rect:
pygame的文档如是说:

Pygame uses Rect objects to store and manipulate rectangular areas. A Rect can be created from a combination of left, top, width, and height values. Rects can also be created from python objects that are already a Rect or have an attribute named "rect".

Any Pygame function that requires a Rect argument also accepts any of these values to construct a Rect. This makes it easier to create Rects on the fly as arguments to functions.

The Rect functions that change the position or size of a Rect return a new copy of the Rect with the affected changes. The original Rect is not modified. Some methods have an alternate "in-place" version that returns None but effects the original Rect. These "in-place" methods are denoted with the "ip" suffix.

The Rect object has several virtual attributes which can be used to move and align the Rect:


 

    top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h

All of these attributes can be assigned to:

    rect1.right = 10
rect2.center = (20,30)

Assigning to size, width or height changes the dimensions of the rectangle; all other assignments move the rectangle without resizing it. Notice that some attributes are integers and others are pairs of integers.

If a Rect has a nonzero width or height, it will return True for a nonzero test. Some methods return a Rect with 0 size to represent an invalid rectangle.

The coordinates for Rect objects are all integers. The size values can be programmed to have negative values, but these are considered illegal Rects for most operations.

There are several collision tests between other rectangles. Most python containers can be searched for collisions against a single Rect.

The area covered by a Rect does not include the right- and bottom-most edge of pixels. If one Rect's bottom border is another Rect's top border (i.e., rect1.bottom=rect2.top), the two meet exactly on the screen but do not overlap, and rect1.colliderect(rect2) returns false.
--------------------------------------------------------------------------
这段大概说的就是rect包含关于位置的一些属性,可以通过调整这些属性来实现移动。
这样已经很方便了,但。。。

rect对象还提供两个函数,非常方便的实现了移动的功能:
rect.move

rect.move_ip
这两个函数功能都是移动rect对象:
区别在于move_ip改变直接调整对象,move返回一个改变后的对象。
很爽吧?

贴段示例代码:

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 __doc__ = """演示pygame的矩形移动"""
 5 
 6 import os
 7 import sys
 8 import pygame
 9 import time
10 import random
11 from sys import exit
12 from pygame.locals import *
13 
14 
15 WIDTH = 800
16 HEIGHT = 600
17 
18 #非零随机
19 def random_none_zero(m1,m2):
20     n = random.randint(m1, m2)
21 
22     while n == 0:
23         n = random.randint(m1, m2)
24     return n
25 
26 def main():
27     pygame.init()
28 
29     pygame.display.set_caption("move rect")
30     screen = pygame.display.set_mode((WIDTH,HEIGHT),0,32)    
31     pygame.mouse.set_visible(0)
32 
33     rect = pygame.Rect((10,20), (200300))
34 
35     done = False
36     while not done:
37         screen.fill((255,255,255))
38         for event in pygame.event.get():
39             if event.type == QUIT or \
40                 (event.type == KEYDOWN and event.key == K_ESCAPE):
41                     done = True
42                     
43         x = random.randint(-50,50)
44         y = random.randint(-50,50)
45         
46         rect.move_ip(x,y)        
47         pygame.draw.rect(screen,(5,5,5),rect)
48         pygame.display.update()
49         pygame.time.delay(1000)
50     return 0
51 
52 if __name__ == '__main__':
53     main()

 

 

2、使用surface.surface

Surface是pygame中一切图形资源的基础。无论pygame.Rect还是pygame.sprite都是都是通过操作Surface来实现的。直接通过Surface来移动对象,有点麻烦,所以才会有了一些封装。
可以理解为surface就是一张图片,贴到父Surface上就显示出来了。
如果需要移动怎么办?
首先要把父Surface清空,然后对坐标进行设置,最后贴到父Surface上即可。
贴段pygame文档中带的moveit.py中的代码,图片资源我就不提供了,它是封装了个图片对象(也是surface),然后设置坐标移动的。代码很简单。

#!/usr/bin/env python

"""
This is the full and final example from the Pygame Tutorial,
"How Do I Make It Move". It creates 10 objects and animates
them on the screen.

Note it's a bit scant on error checking, but it's easy to read. :]
Fortunately, this is python, and we needn't wrestle with a pile of
error codes.
"""


#import everything
import os, pygame
from pygame.locals import *

#our game object class
class GameObject:
    
def __init__(self, image, height, speed):
        self.speed 
= speed
        self.image 
= image
        self.pos 
= image.get_rect().move(0, height)
    
def move(self):
        self.pos 
= self.pos.move(self.speed, 0)
        
if self.pos.right > 600:
            self.pos.left 
= 0


#quick function to load an image
def load_image(name):
    path 
= os.path.join('data', name)
    
return pygame.image.load(path).convert()


#here's the full code
def main():
    pygame.init()
    screen 
= pygame.display.set_mode((640480))

    player 
= load_image('player1.gif')
    background 
= load_image('liquid.bmp')

    
# scale the background image so that it fills the window and
    #   successfully overwrites the old sprite position.
    background = pygame.transform.scale2x(background)
    background 
= pygame.transform.scale2x(background)

    screen.blit(background, (0, 0))

    objects 
= []
    
for x in range(10):
        o 
= GameObject(player, x*40, x)
        objects.append(o)

    
while 1:
        
for event in pygame.event.get():
            
if event.type in (QUIT, KEYDOWN):
                
return

        
for o in objects:
            screen.blit(background, o.pos, o.pos)
        
for o in objects:
            o.move()
            screen.blit(o.image, o.pos)

        pygame.display.update()



if __name__ == '__main__': main()


 3、使用

 pygame.sprite
这个留给下一篇来写。

posted @ 2011-03-04 16:53  飘啊飘  阅读(6980)  评论(0编辑  收藏  举报