前一篇
说明我写这个系列是为了给初学者展示一些思路和技巧,很多代码不是最优的。如果有朋友对构架有不同看法,欢迎指正。
这里,继续上个例子展示一些python的技巧。
首先,我们修改Jbutton()类。需要涉及很多的向量计算,这里引入
DVerctor。需要将这个文件考到执行文件相同的目录,import。
DVerctor.py ,可以运行测试一下
################## http://www.pygame.org/wiki/2DVectorClass ##################
import operator
import math
class Vec2d(object):
"""2d vector class, supports vector and scalar operators,
and also provides a bunch of high level functions
"""
__slots__ = ['x', 'y']
def __init__(self, x_or_pair, y = None):
if y == None:
self.x = x_or_pair[0]
self.y = x_or_pair[1]
else:
self.x = x_or_pair
self.y = y
def __len__(self):
return 2
def __getitem__(self, key):
if key == 0:
return self.x
elif key == 1:
return self.y
else:
raise IndexError("Invalid subscript "+str(key)+" to Vec2d")
def __setitem__(self, key, value):
if key == 0:
self.x = value
elif key == 1:
self.y = value
else:
raise IndexError("Invalid subscript "+str(key)+" to Vec2d")
# String representaion (for debugging)
def __repr__(self):
return 'Vec2d(%s, %s)' % (self.x, self.y)
# Comparison
def __eq__(self, other):
if hasattr(other, "__getitem__") and len(other) == 2:
return self.x == other[0] and self.y == other[1]
else:
return False
def __ne__(self, other):
if hasattr(other, "__getitem__") and len(other) == 2:
return self.x != other[0] or self.y != other[1]
else:
return True
def __nonzero__(self):
return bool(self.x or self.y)
# Generic operator handlers
def _o2(self, other, f):
"Any two-operator operation where the left operand is a Vec2d"
if isinstance(other, Vec2d):
return Vec2d(f(self.x, other.x),
f(self.y, other.y))
elif (hasattr(other, "__getitem__")):
return Vec2d(f(self.x, other[0]),
f(self.y, other[1]))
else:
return Vec2d(f(self.x, other),
f(self.y, other))
def _r_o2(self, other, f):
"Any two-operator operation where the right operand is a Vec2d"
if (hasattr(other, "__getitem__")):
return Vec2d(f(other[0], self.x),
f(other[1], self.y))
else:
return Vec2d(f(other, self.x),
f(other, self.y))
def _io(self, other, f):
"inplace operator"
if (hasattr(other, "__getitem__")):
self.x = f(self.x, other[0])
self.y = f(self.y, other[1])
else:
self.x = f(self.x, other)
self.y = f(self.y, other)
return self
# Addition
def __add__(self, other):
if isinstance(other, Vec2d):
return Vec2d(self.x + other.x, self.y + other.y)
elif hasattr(other, "__getitem__"):
return Vec2d(self.x + other[0], self.y + other[1])
else:
return Vec2d(self.x + other, self.y + other)
__radd__ = __add__
def __iadd__(self, other):
if isinstance(other, Vec2d):
self.x += other.x
self.y += other.y
elif hasattr(other, "__getitem__"):
self.x += other[0]
self.y += other[1]
else:
self.x += other
self.y += other
return self
# Subtraction
def __sub__(self, other):
if isinstance(other, Vec2d):
return Vec2d(self.x - other.x, self.y - other.y)
elif (hasattr(other, "__getitem__")):
return Vec2d(self.x - other[0], self.y - other[1])
else:
return Vec2d(self.x - other, self.y - other)
def __rsub__(self, other):
if isinstance(other, Vec2d):