Here's your updated code with randomized deviation while ensuring the point stays "in front" of the path:
python Copy code
def calculate_next_point(x, y, step_multiplier=1.0, max_deviation=0.0, random_impl=None, random_ret_type=float):
dx = x[-1] - x[-2]
dy = y[-1] - y[-2]
magnitude = (dx**2 + dy**2) ** 0.5
if magnitude == 0:
return random_ret_type(x[-1]), random_ret_type(y[-1]) # Same point if no direction
# Unit direction vector
unit_dx = dx / magnitude
unit_dy = dy / magnitude
# Perpendicular vector for lateral deviation
perp_dx = -unit_dy
perp_dy = unit_dx
# Random deviation (only if parameters are provided)
deviation = 0.0
if random_impl is not None and max_deviation > 0:
deviation = random_impl(-max_deviation, max_deviation)
# Calculate new point with both forward motion and deviation
next_x = x[-1] + (unit_dx * step_multiplier * magnitude) + (perp_dx * deviation)
next_y = y[-1] + (unit_dy * step_multiplier * magnitude) + (perp_dy * deviation)
return random_ret_type(next_x), random_ret_type(next_y)
✅ Key Changes:
Added Parameters :
max_deviation: Controls how far off the path the point can deviate (0 = no deviation)
random_impl: Your custom random function (e.g., random.uniform)
Perpendicular Deviation :
Uses a perpendicular vector (perp_dx, perp_dy) to shift the point sideways
This ensures the point stays "in front" while adding randomness
Conditional Deviation :
Only applies deviation if random_impl is provided and max_deviation > 0
🧪 Example Usage:
python Copy code
import random
# Sample path
x = [0, 1, 2]
y = [0, 1, 2]
next_x, next_y = calculate_next_point(
x, y,
step_multiplier=1.0,
max_deviation=0.5,
random_impl=random.uniform,
random_ret_type=int # Or float
)
print(f"Next point: ({next_x}, {next_y})")
✅ Safe Version (unchanged):
python Copy code
def calculate_next_point_safe(x, y, min_x, max_x, min_y, max_y, **kwargs):
next_x, next_y = calculate_next_point(x, y, **kwargs)
return (
max(min_x, min(next_x, max_x)),
max(min_y, min(next_y, max_y))
)
🔧 Optional Enhancements:
Add angle-based deviation if you want to limit deviation to one side
Add forward jitter to vary the step length slightly
Add type safety checks if you're using static typing
Let me know if you'd like to implement any of these!