这是vector2
模块:不能得到这个Python程序工作
class Vector2(object):
"this calculates the vector between two points"
def __init__(self , x = 0.0, y = 0.0):
self.x = x
self.y = y
def __str__(self):
return "(%s,%s)"%(self.x, self.y)
@classmethod
def from_points(cls,p1,p2):
return cls(p2[0]-p1[0],p2[1]-p1[1])
#the magnetude of a vector is the distance between two points
def get_magnetude(self):
return math.sqrt(self.x**2+self.y**2)
def normalize(self):
magnetude = self.get_magnetude()
self.x /= magnetude
self.y /= magnetude
#rhs stands for right hand side
def __add__(self,rhs):
return Vector2(self.x + rhs.x,self.y+rhs.y)
def __sub__(self,rhs):
return Vector2(self.x-rhs.x,self.y-rhs.y)
def __neg__(self):
return Vector2(-self.x, -self.y)
def __mul__(self,scalar):
return Vector2(self.x*scalar,self.y*scalar)
def __div__(self,scalar):
return Vector2(self.x /scalar, self.y/scalar)
这是主程序,其中进口vector2
:
background_image_file = 'download.jpeg'
sprite_image_file = 'images.jpeg'
import math
import pygame
from pygame.locals import*
from sys import exit
import vector2
pygame.init()
screen = pygame.display.set_mode((640,480), 0 ,32)
background = pygame.image.load(background_image_file).convert()
sprite = pygame.image.load(sprite_image_file).convert_alpha()
clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)#the starting point coordonates
heading = Vector2()#a vector without its magnetude(unit vector)
speed = 250.0
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == MOUSEBUTTONDOWN:
destination_x = event.pos[0]-sprite.get_width()/2
destination_y =event.pos[1]-sprite.get_height()/2
destination = (destination_x, destination_y)
heading = Vector2.get_magnetude(position,destination)#
heading.normalize()#a vector without magnetude,just direction
screen.blit(background, (0,0))
screen.blit(sprite, position)
time_passed = clock.tick()
time_passed_seconds = time_passed/1000.0
distance_moved = time_passed_seconds * speed
position += (heading * distance_moved)
pygame.display.update()
我正在学习Python和pygame的通过我的自我(用Python和Pygame开始游戏开发 - 从新手到专业(2007)),我无法让程序工作。也可以有人请向我解释为什么作者使用position = Vector2(100.0,100.0)
和position = Vector2()
来创建新的载体?
口口声声说:
traceback (most recent call last):
File "/home/moussa/Documents/python /vector_movement.py", line 21, in <module>
position = Vector2(100.0, 100.0)#the starting point coordonates
NameError: name 'Vector2' is not defined
@adchilds这是不正确的。假设类Vector2处于文件vector2中,需要使用vector2.Vector2来引用它,或者使用from vector2 import Vector2来引用它。 –
问题中所显示的代码是在一个文件中显示的,还是在“#主程序从这里开始”的评论中是两分为二?如果它是全部在一个文件中,你得到的异常没有任何意义,但如果顶部部分在'vector2.py'中,则会发生异常。 – Blckknght
它实际上是两个独立的代码,但在同一个文件夹内。因此,我只是导入了Vector2以便使用它。 – user2983686