|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Seternal 于 2017-9-14 22:22 编辑
问题是这样的。总的来说我在学习pygame这个第三方库,目前用的Python是3.6版本,电脑系统为win10。这是背景。然后说一下问题发现的过程。首先,我看的教程是这个用Python和pygame写游戏http://eyehere.net/2011/python-pygame-novice-professional-16/。这位大佬用的版本和我的有些不同,所以在这个过程中有些语法和第三方库的不兼容,有的我迷迷糊糊地改没想到还成功了,但是有的只是伪成功,问题实际上没有得到解决。然后,我切入正题==。我遇到的就是这个我以为我改成功了,实际上是自欺欺人的情况。当前我想先确认一下问题是否出在以下代码上:- import math
- class Vector2(tuple):
- def __new__(typ, x=1.0, y=1.0):
- n = tuple.__new__(typ, (int(x), int(y)))
- n.x = x
- n.y = y
- return n
- def __mul__(self, other):
- return self.__new__(type(self), self.x*other, self.y*other)
- def __divmod__(self, other):
- return self.__new__(type(self), self.x/other, self.y/other)
- def __add__(self, other):
- return self.__new__(type(self), self.x+other.x, self.y+other.y)
- def __sub__(self, other):
- return self.__new__(type(self), self.x-other.x, self.y-other.y)
- def __str__(self):
- return "(%s, %s)"%(self.x, self.y)
- @staticmethod
- def from_points(P1, P2):
- return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
- def get_magnitude(self):
- return math.sqrt( self.x**2 + self.y**2 )
- def normalize(self):
- magnitude = self.get_magnitude()
- if magnitude==0:
- return None
- else:
- self.x /= magnitude
- self.y /= magnitude
复制代码
这个是我在gameobject的vector2中找的代码。我觉得当我的程序运行时,会出现的问题是由normalize函数引发的。因为几乎每一次调用这个函数时都会出现magnitude==0的情况。在今晚之前,为了它不报错,我将原代码改为:
- def normalize(self):
- magnitude = self.get_magnitude()
- if magnitude==0:
- print("magnitude=0!")
- else:
- self.x /= magnitude
- self.y /= magnitude
复制代码
事实上问题依然存在,但是它这样能够运行。直到我遇到了这段代码:
- class GameEntity(object):
- def __init__(self,world,name,image):
- self.world=world
- self.name=name
- self.image=image
- self.location=Vector2(0,0)
- self.destination=Vector2(0,0)
- self.speed=0.
- self.brain=StateMachine()
- self.id=0
- def render(self,surface):
- x,y=self.location
- w,h=self.image.get_size()
- surface.blit(self.image,(x-w/2,y-h/2))
- def process(self,time_passed):
- self.brain.think()
- if self.speed>0 and self.location!=self.destination:
- vec_to_destination=self.destination-self.location
- distance_to_destination=vec_to_destination.get_magnitude()
- [b] heading[/b]=vec_to_destination.[b]normalize()[/b]
- travel_distance=min(distance_to_destination,time_passed*self.speed)
- self.location+=travel_distance*[b]heading[/b]
复制代码
这里是一个游戏实体类的代码,加粗的地方就是与normalize函数相关的变量。运行后它表示heading是一个'NoneType':
File "D:/pycharm/filetem/game14.0.py", line 31, in process
self.location+=travel_distance*heading
TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'
也就是说当调用normalize时返回的是None,也就是说magnitude=0!
到这里我想先确认一件事:就是我的vector2代码是否有误,比如和我的版本不兼容,或者根本不能这么写之类的。由于教程给出的代码对我来说比较大,我只能一个个排除错误,感觉一次性贴一大段代码不太合适,见谅。
然后如果有大佬知道错在何处,请告诉我如何治本。。。毕竟治标的办法我只能骗骗自己TAT。。问题来了躲不掉啊。。
最后,关于这个问题有需要补充的地方敬请提问,我能说明白的定然悉数告知! |
|