惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
IT之家
IT之家
博客园 - 聂微东
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
人人都是产品经理
人人都是产品经理
PCI Perspectives
PCI Perspectives
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 叶小钗
V
Vulnerabilities – Threatpost
美团技术团队
S
Secure Thoughts
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
腾讯CDC
Application and Cybersecurity Blog
Application and Cybersecurity Blog
雷峰网
雷峰网
B
Blog
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
TaoSecurity Blog
TaoSecurity Blog
N
News and Events Feed by Topic
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
T
Tailwind CSS Blog
月光博客
月光博客
Simon Willison's Weblog
Simon Willison's Weblog
Hacker News: Ask HN
Hacker News: Ask HN
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
MongoDB | Blog
MongoDB | Blog
S
Security @ Cisco Blogs
Jina AI
Jina AI
Engineering at Meta
Engineering at Meta
S
Security Affairs
Forbes - Security
Forbes - Security
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
T
Tor Project blog
O
OpenAI News
L
Lohrmann on Cybersecurity
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 飘啊飘

一个精简的vi源码(2000行) dtruss 粗糙的翻译 gdb常用命令[转] gdb中信号的处理[转] 在linux中通过进程名获得进程id busybox0.60.3源码学习开始 pygame做的贪吃蛇 python中使用struct模块处理二进制数据 使用PYGAME开发的坦克游戏[代码][思路] 一篇很好的讲/etc/inittab的文章[转] 哲学家吃空心粉问题 《代码整洁之道》笔记之函数 使用面向对象概念优化条件判断语句的一个小应用 python生成文件树的代码 深入理解软件包的配置、编译与安装[转] pywin32重启电脑 - 飘啊飘 - 博客园 解决LINUX和WINDOWS时间不一置 通过状态机实现的一个配置读取函数 UNIX基础知识--《APUE》第一章笔记
pygame学习之对象移动
飘啊飘 · 2011-03-04 · via 博客园 - 飘啊飘

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):
                
returnfor 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
这个留给下一篇来写。