# Creating Your First Tilemap Game with CircuitPython

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/091/240/medium800thumb/gaming_tilegame.jpg?1589677484)

This project will show you how to create your first tile map game with CircuitPython. We will learn how to make and modify indexed bmp graphics for the game. `ugame` is used for device agnostic control handling. See how to use spreadsheet applications to create and edit game maps.&nbsp;

Everything will come together in a sample game with two levels. Once you reach the end of the guide you'll have all the tools you need to customize the sample game or create one of your very own!

The guide is meant to be used with any of these devices: PyGamer, PyBadge, PyBadge LC, Edge Badge, or Pew Pew M4.

## Parts
### Adafruit PyGamer for MakeCode Arcade, CircuitPython or Arduino

[Adafruit PyGamer for MakeCode Arcade, CircuitPython or Arduino](https://www.adafruit.com/product/4242)
What&nbsp;fits in your pocket, is fully Open Source, and can run CircuitPython, MakeCode Arcade or Arduino games you write yourself? That's right, it's the **Adafruit PyGamer!** We wanted to make an entry-level gaming handheld for DIY gaming, and maybe a little...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4242)
[Related Guides to the Product](https://learn.adafruit.com/products/4242/guides)
![Angled shot of Adafruit PyGamer for MakeCode Arcade, CircuitPython or Arduino.](https://cdn-shop.adafruit.com/640x480/4242-00.jpg)

### Adafruit PyBadge for MakeCode Arcade, CircuitPython, or Arduino

[Adafruit PyBadge for MakeCode Arcade, CircuitPython, or Arduino](https://www.adafruit.com/product/4200)
What's the size of a credit card and can run CircuitPython, MakeCode Arcade or Arduino? That's right, its the **Adafruit PyBadge!** We wanted to see how much we could cram into a ​3 3⁄8 × ​2 1⁄8 inch rounded rectangle, to make an all-in-one dev board with...

In Stock
[Buy Now](https://www.adafruit.com/product/4200)
[Related Guides to the Product](https://learn.adafruit.com/products/4200/guides)
![Angled shot of a Adafruit PyBadge for MakeCode Arcade, CircuitPython, or Arduino. ](https://cdn-shop.adafruit.com/640x480/4200-01.jpg)

### Adafruit PyBadge LC - MakeCode Arcade, CircuitPython, or Arduino

[Adafruit PyBadge LC - MakeCode Arcade, CircuitPython, or Arduino](https://www.adafruit.com/product/3939)
What's the size of a credit card and can run CircuitPython, MakeCode Arcade or Arduino even when you're on a budget? That's right, it's the&nbsp; **Adafruit PyBadge LC!** &nbsp;We wanted to see how much we could cram into a ​3 3⁄8 × ​2 1⁄8 inch...

In Stock
[Buy Now](https://www.adafruit.com/product/3939)
[Related Guides to the Product](https://learn.adafruit.com/products/3939/guides)
![Angled Shot of Adafruit PyBadge - Low Cost. ](https://cdn-shop.adafruit.com/640x480/3939-05.jpg)

### Adafruit EdgeBadge - TensorFlow Lite for Microcontrollers

[Adafruit EdgeBadge - TensorFlow Lite for Microcontrollers](https://www.adafruit.com/product/4400)
Machine learning has come to the 'edge' - small microcontrollers that can run a very miniature version of TensorFlow Lite to do ML computations.&nbsp;

But you don't need super complex hardware to start developing your own TensorFlow models! We've adapted our popular...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4400)
[Related Guides to the Product](https://learn.adafruit.com/products/4400/guides)
![Top view of Adafruit EdgeBadge - Display reads "Test the TensorFlow lite voice model. Press and hold A button, say YES or NO, and see if the machine learned!".](https://cdn-shop.adafruit.com/640x480/4400-15.jpg)

### Adafruit PyGamer Starter Kit

[Adafruit PyGamer Starter Kit](https://www.adafruit.com/product/4277)
**Please note: you may get a royal blue _or_ purple case with your starter kit (they're both lovely colors)**

What&nbsp;fits in your pocket, is fully Open Source, and can run CircuitPython, MakeCode Arcade or Arduino games you write yourself? That's right,...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4277)
[Related Guides to the Product](https://learn.adafruit.com/products/4277/guides)
![Adafruit PyGamer Starter Kit with PCB, enclosure, buttons, and storage bag](https://cdn-shop.adafruit.com/640x480/4277-08.jpg)

### Plastic Button Caps For Square Top (10-pack) - 8mm Diameter

[Plastic Button Caps For Square Top (10-pack) - 8mm Diameter](https://www.adafruit.com/product/4228)
These Reese's Piece's lookin' bits fit perfectly on top of tactile buttons with 2.4mm square tops and give a satisfying 8mm diameter surface area for your fingers to press.  
  
You get 10 candy-colored round caps. You get two of each color: **red, yellow, white,...**

In Stock
[Buy Now](https://www.adafruit.com/product/4228)
[Related Guides to the Product](https://learn.adafruit.com/products/4228/guides)
![Angled shot of 10 plastic button caps colored reddish-orange, yellow, white, and black.](https://cdn-shop.adafruit.com/640x480/4228-04.jpg)

### Adafruit PyGamer Acrylic Enclosure Kit

[Adafruit PyGamer Acrylic Enclosure Kit](https://www.adafruit.com/product/4238)
You've got your PyGamer, and you're ready to start jammin' on your favorite arcade games. You gaze adoringly at the charming silkscreen designed by Ada-friend PaintYourDragon.&nbsp;The nostalgia is palpable!

Cradling the PCB in your hands, you realize there's something...

In Stock
[Buy Now](https://www.adafruit.com/product/4238)
[Related Guides to the Product](https://learn.adafruit.com/products/4238/guides)
![Enclosure pieces and black, plastic hardware for a DIY handheld game console.](https://cdn-shop.adafruit.com/640x480/4238-00.jpg)

# Creating Your First Tilemap Game with CircuitPython

## CircuitPython Setup

## CircuitPython Setup for the PyBadge and PyGamer

First, to make sure you're running the most recent version of&nbsp; **CircuitPython** &nbsp;for the&nbsp; **PyBadge** or **PyGamer:**

&nbsp;

[Click to read on installing CircuitPython on the PyBadge devices](https://learn.adafruit.com/adafruit-pybadge/installing-circuitpython)
Or

[Click to read installing CircuitPython on the PyGamer](https://learn.adafruit.com/adafruit-pygamer/circuitpython)
If you have an **Edge Badge** the process is the same as **PyBadge** , but use the button below to download the firmware file.

If you have a **Pew Pew M4** the process is very similar as the others, but there is no button for the reset pin. Short the `R`&nbsp; (reset) and `-` (GND) pins with a wire twice in quick succession to access the BOOT drive. Use the button below to download the firmware file.

[Download Edge Badge firmware](https://circuitpython.org/board/edgebadge/)
Or

[Download Pew Pew M4 firmware](https://circuitpython.org/board/pewpew_m4/)
## CircuitPython Libraries

You'll need a few&nbsp;CircuitPython&nbsp;libraries in the&nbsp; **lib** folder on the **CIRCUITPY** &nbsp;drive of your device for the code to work. Head to&nbsp;[https://circuitpython.org/libraries](https://circuitpython.org/libraries)&nbsp;to download the latest library bundle matching the major version of CircuitPython now on your board (5 for CircuitPython 5.x, etc.).&nbsp;[The procedure is available in the Grand Central M4 Express guide](https://learn.adafruit.com/adafruit-grand-central/circuitpython-libraries).

Once you've downloaded the libraries bundle, add these library directories to the&nbsp; **lib** &nbsp;folder on the **CIRCUITPY** drive:

- **adafruit\_display\_text**
- **adafruit\_imageload**

[Download Circuit Python Library bundle](https://circuitpython.org/libraries)
## Tilegame Assets

Included with this project is a directory called **tilegame\_assets**. You must copy this directory onto the **CIRCUITPY** drive. This contains the artwork, maps, and other modules needed for the game.&nbsp;

With everything in place you drive should have these files on it:

![](https://cdn-learn.adafruit.com/assets/assets/000/091/241/medium800/gaming_required_files.png?1589728609)

_ **It's okay if your device has other files as well, but it must have these ones at a minimum.** _

## Project Files

To get all the code and files for this project, click Download: Project Zip in the code box below. Unzip them and place a copy of them on the **CIRCUITPY** drive of your device in the directories noted above.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Tilemap_Game_With_CircuitPython/code.py

# Creating Your First Tilemap Game with CircuitPython

## Rendering and Movement

## Basic Rendering Code

If you are brand new to CircuitPython or `displayio` based programs, or even if it's just been a while, you should start by going over the [Multiple Tilegrids page in the displayio guide](https://learn.adafruit.com/circuitpython-display-support-using-displayio/multiple-tilegrids). After you've done that then come back here.

To start, lets look at this example:

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Tilemap_Game_With_CircuitPython/basic_rendering/code.py

In this code we have two Groups, one for the castle and one for the sprite or player icon, Blinka. These groups each get a TileGrid created and added to them. The `castle` TileGrid is sized 10x8 and divides evenly into the 160x128 pixel screen with each tile being 16x16 pixels. It holds the tiles that make up the portion of the map visible currently. The `sprite` TileGrid is only 1x1 but does still use the same 16x16 pixel size. It holds the Blinka image for the player.

If you do you do not understand the basics of how this layout works take a look back at the [Multiple Tilegrids page in the displayio guide](https://learn.adafruit.com/circuitpython-display-support-using-displayio/multiple-tilegrids). We will build on these concepts to create the rest of the game map. The first thing we'll do is add a movement system so we can make Blinka move around using the d-pad or joystick.&nbsp;

![gaming_begin_0.png](https://cdn-learn.adafruit.com/assets/assets/000/089/673/medium640/gaming_begin_0.png?1584928958)

## Basic Movement Code
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Tilemap_Game_With_CircuitPython/basic_movement/code.py

In the code above we have a variable&nbsp;`player_loc` that stores the coordinates of the player in tile coordinates. It's set to `{"x":4, "y":3} `by default. These correspond to the indexes of the tiles starting from the top left corner at `{"x":0, "y":0}`.

![](https://cdn-learn.adafruit.com/assets/assets/000/089/991/medium800/gaming_player_loc_grid.png?1585434071)

To handle player movement we will use a library&nbsp;called **ugame.** This helper module abstracts away the differences between different boards and leaves us with common signals to use for D-pad and other buttons.

The code above already contains the import for it, here is what it looks like:

```python
import ugame
```

After it's been imported we can access the current button states with `ugame.buttons.get_pressed()` it will return a number which holds each button state accessible by anding with the button constants like this:

```python
ugame.buttons.get_pressed() &amp; ugame.K_UP # True if up btn is pressed.
ugame.buttons.get_pressed() &amp; ugame.K_DOWN # True if down btn is pressed.
ugame.buttons.get_pressed() &amp; ugame.K_RIGHT # True if right btn is pressed.
ugame.buttons.get_pressed() &amp; ugame.K_LEFT # True if left btn is pressed.
```

We'll use these values in the main loop along with the `prev_btn_vals` to decide when we need to change the `player_loc`. Inside the main loop we update the `sprite.x` and `sprite.y` values to match the `player_loc`. This will make Blinka move around when the player presses D-pad buttons or uses the joystick.&nbsp;

Update the code from above to use this main loop.

```python
# Variable to old previous button state
prev_btn_vals = ugame.buttons.get_pressed()
while True:
    cur_btn_vals = ugame.buttons.get_pressed() # update button sate
    # if up button was pressed
    if not prev_btn_vals &amp; ugame.K_UP and cur_btn_vals &amp; ugame.K_UP:
        player_loc["y"] = max(1, player_loc["y"]-1)
    # if down button was pressed
    if not prev_btn_vals &amp; ugame.K_DOWN and cur_btn_vals &amp; ugame.K_DOWN:
        player_loc["y"] = min(6, player_loc["y"]+1)
    # if right button was pressed    
    if not prev_btn_vals &amp; ugame.K_RIGHT and cur_btn_vals &amp; ugame.K_RIGHT:
        player_loc["x"] = min(8, player_loc["x"]+1)
    # if left button was pressed    
    if not prev_btn_vals &amp; ugame.K_LEFT and cur_btn_vals &amp; ugame.K_LEFT:
        player_loc["x"] = max(1, player_loc["x"]-1)
        
    # update the the player sprite position
    sprite.x = 16 * player_loc["x"]
    sprite.y = 16 * player_loc["y"]
    
    # update the previous values
    prev_btn_vals = cur_btn_vals
```

Now we can use the D-pad or joystick to move Blinka around!

![](https://cdn-learn.adafruit.com/assets/assets/000/091/236/medium800thumb/gaming_basic_movement.jpg?1589668879)

Next we will change the graphics to get rid of the white square around Blinka.

# Creating Your First Tilemap Game with CircuitPython

## Indexed BMP Graphics

There are many image editing programs that can be used to create and modify bmp assets for use with CircuitPython. If you have access to and are familiar with Adobe Photoshop you can use that. If you are into making games and/or pixel art specifically, there is [Aseprite](https://www.aseprite.org/)&nbsp;which offers many great features that make it very easy to work with pixel art indexed bmp files. It's not free, but it is a nice utility for making and editing graphics.

For this guide, we'll use a free alternative: [The GNU Image](https://www.gimp.org/downloads/)[Manipulation Program or GIMP](https://www.gimp.org/downloads/). This works on Linux, Mac, and Windows PCs, and it's free to use and open sourced. We will use this to edit the image so that we can make the white background appear as transparent in the game. If you don't already have GIMP installed, use the link above and follow the installation instructions for your OS.

We'll starting from this bmp file:

[castle_sprite_sheet.bmp](https://cdn-learn.adafruit.com/assets/assets/000/075/025/original/castle_sprite_sheet.bmp?1556343110)
Open this file in GIMP by using File -\> Open or Ctrl+O then navigate to the directory where you've download the bmp file or project zip.

At real size 100% zoom the image will likely appear very small in GIMP. It's very helpful to zoom in with Ctrl+MouseWheel or the plus and minus buttons.

![gaming_spritesheet_gimp_realsize_screenshot.png](https://cdn-learn.adafruit.com/assets/assets/000/089/993/medium640/gaming_spritesheet_gimp_realsize_screenshot.png?1585500088)

## Transparency within Indexed BMPs

The bmp file format does not directly support transparency. Instead we are able to add code in CircuitPython that declares certain colors to appear as transparent instead of showing normally. You can think of it sort of like a green screen effect.

In the existing image, white is the color in the background, but we don't want to set white as transparent because Blinka and the Robot's eye's contain white so they would look wrong. Sometimes bright pink is used as the background color in sprite sheets for this purpose. But we have the heart graphic already using pink though, so we don't want to use pink either. We'll use green instead to follow with the green screen analogy. But really it could be any color that is not already used in the graphic.

## Converting to RGB Mode

Before we can modify the image we need to change it back to RGB color mode. Right now the image is in indexed color mode which means it only has access to a small set of colors.&nbsp;

Here are the currently available colors for this image:

&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/089/994/medium800/gaming_gimp_original_colormap.png?1585500925)

Since the green we want to use is not one of these colors it won't work, by default GIMP would choose the closest available color. But instead we want to add green to the available colors and use it. So we need to switch back to RGB color mode for now.&nbsp;

To do that click Image -\> Mode -\> RGB

![gaming_rgb_color_mode_with_padding.png](https://cdn-learn.adafruit.com/assets/assets/000/090/482/medium640/gaming_rgb_color_mode_with_padding.png?1587322756)

## Filling in the Background

Now you can set your foreground color and use the paint bucket tool to fill in the background parts of the sprite image with pure green `#00FF00`.

![](https://cdn-learn.adafruit.com/assets/assets/000/090/479/medium800/gaming_fill_with_green.png?1587001956)

In the image above, I've added small paint bucket icons in the two spots I clicked with the paint bucket tool to fill in the background green.&nbsp;

## Converting back to Indexed Color Mode

Once the background is filled in we need to switch the image back to indexed color mode so that CircuitPython can use it.&nbsp;

Click: Image -\> Mode -\> Indexed

![gaming_indexed_color_mode_with_padding.png](https://cdn-learn.adafruit.com/assets/assets/000/090/483/medium640/gaming_indexed_color_mode_with_padding.png?1587323297)

Leave the default settings in the Convert Image to Index Colors configuration dialog. It should look like this.

&nbsp;

Click the Convert button.

![gaming_convert_to_indexed_config.png](https://cdn-learn.adafruit.com/assets/assets/000/090/484/medium640/gaming_convert_to_indexed_config.png?1587323433)

## Re-arrange the Color Index

In the CircuitPython code we will need to specify a color index that is going to be shown as transparent. We can see the colors and their indexes inside of gimp in the Rearrange Colormap window. To access it:

Click: Color -\> Map -\> Rearrange Colormap

![](https://cdn-learn.adafruit.com/assets/assets/000/090/486/medium800/gaming_rearrange_colormap.png?1587324951)

![](https://cdn-learn.adafruit.com/assets/assets/000/090/487/medium800/gaming_gimp_edited_colormap.png?1587325040)

In my case, the newly added pure green transparency placeholder is at index `14`. It may be different for you, if so that's no problem.&nbsp;&nbsp;

We could make note of this index and use it in the CircuitPython code. But then if we ever change the image, we would need to make sure to go change the code if the index changed again due to us adding or removing colors.&nbsp;

Instead let's move the transparency placeholder to index 0. Then we can always make index 0 transparent in the code and as long as we always follow this rule when preparing bmp files, we can use the same code everywhere and it will work.&nbsp;

So click and drag your placeholder color over to the very first position in the list. The index still shows the wrong number but that is okay for now.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/090/488/medium800/gaming_gimp_edited1_colormap.png?1587325325)

Once your transparency placeholder is in the first position, click the Ok button.

At this point you are ready to export your image as a bmp file.

But I know it is weird the indexes were wrong on the previous screen... If you like to double check on things you can click Color -\> Map -\> Rearrange Colormap again to open up a new window and see that the indexes are updated to the proper numbers. It would look like this now:

![](https://cdn-learn.adafruit.com/assets/assets/000/090/489/medium800/gaming_gimp_edited2_colormap.png?1587325536)

## Saving the Image as a BMP File

Now the image is ready to be exported out of gimp as a bitmap file that is ready to show with CircuitPython `displayio`.

Click: File -\> Export As..

or Press: Ctrl+Shift+E

You can choose any name for your file, but it must end with `.bmp` because this will be the format that gimp saves the file with. I am going to use the name `castle_sprite_sheet_edited.bmp`. You can choose a different name if you like, if you do make sure to edit the rest of the sample code to use your own bmp filename.&nbsp;

At a minimum, you need to export one copy to your **CIRCUITPY** drive, but you can also save a copy to your local file system if you like. For this example we are going to save it into the `tilegame_assets` directory.

![](https://cdn-learn.adafruit.com/assets/assets/000/090/491/medium800/gaming_bmp_export.png?1587339902)

Once you've got the filename and location selected click on the Export button at the bottom.

Leave the default values in he export dialog.&nbsp;

Click the Export button.

&nbsp;

![gaming_export_dialog.png](https://cdn-learn.adafruit.com/assets/assets/000/090/492/medium640/gaming_export_dialog.png?1587340025)

Now we can change the sprite image loading code to use the new image and set the color at index `0` to be transparent.

```python
sprite_sheet, palette = adafruit_imageload.load("tilegame_assets/castle_sprite_sheet_edited.bmp",
                                                bitmap=displayio.Bitmap,
                                                palette=displayio.Palette)

# Make the color at index 0 show as transparent
palette.make_transparent(0)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/091/237/medium800thumb/gaming_basic_movement_transparent_sprite.jpg?1589669323)

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Tilemap_Game_With_CircuitPython/basic_movement_transparent_sprite/code.py

# Creating Your First Tilemap Game with CircuitPython

## Game Code Structure

## State Machine

At the highest level inside the main loop, the game program uses a state machine to behave the correct way at any given time, based on what the player has done so far. If you don't know what a state machine is, or just want a refresher there is a nice guide here: [https://learn.adafruit.com/circuitpython-101-state-machines](https://learn.adafruit.com/circuitpython-101-state-machines)

## GAME\_STATE Object

The state machine in this game uses numbers to track the state and we give each number a descriptive variable name to use in the code.

The current state that the state machine is in gets stored in `GAME_STATE["STATE"]`. All of the possible states are in `tilegame_assets\states.py`:

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Tilemap_Game_With_CircuitPython/tilegame_assets/states.py

The `"STATE"` item within the `GAME_STATE` dictionary is the only one that refers to the state machine logic.&nbsp;

The rest of the items in the `GAME_STATE` dictionary store information about the current game and map.&nbsp;

Here are the starting values:

```python
GAME_STATE = {
    # hold the map state as it came out of the csv. Only holds non-entities.
    "ORIGINAL_MAP": {},
    # hold the current map state as it changes. Only holds non-entities.
    "CURRENT_MAP": {},
    # Dictionary with touple keys that map to lists of entity objects.
    # Each one has the index of the sprite in the ENTITY_SPRITES list
    # and the tile type string
    "ENTITY_SPRITES_DICT": {},
    # hold the location of the player in tile coordinates
    "PLAYER_LOC": (0, 0),
    # list of items the player has in inventory
    "INVENTORY": [],
    # how many hearts there are in this map level
    "TOTAL_HEARTS": 0,
    # sprite object to draw for the player
    "PLAYER_SPRITE": None,
    # size of the map
    "MAP_WIDTH": 0,
    "MAP_HEIGHT": 0,
    # which map level within MAPS we are currently playing
    "MAP_INDEX": 0,
    # current state of the state machine 
    "STATE": STATE_PLAYING,
}
```

Their values will change as the map gets loaded and the player moves around and does things within the game.&nbsp;

# Creating Your First Tilemap Game with CircuitPython

## CSV Maps and Tile Types

## Map File

The game will load the maps from CSV (Comma Separated Value) files. We can edit these with any spreadsheet program. Here is an example of a map:

![](https://cdn-learn.adafruit.com/assets/assets/000/090/711/medium800/gaming_csv_map_example.png?1588036891)

Any blank cells will get treated as empty tiles that can't be walked on. Every cell that isn't empty must have an entry in the main `TILES` dictionary which is located inside of `tilegame_assets\tiles.py`.&nbsp;

## Loading The Map

To load the CSV map we start by loop over each row. `split(',')` breaks the row down into a list which we will also loop over. On each item within the row, we look it up in the **TILES** dictionary. Non-entities get added to the `ORIGINAL_MAP` and `CURRENT_MAP` game state objects.

The `enumerate()` function is used on the loops to easily track `x` and `y` coordinates so we know where to add tiles to the map objects.

Entities also get added to the `ENTITY_SPRITES_DICT` game state object. Their sprites are loaded and added to the `sprite_group` so they'll be drawn on the screen. In the map objects a `"floor"` tile is placed at the location of the entity. The entity will be drawn on top of the floor.

Here is the code that loads the map:

```python
def load_map(file_name):
    # pylint: disable=global-statement,too-many-statements,too-many-nested-blocks,too-many-branches
    global ENTITY_SPRITES, CAMERA_VIEW

    # empty the sprites from the group
    for cur_s in ENTITY_SPRITES:
        group.remove(cur_s)
    # remove player sprite
    try:
        group.remove(GAME_STATE["PLAYER_SPRITE"])
    except ValueError:
        pass

    # reset map and other game state objects
    GAME_STATE["ORIGINAL_MAP"] = {}
    GAME_STATE["CURRENT_MAP"] = {}
    ENTITY_SPRITES = []
    GAME_STATE["ENTITY_SPRITES_DICT"] = {}
    CAMERA_VIEW = {}
    GAME_STATE["INVENTORY"] = []
    GAME_STATE["TOTAL_HEARTS"] = 0

    # Open and read raw string from the map csv file
    f = open("tilegame_assets/{}".format(file_name), "r")
    map_csv_str = f.read()
    f.close()

    # split the raw string into lines
    map_csv_lines = map_csv_str.replace("\r", "").split("\n")

    # set the WIDTH and HEIGHT variables.
    # this assumes the map is rectangular.
    GAME_STATE["MAP_HEIGHT"] = len(map_csv_lines)
    GAME_STATE["MAP_WIDTH"] = len(map_csv_lines[0].split(","))

    # loop over each line storing index in y variable
    for y, line in enumerate(map_csv_lines):
        # ignore empty line
        if line != "":
            # loop over each tile type separated by commas, storing index in x variable
            for x, tile_name in enumerate(line.split(",")):
                print("%s '%s'" % (len(tile_name), str(tile_name)))

                # if the tile exists in our main dictionary
                if tile_name in TILES.keys():

                    # if the tile is an entity
                    if (
                        "entity" in TILES[tile_name].keys()
                        and TILES[tile_name]["entity"]
                    ):
                        # set the map tiles to floor
                        GAME_STATE["ORIGINAL_MAP"][x, y] = "floor"
                        GAME_STATE["CURRENT_MAP"][x, y] = "floor"

                        if tile_name == "heart":
                            GAME_STATE["TOTAL_HEARTS"] += 1

                        # if it's the player
                        if tile_name == "player":
                            # Create the sprite TileGrid
                            GAME_STATE["PLAYER_SPRITE"] = displayio.TileGrid(
                                sprite_sheet,
                                pixel_shader=palette,
                                width=1,
                                height=1,
                                tile_width=16,
                                tile_height=16,
                                default_tile=TILES[tile_name]["sprite_index"],
                            )

                            # set the position of sprite on screen
                            GAME_STATE["PLAYER_SPRITE"].x = x * 16
                            GAME_STATE["PLAYER_SPRITE"].y = y * 16

                            # set position in x,y tile coords for reference later
                            GAME_STATE["PLAYER_LOC"] = (x, y)

                            # add sprite to the group
                            group.append(GAME_STATE["PLAYER_SPRITE"])
                        else:  # not the player
                            # Create the sprite TileGrid
                            entity_srite = displayio.TileGrid(
                                sprite_sheet,
                                pixel_shader=palette,
                                width=1,
                                height=1,
                                tile_width=16,
                                tile_height=16,
                                default_tile=TILES[tile_name]["sprite_index"],
                            )
                            # set the position of sprite on screen
                            # default to off the edge
                            entity_srite.x = -16
                            entity_srite.y = -16

                            # add the sprite object to ENTITY_SPRITES list
                            ENTITY_SPRITES.append(entity_srite)
                            # print("setting GAME_STATE['ENTITY_SPRITES_DICT'][%s,%s]" % (x,y))

                            # create an entity obj
                            _entity_obj = {
                                "entity_sprite_index": len(ENTITY_SPRITES) - 1,
                                "map_tile_name": tile_name,
                            }

                            # if there are no entities at this location yet
                            if (x, y) not in GAME_STATE["ENTITY_SPRITES_DICT"]:
                                # create a list and add it to the dictionary at the x,y location
                                GAME_STATE["ENTITY_SPRITES_DICT"][x, y] = [_entity_obj]
                            else:
                                # append the entity to the existing list in the dictionary
                                GAME_STATE["ENTITY_SPRITES_DICT"][x, y].append(
                                    _entity_obj
                                )

                    else:  # tile is not entity
                        # set the tile_name into MAP dictionaries
                        GAME_STATE["ORIGINAL_MAP"][x, y] = tile_name
                        GAME_STATE["CURRENT_MAP"][x, y] = tile_name

                else:  # tile type wasn't found in dict
                    print("tile: %s not found in TILES dict" % tile_name)
    # add all entity sprites to the group
    print("appending {} sprites".format(len(ENTITY_SPRITES)))
    for entity in ENTITY_SPRITES:
        group.append(entity)
```

## Tile Types

These entries define the look and behavior of the tiles. Here is an example of a tile type entry:

```python
# ... behavior functions declared above...
TILES = {
  # ... many tile type entries ...
  "mho": {
    "sprite_index": 2,
    "can_walk": True,
    "entity": True,
    "before_move": take_item
  },
  # ... more entries ...
}
```

The keys within the `TILES` dictionary match up with the values from the map CSV file. One of the `mho` tiles is located at cell `D3`. There may be tile keys that aren't present in a particular map, they will have no effect when playing that map level in the game.&nbsp;

These entries define the look and behavior of tiles using the following properties:

- `sprite_index` - The index within the sprite sheet to show for this tile.
- `can_walk` - Whether the player is allowed to walk on this tile.
- `entity` - Whether this tile represents an entity. If so it will get drawn on top of a floor tile and theoretically it could move around the map. The player is an entity as well as Mho, Heart, Minerva, and Robot. However the player is the only entity in the example game that moves.
- `before_move` - (Optional) If set to a function the function will get called when the player tries to walk on this tile. If the function returns `True` the player will be allowed to walk on the tile, if the function returns `False` the player will not be allowed to walk on it.

## Behavior Functions

These functions must be declared before the main **TILES** dictionary because tiles that want special behaviors will get them by setting the `before_move` property in their tile type entry to a behavior function. These are also declared inside the file: **tilegame\_assets\tiles.py**. The existing behavior functions are:&nbsp;

- `take_item`- if the item is still here then add it to the player's inventory and remove it from this tile. In the example game both `"mho"` and `"heart"` tile types use this function.
- `sparky_walk` - if the player has a `"Mho"` in their inventory it gets consumed and the Sparky is removed from this tile. If they player has no `"Mho"` they let the smoke out and must restart this level.&nbsp;
- `minerva_walk` - change the game state to `STATE_MINERVA` in this state Minerva will show the player a fun fact and prompt them to press a button to continue. This function always returns `False` so the player is never allowed to actually move on to this tile. The fun facts are stored as a list inside he file: **tilegame\_assets\fun\_facts.py**. If you add your own facts to this list Minerva will show them to the player sometimes.
- `robot_walk` - if the player has gathered all of the hearts from this map then they are allowed to move to the robot, and they win this level. Game state is changed to `STATE_MAPWIN`. If they have not gathered all available hearts then they are not allowed to move to this tile.&nbsp;

You can declare your own tile types and behavior functions in this file to customize your game!

![](https://cdn-learn.adafruit.com/assets/assets/000/091/235/medium800/gaming_mapwin_minerva.png?1589668261)

## tiles.py
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Tilemap_Game_With_CircuitPython/tilegame_assets/tiles.py

# Creating Your First Tilemap Game with CircuitPython

## Camera View

In order to allow the map to be larger than the screen, or shaped differently than a plain rectangle we use a `CAMERA_VIEW` dictionary. Just like the full map dictionary, the keys are (x,y) coordinate tuples and the values are tile type strings. But unlike the full map dictionary the `CAMERA_VIEW` is always the exact same size and shape 10x8 tiles in this game, which matches up with the screen size on the PyGamer and PyBadge devices.  
  
There are two functions related to camera management: `set_camera_view()` and `draw_camera_view()`.

`set_camera_view()` will build the `CAMERA_VIEW` dictionary based on the current game state. It accepts parameters for x, y starting point within the map as well as width and height. The example game will always use `10, 8` for the size so it fits perfectly on the `160x128` pixel screen. If you wanted to adapt the game code to work with a different sized screen you could change these values.

`draw_camera_view()` will draw the current contents of the `CAMERA_VIEW` dictionary onto the screen. It will also check for the existence of and draw any entities that are within the coordinates of the `CAMERA_VIEW`.

![](https://cdn-learn.adafruit.com/assets/assets/000/091/270/medium800/gaming_map_camera.png?1589768031)

In this game, the camera will always stay centered on the player because we reference the player location in the x, and y value parameters when `set_camera_view()` is called.

Here are the `set_camera_view()` and `draw_camera_view()` function definitions:

```python
# set the appropriate tiles into the CAMERA_VIEW dictionary
# based on given starting coords and size
def set_camera_view(startX, startY, width, height):
    global CAMERA_OFFSET_X
    global CAMERA_OFFSET_Y
    # set the offset variables for use in other parts of the code
    CAMERA_OFFSET_X = startX
    CAMERA_OFFSET_Y = startY

    # loop over the rows and indexes in the desired size section
    for y_index, y in enumerate(range(startY, startY + height)):
        # loop over columns and indexes in the desired size section
        for x_index, x in enumerate(range(startX, startX + width)):
            # print("setting camera_view[%s,%s]" % (x_index,y_index))
            try:
                # set the tile at the current coordinate of the MAP into the CAMERA_VIEW
                CAMERA_VIEW[x_index, y_index] = GAME_STATE["CURRENT_MAP"][x, y]
            except KeyError:
                # if coordinate is out of bounds set it to floor by default
                CAMERA_VIEW[x_index, y_index] = "floor"


# draw the current CAMERA_VIEW dictionary and the GAME_STATE['ENTITY_SPRITES_DICT']
def draw_camera_view():
    # list that will hold all entities that have been drawn based on their MAP location
    # any entities not in this list should get moved off the screen
    drew_entities = []
    # print(CAMERA_VIEW)

    # loop over y tile coordinates
    for y in range(0, SCREEN_HEIGHT_TILES):
        # loop over x tile coordinates
        for x in range(0, SCREEN_WIDTH_TILES):
            # tile name at this location
            tile_name = CAMERA_VIEW[x, y]

            # if tile exists in the main dictionary
            if tile_name in TILES.keys():
                # if there are entity(s) at this location
                if (x + CAMERA_OFFSET_X, y + CAMERA_OFFSET_Y) in GAME_STATE[
                    "ENTITY_SPRITES_DICT"
                ]:
                    # default background for entities is floor
                    castle[x, y] = TILES["floor"]["sprite_index"]

                    # if it's not the player
                    if tile_name != "player":
                        # loop over all entities at this location
                        for entity_obj_at_tile in GAME_STATE["ENTITY_SPRITES_DICT"][
                            x + CAMERA_OFFSET_X, y + CAMERA_OFFSET_Y
                        ]:
                            # set appropriate x,y screen coordinates 
                            # based on tile coordinates
                            ENTITY_SPRITES[
                                int(entity_obj_at_tile["entity_sprite_index"])
                            ].x = (x * 16)
                            ENTITY_SPRITES[
                                int(entity_obj_at_tile["entity_sprite_index"])
                            ].y = (y * 16)

                            # add the index of the entity sprite to the draw_entities 
                            # list so we know not to hide it later.
                            drew_entities.append(
                                entity_obj_at_tile["entity_sprite_index"]
                            )

                else:  # no entities at this location
                    # set the sprite index of this tile into the CASTLE dictionary
                    castle[x, y] = TILES[tile_name]["sprite_index"]

            else:  # tile type not found in main dictionary
                # default to floor tile
                castle[x, y] = TILES["floor"]["sprite_index"]

            # if the player is at this x,y tile coordinate accounting for camera offset
            if GAME_STATE["PLAYER_LOC"] == ((x + CAMERA_OFFSET_X, y + CAMERA_OFFSET_Y)):
                # set player sprite screen coordinates
                GAME_STATE["PLAYER_SPRITE"].x = x * 16
                GAME_STATE["PLAYER_SPRITE"].y = y * 16

    # loop over all entity sprites
    for index in range(0, len(ENTITY_SPRITES)):
        # if the sprite wasn't drawn then it's outside the camera view
        if index not in drew_entities:
            # hide the sprite by moving it off screen
            ENTITY_SPRITES[index].x = int(-16)
            ENTITY_SPRITES[index].y = int(-16)
```

In this game, the camera will always stay mostly centered on the player, because we reference the player location in the x, and y value parameters when `set_camera_view()` is called. The max and min functions are used to minimize the amount of "outside the map" area that we show.

Here is the code inside the main loop that calls `set_camera_view()` and `draw_camera_view()`:

```python
# inside main game loop:
  set_camera_view(
    max(min(GAME_STATE['PLAYER_LOC'][0]-4,GAME_STATE['MAP_WIDTH']-SCREEN_WIDTH_TILES),0),
    max(min(GAME_STATE['PLAYER_LOC'][1]-3,GAME_STATE['MAP_HEIGHT']-SCREEN_HEIGHT_TILES),0),
    10,
    8
  )
# draw the camera
draw_camera_view()
```


## Featured Products

### Adafruit PyGamer for MakeCode Arcade, CircuitPython or Arduino

[Adafruit PyGamer for MakeCode Arcade, CircuitPython or Arduino](https://www.adafruit.com/product/4242)
What&nbsp;fits in your pocket, is fully Open Source, and can run CircuitPython, MakeCode Arcade or Arduino games you write yourself? That's right, it's the **Adafruit PyGamer!** We wanted to make an entry-level gaming handheld for DIY gaming, and maybe a little...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4242)
[Related Guides to the Product](https://learn.adafruit.com/products/4242/guides)
### Adafruit PyBadge for MakeCode Arcade, CircuitPython, or Arduino

[Adafruit PyBadge for MakeCode Arcade, CircuitPython, or Arduino](https://www.adafruit.com/product/4200)
What's the size of a credit card and can run CircuitPython, MakeCode Arcade or Arduino? That's right, its the **Adafruit PyBadge!** We wanted to see how much we could cram into a ​3 3⁄8 × ​2 1⁄8 inch rounded rectangle, to make an all-in-one dev board with...

In Stock
[Buy Now](https://www.adafruit.com/product/4200)
[Related Guides to the Product](https://learn.adafruit.com/products/4200/guides)
### Adafruit PyBadge LC - MakeCode Arcade, CircuitPython, or Arduino

[Adafruit PyBadge LC - MakeCode Arcade, CircuitPython, or Arduino](https://www.adafruit.com/product/3939)
What's the size of a credit card and can run CircuitPython, MakeCode Arcade or Arduino even when you're on a budget? That's right, it's the&nbsp; **Adafruit PyBadge LC!** &nbsp;We wanted to see how much we could cram into a ​3 3⁄8 × ​2 1⁄8 inch...

In Stock
[Buy Now](https://www.adafruit.com/product/3939)
[Related Guides to the Product](https://learn.adafruit.com/products/3939/guides)
### Adafruit EdgeBadge - TensorFlow Lite for Microcontrollers

[Adafruit EdgeBadge - TensorFlow Lite for Microcontrollers](https://www.adafruit.com/product/4400)
Machine learning has come to the 'edge' - small microcontrollers that can run a very miniature version of TensorFlow Lite to do ML computations.&nbsp;

But you don't need super complex hardware to start developing your own TensorFlow models! We've adapted our popular...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4400)
[Related Guides to the Product](https://learn.adafruit.com/products/4400/guides)
### Adafruit PyGamer Starter Kit

[Adafruit PyGamer Starter Kit](https://www.adafruit.com/product/4277)
**Please note: you may get a royal blue _or_ purple case with your starter kit (they're both lovely colors)**

What&nbsp;fits in your pocket, is fully Open Source, and can run CircuitPython, MakeCode Arcade or Arduino games you write yourself? That's right,...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4277)
[Related Guides to the Product](https://learn.adafruit.com/products/4277/guides)
### Plastic Button Caps For Square Top (10-pack) - 8mm Diameter

[Plastic Button Caps For Square Top (10-pack) - 8mm Diameter](https://www.adafruit.com/product/4228)
These Reese's Piece's lookin' bits fit perfectly on top of tactile buttons with 2.4mm square tops and give a satisfying 8mm diameter surface area for your fingers to press.  
  
You get 10 candy-colored round caps. You get two of each color: **red, yellow, white,...**

In Stock
[Buy Now](https://www.adafruit.com/product/4228)
[Related Guides to the Product](https://learn.adafruit.com/products/4228/guides)
### Adafruit PyGamer Acrylic Enclosure Kit

[Adafruit PyGamer Acrylic Enclosure Kit](https://www.adafruit.com/product/4238)
You've got your PyGamer, and you're ready to start jammin' on your favorite arcade games. You gaze adoringly at the charming silkscreen designed by Ada-friend PaintYourDragon.&nbsp;The nostalgia is palpable!

Cradling the PCB in your hands, you realize there's something...

In Stock
[Buy Now](https://www.adafruit.com/product/4238)
[Related Guides to the Product](https://learn.adafruit.com/products/4238/guides)

## Related Guides

- [Adafruit PyBadge and PyBadge LC](https://learn.adafruit.com/adafruit-pybadge.md)
- [Introducing Adafruit PyGamer](https://learn.adafruit.com/adafruit-pygamer.md)
- [Next Level MakeCode Arcade Games](https://learn.adafruit.com/next-level-makecode-arcade-games.md)
- [Creating Custom Symbol Fonts for Adafruit GFX Library](https://learn.adafruit.com/creating-custom-symbol-font-for-adafruit-gfx-library.md)
- [PYOA for PyGamer/PyBadge - Adding Cursor Support to CircuitPython](https://learn.adafruit.com/cursor-for-circuitpython.md)
- [Arcada Animated GIF Display](https://learn.adafruit.com/pyportal-animated-gif-display.md)
- [Playing Arduboy Games on Arcada](https://learn.adafruit.com/playing-arduboy-games-on-arcada.md)
- [PyBadge Case](https://learn.adafruit.com/pybadge-case.md)
- [Making oscilloscope images with DACs](https://learn.adafruit.com/dac-oscilloscope-images.md)
- [NES Emulator for Arcada](https://learn.adafruit.com/nes-emulator-for-arcada.md)
- [PyBadge Conference Badge With Unicode Fonts](https://learn.adafruit.com/pybadge-conference-badge-multi-language-unicode-fonts.md)
- [MakeCode Arcade Pixel Art Sprites](https://learn.adafruit.com/makecode-arcade-pixel-art-sprites.md)
- [Playing Gamebuino META Games on Arcada](https://learn.adafruit.com/playing-gamebuino-meta-games-on-arcada.md)
- [PyGamer - Gaming Handheld Crank](https://learn.adafruit.com/gaming-handheld-crank.md)
- [Rotary Encoder in CircuitPython](https://learn.adafruit.com/rotary-encoder.md)
- [PyPortal IoT Plant Monitor with Google Cloud IoT Core and CircuitPython](https://learn.adafruit.com/pyportal-iot-plant-monitor-with-google-cloud-iot-core-and-circuitpython.md)
