from __future__ import division def setup(): """ test line_intersect() with visual and textual output """ (a, b), (c, d) = (4, 0), (6, 10) # try (4, 0), (6, 4) (e, f), (g, h) = (0, 3), (10, 7) # for non intersecting test pt = line_instersect(a, b, c, d, e, f, g, h) scale(9) line(a, b, c, d) line(e, f, g, h) if pt: x, y = pt stroke(255) point(x, y) println(pt) # prints x, y coordinates or 'None' def line_instersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2): """ returns a (x, y) tuple or None if there is no intersection """ d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) if d: uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d else: return if not(0 <= uA <= 1 and 0 <= uB <= 1): return x = Ax1 + uA * (Ax2 - Ax1) y = Ay1 + uA * (Ay2 - Ay1) return x, y