Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Slope-intercept form and distance calculations solution in Clear category for Shooting Range by kkkkk
from math import sqrt
def slope(pt1, pt2):
"""Return slope of a line given two points."""
if pt2[0] - pt1[0] == 0:
return 0
return (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])
def distance(pt1, pt2):
"""Return the distance between two points."""
return sqrt((pt2[0] - pt1[0])**2 + (pt2[1] - pt1[1])**2)
def shot(wall1, wall2, shot_point, later_point):
"""Calculate the score of a shot against a wall, ignoring wall height."""
# Determine mid-point of wall.
midpt_x = (wall1[0] + wall2[0]) / 2
midpt_y = (wall1[1] + wall2[1]) / 2
# Use the slope-intercept form (y = mx + b) to determine the
# intersection of the wall and the shot trajectory. Begin by
# calculating the slope and the value for 'b', then use those
# values to determine y and x.
wall_slope = slope(wall2, wall1)
wall_bval = wall1[1] - (wall_slope * wall1[0])
# Handle the special cases where the shot or wall is vertical.
if later_point[0] == shot_point[0]:
x_intercept = later_point[0]
y_intercept = (wall_slope * x_intercept) + wall_bval
else:
shot_slope = slope(later_point, shot_point)
shot_bval = shot_point[1] - (shot_slope * shot_point[0])
if wall1[0] == wall2[0]:
x_intercept = wall1[0]
else:
x_intercept = (wall_bval - shot_bval) / (shot_slope - wall_slope)
y_intercept = (shot_slope * x_intercept) + shot_bval
mid_to_intercept = distance((midpt_x, midpt_y), (x_intercept, y_intercept))
mid_to_end = distance((midpt_x, midpt_y), wall2)
if mid_to_intercept > mid_to_end:
# The interception point is somewhere past a wall endpoint.
return -1
elif distance(shot_point, (x_intercept, y_intercept)) < \
distance(later_point, (x_intercept, y_intercept)):
# The shooter is shooting away from the wall. The distance from
# the shot point to the wall interception point is less than the
# distance from the bullet endpoint to the wall interception point.
return -1
else:
# Otherwise, the wall was hit; determine where.
relative_distance = round(100 - ((mid_to_intercept / mid_to_end) * 100))
return relative_distance
March 12, 2017
Comments: