我的教授给了我这段代码,我唯一想做的部分就是TODO区域。我仍然是python的新手,从未接触过这种类型的项目,所以我相当困惑。所有这个项目都是为了得到绘制的图形图像。
import math, random, pylab
class Location(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def move(self, xc, yc):
return Location(self.x+float(xc), self.y+float(yc))
def getCoords(self):
return self.x, self.y
def getDist(self, other):
ox, oy = other.getCoords()
xDist = self.x - ox
yDist = self.y - oy
return math.sqrt(xDist**2 + yDist**2)
class CompassPt(object):
possibles = ('N', 'S', 'E', 'W')
def __init__(self, pt):
if pt in self.possibles: self.pt = pt
else: raise ValueError('in CompassPt.__init__')
def move(self, dist):
if self.pt == 'N': return (0, dist)
elif self.pt == 'S': return (0, -dist)
elif self.pt == 'E': return (dist, 0)
elif self.pt == 'W': return (-dist, 0)
else: raise ValueError('in CompassPt.move')
class Field(object):
def __init__(self, drunk, loc):
self.drunk = drunk
self.loc = loc
def move(self, cp, dist):
oldLoc = self.loc
xc, yc = cp.move(dist)
self.loc = oldLoc.move(xc, yc)
def getLoc(self):
return self.loc
def getDrunk(self):
return self.drunk
class Drunk(object):
def __init__(self, name):
self.name = name
def move(self, field, time = 1):
if field.getDrunk() != self:
raise ValueError('Drunk.move called with drunk not in field')
for i in range(time):
pt = CompassPt(random.choice(CompassPt.possibles))
field.move(pt, 1)这是我需要做的部分,也是我尝试做的部分。到目前为止,我的图表没有移动,哈哈。我在图的中间看到一个点,除非它随机地在一个位置漫游,如果可能的话,哈哈。
# TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
def performTrial(time, f):
start = f.getLoc()
# TODO
distances = [0.0]
for t in range(1, time + 1):
# TODO
f.getDrunk().move(f)
newLoc = f.getLoc()
distance = newLoc.getDist(start)
distances.append(distance)
xcoords, ycoords = distances[::2], distances[1::2]
return xcoords,ycoords
# END OF TODOEND OF TODO END OF TODO END OF TODO END OF TODO剩下的部分也是由教授提供的
drunk = Drunk('Homer Simpson')
for i in range(1):
f = Field(drunk, Location(0, 0))
coords = performTrial(500, f)
print(coords)
pylab.plot(coords[0],coords[1],marker='^',linestyle=':',color='b')
pylab.title('Homer\'s Random Walk')
pylab.xlabel('Time')
pylab.ylabel('Distance from Origin')
pylab.show()更新:修复了坐标,但现在我得到了一个错误:
in _xy_from_xy(self, x, y)
235 y = np.atleast_1d(y)
236 if x.shape[0] != y.shape[0]:
--> 237 raise ValueError("x and y must have same first dimension")
238 if x.ndim > 2 or y.ndim > 2:
239 raise ValueError("x and y can be no greater than 2-D")
ValueError: x and y must have same first dimension 发布于 2014-08-01 17:27:01
def move(self, xc, yc):
return Location(self.x+float(xc), self.y+float(yc))这不会移动任何东西,它只是返回新的坐标。另外,不需要将xc和yc转换为浮点数。
如果此函数用于移动位置,则必须添加以下内容:
def move(self, xc, yc):
self.x += xc
self.y += yc
return Location(self.x, self.y)https://stackoverflow.com/questions/25076873
复制相似问题