---
title: "Turtle Events"
---

## Basic Turtle Events

Here is a template for a Turtle program that responds to events like key presses and mouse clicks. The program creates a turtle that moves around the screen in response to the arrow keys. The turtle changes color when the mouse is clicked.

```python
import turtle

screen = turtle.Screen()
pen = turtle.Turtle()

# First we define functions that will be called when events happen.
# First the arrow keys:
def move_up():
    pen.setheading(90)
    pen.forward(10)

def move_down():
    pen.setheading(270)
    pen.forward(10)

def move_left():
    pen.setheading(180)
    pen.forward(10)

def move_right():
    pen.setheading(0)
    pen.forward(10)

# Then the mouse click:
def change_color(x, y):
    """Change the color of the turtle when the screen is clicked."""
    if x < 0:
        pen.color("red")
    else:
        pen.color("blue")

# Hook up the functions to the events. First the arrow keys:
screen.onkey(move_up, "Up")
screen.onkey(move_down, "Down")
screen.onkey(move_left, "Left")
screen.onkey(move_right, "Right")
# Now the mouse click:
screen.onscreenclick(change_color)

# This line is necessary to make key events work.
screen.listen()
screen.mainloop()
```

## Managing State

When you need to change how the program reacts depending on the state of the program, you can use a classes. For example, here is a simple two-player "game":

```python
import turtle

class Player:
    """Represents a player in a game.
    
    Attributes:
    - name: the player's name
    - turtle: the turtle object representing the player
    """
    def __init__(self, name, x, y, color):
        """Create a new player with the given name, position, and color."""
        # Store the player's name
        self.name = name
        # Create and store a turtle object for the player
        self.turtle = turtle.Turtle()
        self.turtle.goto(x, y)
        self.turtle.color(color)
        self.turtle.shape('circle')
        self.turtle.shapesize(3)
        
        # Hook up the turtle to respond to clicks
        self.turtle.onclick(self.on_click)
    
    def on_click(self, x, y):
        """This function is called when the player's turtle is clicked."""
        # Show my name and the location where I was clicked
        print(self.name, 'was clicked at', x, y)
        # Move forward a little
        self.turtle.forward(10)

# Create two players. Each one is an instance of the Player class.
player1 = Player("Alice", 30, 50, 'red')
player2 = Player("Bob", -10, 0, 'blue')

# Wait for events.
turtle.mainloop()
```

For more advanced games, you might want a separate class for the game itself, which manages the players and the game state. That way, you can have a single object that keeps track of details about the game, like whose turn it is, the score, and so on.

To design a game state class, think about what information you need to keep track of. Imagine some friends are playing a board game but you need to move your game to a new location. What do you need to write down so that you can set up the game again later? That information is what you should store in your game state class.

Here's a simple two-player game where the players take turns moving a turtle around the screen:

```python
import turtle

class State:
    """Represents the state of a simple two-player game.

    Attributes:
    - players: a list of the two players
    - current_player: the index of the current player (0 or 1)
    """

    def __init__(self):
        """Create a new game state with two players."""
        self.players = []
        self.current_player = 0

        self.players.append(turtle.Turtle())
        self.players[0].color('red')
        self.players.append(turtle.Turtle())
        self.players[1].color('blue')

    def on_click(self, x, y):
        """Move the current player to the clicked location, then switch players."""
        player = self.players[self.current_player]
        player.goto(x, y)
        # Switch players
        self.current_player = (self.current_player + 1) % 2

# Create a new game state.
state = State()
turtle.onscreenclick(state.on_click)
turtle.mainloop()
```
