using Pkg
Pkg.add("Plots")
using Plots
Making birds fly
In addition to a working Julia installation, you will need the Plots package in order to complete this homework. Run the following commands to install and load it:
In this week’s lecture, you learned about custom types, functions and array comprehensions. In this homework, you get to put these concepts to practice.
Specifically, we will implement a version of the artificial birds that we saw in first week’s lecture’s flocking example. For now, however, we omit the collision avoidance, tracking and navigation rules and only concentrate on figuring out how to make the birds “fly”.
Your task is to:
Write a custom type called
Bird
which has the following fields, each of them of typeFloat64
:x
, the bird’s location coordinate in the horizontal dimensiony
, the bird’s location coordinate in the vertical dimensiondir_x
, the bird’s direction (where its beak is pointing) in the horizontal dimensiondir_y
, the birds’ direction in the vertical dimension
Use an array comprehension to make a population of
Bird
objects such that each bird gets a random location and random direction in both dimensions. Store this array in a variable namedpopulation
.Download this file and save it with the filename
plot_birds.jl
. Then run the following in Julia:include("plot_birds.jl")
(You may need to specify the whole path of the file in the above command if the file is not located in the same directory as your Julia session.)
TipIf the above fails, you can also simply copy-paste the contents of
plot_birds.jl
into your own file.Run the following command:
plot(population)
This will draw the bird’s positions and directions in a graphical plot.
Write a function called
fly!
which takes one argument – aBird
object – and makes this bird fly. In this context, to fly means to movex
in the direction ofdir_x
by a little amount – let’s call that little amountdelta
– and to likewise movey
in the direction ofdir_y
by the same amount. (You can makedelta
an argument offly!
if you want.)TipUse pen and paper to visually figure out how to update the
x
andy
values of theBird
object. Use your imagination. Also note that there is no single “correct” answer as to how this function ought to be implemented. We will look at a few different possibilities in next week’s lecture.Test your function by calling it on a few birds in your population of birds. Then re-plot the population. Do the birds’ positions change as you’d expect?