Position class:
import math
class Position:
def __init__(self, x, y, speed):
self.x = x
self.y = y
self.dx = 0.0
self.dy = 0.0
if speed < 0:
raise ValueError('Speed cannot be negative')
else:
self.speed = speed
def moveTo(self):
self.x = self.dx
self.y = self.dy
def tick(self):
if self.dx !=
self.x
if pow((self.dx - self.x), 2) > pow(self.speed, 2):
if self.dx > self.x
self.x = self.x + self.speed
else:
self.x = self.x - self.speed
if self.dy !=
self.y
if pow((self.dy - self.y), 2) >
pow(self.speed, 2):
if self.dy > self.y
self.y = self.y + self.speed
else:
self.y = self.y - self.speed
def distance(self, other):
return
math.sqrt(math.pow((self.x - other.x), 2) + math.pow((self.y -
other.y), 2))
Function Tests:
import math Fclass Position: definit__(self, x, y, speed): self.x = x self.y = y self. dx = 0.0 self.dy = 0.0 if speed < 0: raise ValueError('Speed cannot be negative') else: self.speed = speed def moveTo (self): self.x = self.dx self.y = self.dy def tick (self): if self.dx != self.x if pow((self.dx - self.x), 2) > pow (self.speed, 2): if self. dx > self.x self.x = self.x + self.speed else: self.x = self.x - self.speed if self.dy != self.y if pow((self.dy - self.y), 2) > pow (self. speed, 2): if self.dy > self.y self.y = self.y + self.speed else: self.y = self.y - self.speed def distance (self, other): return math.sqrt (math.pow ((self.x - other.x), 2) + math.pow ((self. y - other.y), 2))
In [1]: import math class Position: definit__(self, x, y, speed): self.x = x self.y = y self.dx = 0.0 self.dy = 0.0 if speed < 0 : raise ValueError('Speed cannot be negative') else: self.speed = speed def moveTo(self): self.x = self.dx self.y = self.dy def tick(self): if self.dx != self.x: if pow((self.dx - self.x), 2) > pow(self.speed, 2): if self.dx > self.x: self.x = self.x = self.speed else: self.x = self.x - self.speed if self.dy != self.y: if pow((self.dy - self.y), 2) > pow(self.speed, 2): if self.dy > self.y: self.y = self.y + self.speed else: self.y = self.y - self.speed def distance(self, other): return math.sqrt(math.pow((self.x - other.x), 2) + math.pow((self.y - other.y), 2)) In [2]: p = Position(5.5, -5.5, 0.5) p.tick) print('p.x = ' + str(p.x) + ' p.dx = ' + str(p.dx)) print('p.y = ' + str(p.y) + ' p.dy = ' + str(p.dy)) p.x = 5.0 p.dx = 0.0 p.y = -5.0 p.dy = 0.0 In [3]: 9 = Position(0, 0, -0.5) - - - - - - - ValueError Traceback (most recent call last) <ipython-input-3-d25e53dfd551> in <module> ----> 1 q = Position(0, 0, -0.5) 00 <ipython-input-1-401cc8a0748c> in init__(self, x, y, speed) self.dy = 0.0 if speed < 0: ---> 10 raise ValueError('Speed cannot be negative') 11 else: self.speed = speed ValueError: Speed cannot be negative In [ ]: 9 = Position(-3, 3, 0.5) q.distance(p) In [ ]: p.moveTo() print('p.x = ' + str(p.x) + 'p.dx = ' + str(p.dx)) print('p.y = ' + str(p.y) + 'p.dy = ' + str(p.dy))