Created
February 18, 2017 03:32
-
-
Save kf0jvt/fa313f88b813cfb04737c4d768ec28c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
globals [ | |
sample-car | |
] | |
turtles-own [ | |
speed | |
speed-limit | |
speed-min | |
recently-stopped? | |
deceleration | |
] | |
to setup | |
clear-all | |
ask patches [ setup-road ] | |
setup-cars | |
watch sample-car | |
reset-ticks | |
end | |
to setup-road ;; patch procedure | |
if pycor < 2 and pycor > -2 [ set pcolor white ] | |
end | |
to setup-cars | |
if number-of-cars > world-width [ | |
user-message (word | |
"There are too many cars for the amount of road. " | |
"Please decrease the NUMBER-OF-CARS slider to below " | |
(world-width + 1) " and press the SETUP button again. " | |
"The setup has stopped.") | |
stop | |
] | |
set-default-shape turtles "car" | |
create-turtles number-of-cars [ | |
set color blue | |
set xcor random-xcor | |
set heading 90 | |
;; set initial speed to be in range 0.1 to 1.0 | |
set speed 0.1 + random-float 0.9 | |
set speed-limit 1 | |
set speed-min 0 | |
set recently-stopped? false | |
set deceleration initial_deceleration | |
separate-cars | |
] | |
set sample-car one-of turtles | |
ask sample-car [ set color red ] | |
end | |
; this procedure is needed so when we click "Setup" we | |
; don't end up with any two cars on the same patch | |
to separate-cars ;; turtle procedure | |
if any? other turtles-here [ | |
fd 1 | |
separate-cars | |
] | |
end | |
to go | |
;; if there is a car right ahead of you, match its speed then slow down | |
ask turtles [ | |
let car-ahead one-of turtles-on patch-ahead 1 | |
ifelse car-ahead != nobody | |
[ slow-down-car car-ahead ] | |
[ speed-up-car ] ;; otherwise, speed up | |
;; don't slow down below speed minimum or speed up beyond speed limit | |
if speed < speed-min [ set speed speed-min ] | |
if speed > speed-limit [ set speed speed-limit ] | |
fd speed | |
] | |
tick | |
end | |
to slow-down-car [ car-ahead ] ;; turtle procedure | |
;; slow down so you are driving more slowly than the car ahead of you | |
set speed [ speed ] of car-ahead - deceleration | |
if speed < 0.15 [ | |
set recently-stopped? true | |
] | |
end | |
to speed-up-car ;; turtle procedure | |
set speed speed + acceleration | |
if recently-stopped? [ | |
if speed > 0.4 [ | |
print (word who ": speed greater than 0.4 and recently stopped. Deceleration now " deceleration) | |
set deceleration deceleration * 0.9 | |
set recently-stopped? false | |
] | |
] | |
end | |
; Copyright 1997 Uri Wilensky. | |
; See Info tab for full copyright and license. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment