AI
Computers don't think as humans, but they do think, by following our instructions. In this section, we are going to have the computer think out a short path and chase you.
Two turtles
Up until now we've only had one turtle in our programs, but we can create multiple turtles by creating different variables each containing a turtle.Turtle(). We want one for the human and one for the AI, so we'll do this:
human = turtle.Turtle()
human.shape("turtle")
human.goto(25, 25)
ai = turtle.Turtle()
ai.shape("square")
ai.goto(25, 0)
Notice we're not writing turtle.shape, but human.shape, otherwise Python won't know which turtle we're refering to.
In this way, we can also create three or even more turtles, but we are going to stick to two in this section.
A program that creates two turtles and lets you control one of them looks like this:
Read through the code and think about it for a bit, and try it out, before proceeding.
Turn towards a point
We've seen that left and right can turn the turtle a certain number of degrees clockwise or counterclockwise. We can also ask Python for the angle between two points, for example two turtles, and turn to it directly. A point can either be x,y coordinates or another turtle.
If we want the angle between ai and human, we can compute it with:
new_angle = ai.towards(human)
Turning to a specific angle can be done with setheading:
ai.setheading(new_angle)
Try updating the go_forward function in the program above with this two lines, to see how the computer constantly turns as you move around:
def go_forward():
human.forward(hastighet)
new_angle = ai.towards(human)
ai.setheading(new_angle)
Let the hunger games begin!
What's left for the computer to start chasing you? It has to move! Add a small movement after turning:
def go_forward():
human.forward(speed)
new_angle = ai.towards(human)
ai.setheading(new_angle)
ai.forward(speed/2)
What happens if the AI somehow reaches you? Right now, nothing, but we can add this to the end of the same function:
if human.distance(ai) < 10:
turtle.bye()
What else can you build after this? Programming lets you do whatever you want with your computer!
In this video, we combine all our Python knowledge. Two turtles appear on the screen, you control one and the computer controls the other. Will it catch you?
- AI: Artificial intelligence, a thinking machine