Python A* algorithm not searching appropriately - python

So I'm trying to write a Python implementation of the A* algorithm. My algorithm finds the path to the target without trouble, but when I get the program to visualize the closed and open lists, I notice that the closed list, whenever the obstacles are a little complicated, will balloon into a large, perfect diamond shape. In other words, my algorithm is adding nodes to the closed list that are significantly further from the target than any of the neighbors of the "expected" closed list should be.
To illustrate, when a point in the closed list is (2, 1) away from the target, but a wall is blocking the way, the algorithm will add both the node at (2, 2) away from the target (to try and get over the wall) and the algorithm at (3, 1) away from the target... for no good reason, since it's clearly further.
I'm not sure what I'm doing wrong. This distance calculation is meant to use the "Manhattan method" (imperfect for my purposes, but it shouldn't be causing such problems), but other methods continue to offer the same problem (or indeed worse problems).
def distance(self, tile1, tile2):
self.xDist = abs(tile1.col * TILE_SIZE - tile2.col * TILE_SIZE)
self.yDist = abs(tile1.row * TILE_SIZE - tile2.row * TILE_SIZE)
self.totalDist = self.straightCost * (self.xDist + self.yDist)
return self.totalDist
The code for filling the closed list looks like this. Here, .score2 is the H value, calculated using the distance method shown above.
while self.endTile not in self.openList:
self.smallestScore = MAX_DIST * 50
self.bestTile = None
for tile in self.openList:
if tile.score[2] <= self.smallestScore:
self.bestTile = tile
self.smallestScore = tile.score[2]
self.examine(self.bestTile)
The "examine" function adds the examined tile to the closed list and its viable neighbors to the open list, and seems to be working fine. The algorithm appears to be admitting all tiles with an H score of X (where X varies depending on the complexity of the maze the target is set in).
Slowing it down to a node-by-node visualization basically reveals that it is filling in an area of size X, and finds the path when the entrance into the maze is hit by the fill. I really have no clue what I'm doing wrong, and I've been trying to puzzle this out for two days now.
EDIT: in the interest of solving the problem, here is a fuller extract of code. This is the examine() function:
def examine(self, tile):
#Add the tile to the closed list, color it in, remove it from open list.
self.closedList.append(tile)
tile.color = CLOSED
pygame.draw.rect(windowSurface, tile.color, tile.rect)
pygame.display.update(tile.rect)
self.openList.remove(tile)
#Search all neighbors.
for a, b in ((tile.col + 1, tile.row), (tile.col - 1, tile.row),
(tile.col + 1, tile.row + 1), (tile.col + 1, tile.row - 1),
(tile.col - 1, tile.row + 1), (tile.col - 1, tile.row - 1),
(tile.col, tile.row + 1), (tile.col, tile.row - 1)):
#Ignore if out of range.
if a not in range(GRID_WIDTH) or b not in range(GRID_HEIGHT):
pass
#If the neighbor is pathable, add it to the open list.
elif self.tileMap[b][a].pathable and self.tileMap[b][a] not in self.openList and self.tileMap[b][a] not in self.closedList:
self.where = abs((a - tile.col)) + abs((b - tile.row))
if self.where == 0 or self.where == 2:
self.G = tile.score[1] + self.diagCost
self.H = self.distance(self.endTile, self.tileMap[b][a])
self.F = self.G + self.H
elif self.where == 1:
self.G = tile.score[1] + self.straightCost
self.H = self.distance(self.endTile, self.tileMap[b][a])
self.F = self.G + self.H
#Append to list and modify variables.
self.tileMap[b][a].score = (self.F, self.G, self.H)
self.tileMap[b][a].parent = tile
self.tileMap[b][a].color = OPEN
pygame.draw.rect(windowSurface, self.tileMap[b][a].color, self.tileMap[b][a].rect)
pygame.display.update(self.tileMap[b][a].rect)
self.openList.append(self.tileMap[b][a])
#If it's already in one of the lists, check to see if this isn't a better way to get to it.
elif self.tileMap[b][a] in self.openList or self.tileMap[b][a] in self.closedList:
self.where = abs((a - tile.col)) + abs((b - tile.row))
if self.where == 0 or self.where == 2:
if tile.score[1] + self.diagCost < self.tileMap[b][a].score[1]:
self.tileMap[b][a].score = (self.tileMap[b][a].score[0], tile.score[1] + self.diagCost, self.tileMap[b][a].score[2])
self.tileMap[b][a].parent = tile
print "parent changed!"
elif self.where == 1:
if tile.score[1] + self.straightCost < self.tileMap[b][a].score[1]:
self.tileMap[b][a].score = (self.tileMap[b][a].score[0], tile.score[1] + self.straightCost, self.tileMap[b][a].score[2])
self.tileMap[b][a].parent = tile
print "parent changed!"
And this is a newer version of the iteration that slows down so I can watch it progress. It is meant to find the node with the lowest score[0] (score is a tuple of F, G, H scores).
def path(self):
self.openList.append(self.startTile)
self.startTile.score = (self.distance(self.startTile, self.endTile), 0, self.distance(self.startTile, self.endTile))
self.examine(self.openList[0])
self.countDown = 0
while self.endTile not in self.openList:
if self.countDown <= 0:
self.countDown = 5000
self.smallestScore = MAX_DIST * 50
self.bestTile = self.startTile
for tile in self.openList:
if tile.score[0] <= self.smallestScore:
self.bestTile = tile
self.smallestScore = tile.score[0]
self.examine(self.bestTile)
else:
self.countDown -= timePassed
The following is an image illustrating the excess search area, using self.totalDist = self.diagCost * math.sqrt(pow(self.xDist, 2) + pow(self.yDist, 2))
Alternatively, removing the TILE_SIZE constant from the equation gets me this equally inefficient-looking search area:
It seems to me that it shouldn't be searching all that extra area - just the area immediately surrounding the obstacles.

My theory: it's because Manhattan distance is not admissible in this case, because you can move diagonal as well.
Try this:
def distance(self, tile1, tile2):
self.xDist = abs(tile1.col * TILE_SIZE - tile2.col * TILE_SIZE)
self.yDist = abs(tile1.row * TILE_SIZE - tile2.row * TILE_SIZE)
self.totalDist = self.diagCost * math.sqrt(self.xDist*self.xDist + self.yDist*self.yDist)
# or it might be self.straightCost, depending on their values.
# self.diagCost is probably right, though.
return self.totalDist

Related

2D Pathfinding with variable movement speed?

Hi I'm pretty new to the path-finding field and I have searched all around the interwebs for an answer to my question so I figured its time to ask the experts:
My environment consists of a 2D rectangular map with walls and units to traverse the environment
(no collision between units but they can't go through walls)
Units in the environment move in a turn-based fashion in a straight line but they can move at a speed of
0 to unit.movespeed (e.g. 5)(you have control over the movespeed for every movement). (map size is range is from 20,20 to 200,200 cells but you can move to floating-point locations add walls can be at a location like eg wall[(x=10.75,y=9.34),(x=33.56,y=62.43])
In summery every tick, you tell a unit to move to a destination (x,y) of type float
I have tried A* and goal-based vector pathfinding algorithms but the problem I keep running into is figuring out how fast they should move because obviously, the optimal movespeed should be the maximum speed yet if they always move at the maximum speed they are prone to hit a wall because these algorithms don't take into account variable movement speed.
Any Ideas?
image of movespeed issue with a* star and goal-based vector pathfinding problem
Code:
class Cell:
def __init__(self,coords,vector=None,distance=None,obstacle=False):
self.coords = coords
self.vector = vector
self.distance = distance
self.obstacle = obstacle
class VectorMap:
def __init__(self,unit, dest, map=HardCoded._make_map()):
self.size = Coords(len(map), len(map[0]))
self.map = map
VectorMap.map_converter()
self.unit = unit
self.dest = dest
def _create_vector_map(self):
return self._cell_def(1,self.map[self.dest])
def _cell_def(self,dist,current_cell):
neighbors = [Coords(0, 1), Coords(0, -1), Coords(1, 0), Coords(-1, 0), Coords(1, 1), Coords(1, -1),
Coords(-1, 1), Coords(-1, -1)]
for neighbor in neighbors:
#check if out of range of arr then return map
if current_cell.coords.y + neighbor.y < self.size[1] and current_cell.coords.x + neighbor.x < self.size[0]:
neighbor_cell = self.map[current_cell.coords.x + neighbor.x][current_cell.coords.y + neighbor.y]
if neighbor_cell.obstacle:
continue
neighbor_cell.distance = dist
#neighbor_cell.vector = current_cell
return self._cell_def(self.map,dist+1,neighbor_cell)
def map_converter(self):
nmap = []
for x,element in enumerate(self.map):
tmap = []
for y,value in enumerate(element):
tmap.append(Cell(Coords(x,y),vector=None,distance=None,obstacle=False if value == 0 else True))
nmap.append(tmap)
self.map = nmap
self._create_vector_map()
for x,c in enumerate(self.map):
for y,cell in enumerate(c):
cell.vector = Coords(0,0)
right_tile_distance = (self.map[x+1][y].distance if x+1 < self.size.x else self.map[x][y].distance)
up_tile_distance = (self.map[x][y+1].distance if y+1 < self.size.y else self.map[x][y].distance)
cell.vector.x = (self.map[x-1][y].distance if x is not 0 else self.map[x][y].distance) - right_tile_distance
cell.vector.y = up_tile_distance - (self.map[x][y-1].distance if y is not 0 else self.map[x][y].distance)
if cell.vector.x == 0 and right_tile_distance < self.map[x][y].distance:
cell.vector.x = 1
if cell.vector.y == 0 and up_tile_distance < self.map[x][y].distance:
cell.vector.y = 1
cell.vector = Util.normalize(cell.vector)
def vetor_move(self):
vector = self.map[self.unit.coords.x][self.unit.coords.y].vector
movespeed = self.desired_movespeed()
dest = Coords(vector.x * movespeed,vector.y * movespeed)
return Action(mechanic='move', params=[dest], report='Moving With Maths')
def desired_movespeed(self):
pass
class Util:
#staticmethod
def normalize(vector):
norm=np.linalg.norm(vector,ord=1)
if norm == 0:
norm = np.finfo(vector.dtype).eps
return Coords(*(vector/norm))

Why is the tower defense path all messy when I try to eliminate the tower placment on the path?

I want to finish my tower defense game as fast as I can.
I have trouble with if the tower is on the path with a given path list.
It will never work even is I try as hard as I can.
I already tried a lot of times to solve that problem like tech with tim's tower defense youtube tutorial. It made almost perfect sense why it was not working.
But no matter how hard I try, It seems to never work properly.
Find the link to the tutorial here.
WARNING:The video is pretty long.
x, y = tower.x, tower.y
for n, point in enumerate(path):
point_x, point_y = point[0], point[1]
dis_x = abs(point_x - x)
dis_y = abs(point_y - y)
dis = math.sqrt((dis_x - x)**2 + (dis_y - y)**2)
print(dis)
if dis < 130:
return False
return True
You might be thinking 'Why did I do this' so I changed it a bit:
import numpy as np
closest = []
x, y = tower.x, tower.y
for n, point in enumerate(path):
point_x, point_y = point[0], point[1]
dis_x = abs(point_x - x)
dis_y = abs(point_y - y)
dis = math.sqrt((dis_x - x)**2 + (dis_y - y)**2)
print(dis)
if len(closest) <= 2:
if dis < 130:
closest.append(point)
p1 = np.array([x, y])
p2 = np.array(closest[0])
p3 = np.array(closest[1])
dis = np.cross(p2-p1,p3-p1)/np.linalg.norm(p2-p1)
if dis < 90:
return False
return True
I did not recive any error messages, but you can still place towers on some spots on the path,
and you can't place towers on some points not on the path, and I was expecting it to be pretty neat.
As #ImperishableNight stated, the issue is that your function only compares each point on the path and checks if the distance is less than a certain threshold (130 pixels in your case). But this is not enough, since we are not only interested in the end points in each segment of the path, but also all of the points in between. For that, we need to calculate the distance between a point and a line segment.
I have written and commented on the following code using a simple Point class to replace whatever pygame provides. I break the problem up into a bunch of tiny functions to solve your problem. Please let me know if any of this is unclear.
import math
import random
class Point:
def __init__(self, x=0, y=0):
"""
A really simple Point class.
Replaces whatever pygame provides for this example.
"""
self.x = x
self.y = y
def __repr__(self):
"""
A convenient representation of a Point class.
So we see the x and y values when printing these objects.
"""
return "({0}, {1})".format(self.x, self.y)
def gen_rand_point(width, height):
"""
Creates random x and y values for a Point object
"""
rand_x = random.randint(0, width)
rand_y = random.randint(0, height)
point = Point(x=rand_x, y=rand_y)
return point
def gen_rand_point_list(width, height, num_points):
"""
Creates a list of random points using the previous function.
"""
points = []
for i in range(num_points):
point = gen_rand_point(width, height)
points.append(point)
return points
def points_to_segments(points, loop=False):
"""
Converts a list of points into a list of segments.
Offsets the point list and zips it to create "segments".
A segment is just a tuple containing two Point objects.
"""
starts = points
ends = points[1:] + [points[0]]
segments = list(zip(starts, ends))
if loop:
return segments
else:
return segments[:-1]
def calc_sqr_dist(point_a, point_b):
"""
Calculates the square distance between two points.
Can be useful to save a wasteful math.sqrt call.
"""
delta_x = point_b.x - point_a.x
delta_y = point_b.y - point_a.y
sqr_dist = (delta_x ** 2) + (delta_y ** 2)
return sqr_dist
def calc_dist(point_a, point_b):
"""
Calculates the distance between two points.
When you need a wasteful math.sqrt call.
"""
sqr_dist = calc_sqr_dist(point_a, point_b)
dist = math.sqrt(sqr_dist)
return dist
def calc_dot_product(segment_a, segment_b):
"""
Calculates the dot product of two segments.
Info about what the dot product represents can be found here:
https://math.stackexchange.com/q/805954
"""
a0, a1 = segment_a
b0, b1 = segment_b
ax = a1.x - a0.x
ay = a1.y - a0.y
bx = b1.x - b0.x
by = b1.y - b0.y
dot = (ax * bx) + (ay * by)
return dot
def calc_point_segment_dist(point, segment):
"""
Gets the distance between a point and a line segment.
Some explanation can be found here:
https://stackoverflow.com/a/1501725/2588654
"""
start, end = segment
sqr_dist = calc_sqr_dist(start, end)
#what if the segment's start and end are the same?
if sqr_dist == 0:
dist = calc_dist(point, start)
return dist
#what if it is not that easy?
else:
segment_a = (start, point)
segment_b = (start, end)#really is just segment...
dot = calc_dot_product(segment_a, segment_b)
t = float(dot) / sqr_dist
clamped_t = max(0, min(1, t))#clamps t to be just within the segment
#the interpolation is basically like a lerp (linear interpolation)
projection = Point(
x = start.x + (t * (end.x - start.x)),
y = start.y + (t * (end.y - start.y)),
)
dist = calc_dist(point, projection)
return dist
def calc_point_path_dist(point, path):
"""
Gets the distances between the point and each segment.
Then returns the minimum distance of all of these distances.
"""
dists = [calc_point_segment_dist(point, segment) for segment in path]
min_dist = min(dists)
return min_dist
if __name__ == "__main__":
"""
A fun example!
"""
width = 800
height = 600
num_path_points = 5
tower_range = 50
tower = gen_rand_point(width, height)
path_points = gen_rand_point_list(width, height, num_path_points)
path = points_to_segments(path_points)
dist = calc_point_path_dist(tower, path)
in_range = dist <= tower_range
print(dist, in_range)

Click-Circle game - clicking outside and inside the circle

I am trying to code a game that has a red circle in which the user is supposed to click up to 7 times in the window. If the user clicks outside the circle, the circle will change its position to where the user clicked. And the game should end when the user has clicked 3 times inside the circle (does not have to be in a row) or when the user has clicked 7 times in total.
I have coded and done quite most of it I think, its just I cant seem to make it work as I want to.
from graphics import *
def draw_circle(win, c=None):
x = random.randint(0,500)
y = random.randint(0,500)
if var is None:
centa = Point(x,y)
var = Circle(centa,50)
var.setFill(color_rgb(200,0,0))
var.draw(win)
else:
p1 = c.p1
x_dif = (p1.x - x) * -1
y_dif = (p1.y - y) * -1
var.move(x_dif, y_dif)
return (var, x, y)
def main():
win= GraphWin("game",800,800)
score = 0
var,x,y = draw_circle(win)
while score <= 7:
mouseClick2=win.getMouse()
if mouseClick2.y >= y-50 and mouseClick2.y <= y +50 and
mouseClick2.x >= x-50 and mouseClick2.x <= x+50:
score=score + random.randint(0,5)
var,x,y = draw_circle(win, c)
print ("Success!")
print (("the score is, {0}").format(score))
thanks for the help in advance!
I see a couple problems.
your if mouseClick2.y >= y-50... conditional is spread out on two lines, but you don't have a line continuation character.
You never call main().
You don't import random.
You call draw_circle in the while loop with an argument of c, but there is no variable by that name in the global scope. You probably meant to pass in var.
c in draw_circle ostensibly refers to the circle object you want to manipulate, but half the time you manipulate var instead of c.
you assign a value to cvar in the loop, but never use it.
Your else block in draw_circle calculates the movement delta by subtracting the cursor coordinates from c.p1. But c.p1 is the upper-left corner of the circle, not the center of the circle. So your hit detection is off by fifty pixels.
import random
from graphics import *
def draw_circle(win, c=None):
x = random.randint(0,500)
y = random.randint(0,500)
if c is None:
centa = Point(x,y)
c = Circle(centa,50)
c.setFill(color_rgb(200,0,0))
c.draw(win)
else:
center_x = c.p1.x + 50
center_y = c.p1.y + 50
x_dif = (center_x - x) * -1
y_dif = (center_y - y) * -1
c.move(x_dif, y_dif)
return (c, x, y)
def main():
win= GraphWin("game",800,800)
score = 0
var,x,y = draw_circle(win)
while score <= 7:
mouseClick2=win.getMouse()
if mouseClick2.y >= y-50 and mouseClick2.y <= y +50 and \
mouseClick2.x >= x-50 and mouseClick2.x <= x+50:
score=score + random.randint(0,5)
var,x,y = draw_circle(win, var)
print ("Success!")
print (("the score is, {0}").format(score))
main()
Additional possible improvements:
Your hit detection checks whether the cursor is in a 50x50 rectangle centered on the circle. You could instead check whether the cursor is inside the circle if you measured the distance between the cursor and the center, and checked whether it was less than the radius.
var and c could stand to have more descriptive names.
mouseClick2 doesn't make much sense as a name, considering there's no mouseClick1.
The movement delta arithmetic could be simplified: (a-b) * -1 is the same as (b-a).
If you only use a variable's value once, you can sometimes avoid creating the variable at all if you nest expressions.
it might be nice to define constants, such as for the circle's radius, instead of having magic numbers in your code.
You can save five characters by using += to increment the score.
import math
import random
from graphics import *
RADIUS = 50
def draw_circle(win, circle=None):
x = random.randint(0,500)
y = random.randint(0,500)
if circle is None:
circle = Circle(Point(x,y),RADIUS)
circle.setFill(color_rgb(200,0,0))
circle.draw(win)
else:
circle.move(
x - circle.p1.x - RADIUS,
y - circle.p1.y - RADIUS
)
return (circle, x, y)
def main():
win= GraphWin("game",800,800)
score = 0
circle,x,y = draw_circle(win)
while score <= 7:
cursor = win.getMouse()
if math.hypot(cursor.x - x, cursor.y - y) <= RADIUS:
score += random.randint(0,5)
circle,x,y = draw_circle(win, circle)
print ("Success!")
print (("the score is, {0}").format(score))
main()
I'm not really a python guy, but I see that your hitbox is wrong. If there are any other issues then comment it/them to me.
Solving hitbox to be circle:
What you have already written is good to have thing but you should check if click was in circle not square. Pythagoras triangle is solution for this.
Check:
if (math.sqrt(delta_x **2 + delta_y **2) <= circle_radius)
where delta_x and delta_y is center coordinate minus mouse position

Graphics.py: Check if point is in Object

In short, I want to make a radar of sorts, using specifically the graphics.py library, that detects if pre-drawn Shape exists at a Point.
Below I've drafted up a code that will show me all the points within a radar (and return it as an array), but I want to be able to take a point/coordinate and check if it is inside a Circle or Rectangle etc without knowing anything else (i.e only x and y parameters, no knowledge of other existing Shapes). Something like:
if Point(x,y).getObject() is None:
return False
or even
if Point(x,y).getObject().config["fill"] == "#f00":
return True
Here's what I've done so far:
from graphics import *
def getAllPointsInRadius(circle, win):
cx = int(circle.getCenter().getX())
cy = int(circle.getCenter().getY())
r = circle.getRadius()# + 2
points = []
print cx, cy
for i in range(cx-r, cx+r):
for j in range(cy-r, cy+r):
x = i-circle.getRadius()
y = j - circle.getRadius()
if ((i - cx) * (i - cx) + (j - cy) * (j - cy) <= r * r):
points.append(Point(i,j)) #if within, append as Point
p = Point(i, j)
p.setFill('#551A8B')
p.draw(win) #illustrate all points inside radar
else:
p = Point(i, j)
p.setFill('#0000ff')
p.draw(win) #points outside
return points
win = GraphWin('Radar', width = 500, height = 500)
win.setCoords(0, 0, 30, 30)
win.setBackground('black')
#object to be detected
objectCircle = Circle(Point(11, 12), 2)
objectCircle.setFill('#f00')
objectCircle.draw(win)
#radius within objects may be detected
radiusCircle = Circle(Point(10, 10), 3)
radiusCircle.setOutline('#fff')
radiusCircle.draw(win)
print getAllPointsInRadius(radiusCircle, win)
#print Point(11, 12).config["outline"]
win.getMouse()
Addendum: I think maybe by making Point(x,y) I'm actually creating a point and not returning the coordinates. I'm not sure how to do it otherwise, though.

Distance between two objects

So I've been trying to figure out how to find the distance between two objects on a canvas and I've exhausted most relevant links on Google with little success.
I'm trying to make it so that it calculates the distance between the drawn ovals and the line on the canvas.
from __future__ import division
from Tkinter import *
import tkMessageBox
class MyApp(object):
def __init__(self):
self.root = Tk()
self.root.wm_title("Escape")
self.canvas = Canvas(self.root, width=800, height=800, bg='white')
self.canvas.pack()
self.canvas.create_line(100, 100, 200, 200, fill='black')
self.canvas.bind("<B1-Motion>", self.tracer)
self.root.mainloop()
def tracer(self, e):
self.canvas.create_oval(e.x-5, e.y-5, e.x+5, e.y+5, fill='blue', outline='blue')
rx = "%d" % (e.x)
ry = "%d" % (e.y)
print rx, ry
MyApp()
Two circles:
dist = math.sqrt((circle1.x-circle2.x)**2 + (circle1.y-circle2.y)**2) - circle1.r - circle2.r
Kind of obvious, their Euclid distance is calculated using the Pythagorean theorem.
Point/segment:
a = segment[1].y - segment[0].y
b = segment[0].x - segment[1].x
c = - segment[0].x * a - segment[0].y * b
dx = segment[1].x - segment[0].x
dy = segment[1].y - segment[0].y
nc0 = - segment[0].x * dx - segment[0].y * dy
nc1 = - segment[1].x * dx - segment[1].y * dy
if ((dx * x + dy * y + nc0) < 0) dist = math.sqrt((x-segment[0].x)**2 + (y-segment[0].y)**2)
elif((dx * x + dy * y + nc1) < 0) dist = math.sqrt((x-segment[1].x)**2 + (y-segment[1].y)**2)
else dist = (a*x + b*y + c) / math.sqrt(a**2 + b**2)
Circle/segment - same as point/segment, just substract circle's radius
Polygon/polygon - Loop through each vertex of polygon 1 and segment of polygon 2, then loop through each vertex of polygon 2 and segment of polygon 1, then find the smallest.
Don't use magic numbers inside your code. That radius of 5 isn't good.
dist = math.sqrt((oval.x-point.x)**2 + (oval.y-point.y)**2)
not really sure if this answers your question but this is the distance formula
there are several problems with the original question.
at what point are you trying to find the distance?
you are not saving the oval positions so it will be very hard to look up later
why are you trying to get the distance?/what are you planning on doing with it?
are you trying to find distance to edge or distance to center?
in general I would guess you want to get it in the def trace function
step 1. Point of interest is (e.x,e.y)
step 2. Find the closest point on the line (line = (100,100) to (200,200) ) (this is probably a question in its own right. http://nic-gamedev.blogspot.com/2011/11/using-vector-mathematics-and-bit-of_08.html )
step 3. Apply distance method to point of interest and closest point on line
def dist(pt1,pt2):
return ((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)**.5
on another side note ... your ovals look an awful lot like circles ...

Categories