Skip to content

Instantly share code, notes, and snippets.

@cndreisbach
Created January 9, 2015 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cndreisbach/1d37356bfba3af84dab2 to your computer and use it in GitHub Desktop.
Save cndreisbach/1d37356bfba3af84dab2 to your computer and use it in GitHub Desktop.
class Car:
acceleration = 2
braking = 3
desired_speed = 30 # mps = 108 km/hr
minimum_spacing = 15
slowing_prob = 0.2
def __init__(self, speed=0, location=0):
self.speed = speed
self.location = location
def speed_kmh(self):
return int(self.speed / KMH_TO_MPS)
def accident_chance(self):
return BASE_FATALITY_CHANCE_PER_KM * (1.03 ** self.speed_kmh())
def next_probable_location(self):
return self.location + self.speed
def move(self, other_cars):
"""Returns a new Car with a new location and speed_mps. Does this
so that we can loop over all cars to get their next speed and location
without mutating them, preventing issues with some cars moved with others
not yet moving."""
def distance(car):
return car.next_probable_location() - self.next_probable_location()
def too_close(distance):
return 0 < distance < self.minimum_spacing
speed = self.speed
location = self.location
if self.speed < self.desired_speed:
speed += self.acceleration
distances = [distance(car) for car in other_cars]
cars_too_close = [too_close(d) for d in distances]
if any(cars_too_close):
speed = min(d for d in distances if d > 0)
if random.random() < self.slowing_prob:
speed -= self.braking
speed = speed if speed > 0 else 0
location += speed
return Car(speed, location)
def __repr__(self):
return "<Car speed={} location={}>".format(self.speed, self.location)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment