I decided to implement a random walk.
The rules
The rules are easy, an object is moved in the direction dictated by random or pseudo-random numbers. If you want to read more about it, see the Wikipedia Page.
A simple example
Let's say we decide:
1 = "Go right"
2 = "Go down"
3 = "Go left"
4 = "Go up"
We then generate the random or pseudo-random sequence: 3,1,4,1
.
And we convert it to directions:
- Left
- Right
- Up
- Right
we obtain the following:
A more complex example
Runnning my code with:
step_size = 15
step_number = 1000
Generated the following walk:
Running the code with the exact same parameters may yield completely different results because pseudo-random numbers are used.
I think my code is well written and fully Pep8 compliant, two things bother me
I define many
go_<direction>
methods to go to absolute directions, I could have done something like:turn_of_random_deegres() turtle.forward(step)
But it looked cleaner to me, albeit a little longer, to define absolute moving.
- The
go_<direction>
methods change between logo and standard edition. (Control-Find setheading in this doc-page)
- The
The code
import turtle
import random
def go_right(step):
turtle.setheading(0)
turtle.forward(step)
def go_up(step):
turtle.setheading(90)
turtle.forward(step)
def go_left(step):
turtle.setheading(180)
turtle.forward(step)
def go_down(step):
turtle.setheading(270)
turtle.forward(step)
def make_random_walk(step_size, step_number):
move_dict = {1: go_up,
2: go_right,
3: go_left,
4: go_down
}
for _ in range(step_number):
move_in_a_direction = move_dict[random.randint(1, 4)]
move_in_a_direction(step_size)
if __name__ == "__main__":
turtle.hideturtle()
turtle.speed("fastest")
make_random_walk(15, 1000)