# 用python写游戏 - 从入门到精通16

## 距离的魔法

```import pygame
from pygame.locals import *
from random import randint

class Star(object):

def __init__(self, x, y, speed):

self.x = x
self.y = y
self.speed = speed

def run():

pygame.init()
screen = pygame.display.set_mode((640, 480)) #, FULLSCREEN)

stars = []

# 在第一帧，画上一些星星
for n in xrange(200):

x = float(randint(0, 639))
y = float(randint(0, 479))
speed = float(randint(10, 300))
stars.append( Star(x, y, speed) )

clock = pygame.time.Clock()

white = (255, 255, 255)

while True:

for event in pygame.event.get():
if event.type == QUIT:
return
if event.type == KEYDOWN:
return

# 增加一颗新的星星
y = float(randint(0, 479))
speed = float(randint(10, 300))
star = Star(640., y, speed)
stars.append(star)

time_passed = clock.tick()
time_passed_seconds = time_passed / 1000.

screen.fill((0, 0, 0))

# 绘制所有的星
for star in stars:

new_x = star.x - time_passed_seconds * star.speed
pygame.draw.aaline(screen, white, (new_x, star.y), (star.x+1., star.y))
star.x = new_x

def on_screen(star):
return star.x > 0

# 星星跑出了画面，就删了它
stars = filter(on_screen, stars)

pygame.display.update()

if __name__ == "__main__":
run()```

## 理解3D空间

3D空间的事情，基本就是立体几何的问题，高中学一半应该就差不多理解了，这里不多讲了。你能明白下图的小球在(7, 5, 10)的位置，换句话说，如果你站在原点，面朝Z轴方向。那么小球就在你左边7，上面5，前面10的位置。这就够了~

## 使用3D向量

```from gameobjects.vector3 import *
A = Vector3(6, 8, 12)
B = Vector3(10, 16, 12)
print "A is", A
print "B is", B
print "Magnitude of A is", A.get_magnitude()
print "A+B is", A+B
print "A-B is", A–B
print "A normalized is", A.get_normalized()
print "A*2 is", A * 2```

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):