Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Shooting Range solution in Clear category for Shooting Range by JimmyCarlos
class Coordinate:
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return "({},{})".format(self.x,self.y)
def distance_to(self,other) -> float:
"""Uses Pythagoras Theorem to find the distance to another Coordinate object."""
assert type(other) == Coordinate
return ((self.x-other.x)**2 + (self.y-other.y)**2)**0.5
def midpoint(self,other):
"""Finds the Coordinate halfway between two Coordinate objects. Will give floats."""
assert type(other) == Coordinate
return Coordinate((self.x+other.x)/2,(self.y+other.y)/2)
def line_to(self,other):
"""Returns a Line object from this coordinate to another coordinate."""
assert type(other) == Coordinate
dx,dy = other.x - self.x, other.y - self.y
a,b,c = -dy, dx, dx*(self.y) - dy*(self.x)
return Line(a,b,c)
class Line:
def __init__(self,a,b,c):
# Line is defined as ax+by=c
self.a = a
self.b = b
self.c = c
def __repr__(self):
return "{}x+{}y={}".format(self.a,self.b,self.c)
def intersection(self,other):
"""Finds the oordinate of the point where two lines meet"""
assert type(other) == Line
a1,b1,c1,a2,b2,c2 = self.a,self.b,self.c,other.a,other.b,other.c
x = (c1*b2-c2*b1) / (b2*a1-b1*a2)
y = (c1*a2-c2*a1) / (b1*a2-b2*a1)
return Coordinate(x,y)
def distance_to(self,other):
"""Finds the shortest distance from a Coordinate object to this line."""
assert type(other) == Coordinate
# Equation of line is ax + by = c₁
a,b,c1 = self.a,self.b,self.c
# Perpendicular to original through (x₂,y₂) is bx + -ay = c₂, with c₂ = bx₂ - ay₂
c2 = b*other.x - a*other.y
# Using simultaneous equations, we can find the coordinate (x,y) where these 2 lines meet.
x = (a*c1 + b*c2) / (a**2 + b**2)
y = (b*c1 - a*c2) / (a**2 + b**2)
intersection_coordinate = Coordinate(x,y)
# Now use Pythagoras' Theorem to find the distance from the original point to the new point.
return other.distance_to(intersection_coordinate)
def shot(wall_start,wall_end,shot_start,shot_end):
wall_start, wall_end = Coordinate(*wall_start), Coordinate(*wall_end)
shot_start, shot_end = Coordinate(*shot_start), Coordinate(*shot_end)
wall_centre = wall_start.midpoint(wall_end)
wall_length = wall_start.distance_to(wall_end)
wall, shot = wall_start.line_to(wall_end), shot_start.line_to(shot_end)
if wall.distance_to(shot_start) <= wall.distance_to(shot_end): return -1 # Going in wrong direction.
impact_point = wall.intersection(shot)
distance_from_target = impact_point.distance_to(wall_centre)
score = round(100 * (1 - distance_from_target/(wall_length/2)),0)
return score if score >= 0 else -1
Aug. 13, 2019
Comments: