Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import matplotlib.pyplot as plt
- class Boat:
- def __init__(self, boat_x=0.0, boat_y=0.0, heading_angle=0.0, goal_x=100.0, goal_y=100.0):
- self.boat_x = boat_x
- self.boat_y = boat_y
- self.heading_angle = heading_angle
- self.goal_x = goal_x
- self.goal_y = goal_y
- self.speed = 0.0
- self.wind_speed = 0.0
- self.wind_angle = 0.0
- self.trail = [(boat_x, boat_y)]
- self.no_go_limit = math.pi / 4
- self.tack_angle = math.radians(50)
- self.tack_side = 1
- def set_wind(self, wind_speed, wind_x, wind_y):
- self.wind_speed = wind_speed
- self.wind_x = wind_x
- self.wind_y = wind_y
- self.wind_angle = math.atan2(wind_y, wind_x)
- def angle_to_goal(self):
- return math.atan2(self.goal_y - self.boat_y, self.goal_x - self.boat_x)
- def move_fwd(self):
- goal_angle = self.angle_to_goal()
- rel_goal_wind = (goal_angle - self.wind_angle + math.pi) % (2 * math.pi) - math.pi
- # no-go zone
- if -self.no_go_limit < rel_goal_wind < self.no_go_limit:
- print("Alert! No-go-zone reached. Changing tack!")
- self.heading_angle = self.wind_angle + self.tack_side * self.tack_angle
- self.rudder_angle = -0.8 * self.tack_side
- else:
- self.heading_angle = goal_angle
- self.rudder_angle = 0.0
- # polar efficiency (very simplified)
- rel_heading_wind = (self.heading_angle - self.wind_angle + math.pi) % (2 * math.pi) - math.pi
- polar_efficiency = max(0, 1 + math.sin(rel_heading_wind))
- self.speed = self.wind_speed * 0.1 * polar_efficiency
- # update position
- self.boat_x += self.speed * math.cos(self.heading_angle)
- self.boat_y += self.speed * math.sin(self.heading_angle)
- self.trail.append((self.boat_x, self.boat_y))
- # Switch tacks midway (simple logic)
- if (self.tack_side == 1 and self.boat_x > self.goal_x / 2) or \
- (self.tack_side == -1 and self.boat_x < -self.goal_x / 2):
- self.tack_side *= -1
- def distance_to_goal(self):
- return math.sqrt((self.goal_x - self.boat_x) ** 2 + (self.goal_y - self.boat_y) ** 2)
- def sail():
- boat = Boat(boat_x=0, boat_y=0, heading_angle=0, goal_x=100, goal_y=100)
- boat.set_wind(30, 0, -1)
- for step in range(500):
- boat.move_fwd()
- if boat.distance_to_goal() < 5:
- print("Goal reached successfully!")
- break
Advertisement
Add Comment
Please, Sign In to add comment