pygame学习之对象移动
pygame提供了很多强大的包,使得2D游戏的制作非常简单。
2D游戏一个很重要的方面就是移动对象,然后再贴图。,下面我介绍两种方式,最后一种单独写篇来介绍。(目前我掌握的) :
1、使用pygame.rect:
pygame的文档如是说:
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)
这两个函数功能都是移动rect对象:
Rect.move
Rect.move_ip
区别在于move_ip改变直接调整对象,move返回一个改变后的对象。Rect.move_ip
- moves the rectangle, in place
Rect.move_ip(x, y): return None
Same as the Rect.move - moves the rectangle method, but operates in place.
很爽吧?
贴段示例代码:
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), (200, 300))
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 # -*- 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), (200, 300))
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((640, 480))
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()
"""
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((640, 480))
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
这个留给下一篇来写。