# Karel The Robot In CircuitPython

## Overview

https://www.youtube.com/watch?v=oHhZjwJCMMs

Karel was invented by Rich Pattis, a graduate student at Stanford university in the 1970s. It was intended to teach the fundamentals of programming without the complexities that are present in many programming languages. To achieve this goal, Rich created an introductory programming language that students can use to teach a robot to solve simple problems. The robot was named Karel, after Karel Čapek, the author of the 1923 play Rossum's Universal Robots, which is where the English language got the word "robot".

[The Stanford version of the Karel](https://compedu.stanford.edu/karel-reader/docs/python/en/intro.html) language shares many similarities with Python, so Karel feels right at home on CircuitPython. When used under CircuitPython, there is a little bit of initialization needed for the display and to set the initial state, and there is a function that will verify whether you've correctly directed Karel to the goal state. All of the other code that controls Karel is the same in CircuitPython as it is in the Stanford version, so you can copy that portion of your programs between the two, and they will work on both.

## Parts

This project supports any CircuitPython device with a display of at least 240x240 pixels. Externally connected displays can work but require additional wiring. For the simplest setup, use a device with a built-in display; several options are listed below.

### Adafruit PyPortal - CircuitPython Powered Internet Display

[Adafruit PyPortal - CircuitPython Powered Internet Display](https://www.adafruit.com/product/4116)
 **PyPortal** , our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface GUIs, all open-source, and Python-powered using&nbsp;tinyJSON / APIs to get news, stock, weather, cat photos,...

In Stock
[Buy Now](https://www.adafruit.com/product/4116)
[Related Guides to the Product](https://learn.adafruit.com/products/4116/guides)
![Front view of a Adafruit PyPortal - CircuitPython Powered Internet Display with a pyportal logo image on the display. ](https://cdn-shop.adafruit.com/640x480/4116-00.jpeg)

### Adafruit FunHouse - WiFi Home Automation Development Board

[Adafruit FunHouse - WiFi Home Automation Development Board](https://www.adafruit.com/product/4985)
Home is where the heart is...it's also where we keep all our electronic bits. So why not wire it up with sensors and actuators to turn our house into an electronic wonderland. Whether it's tracking the environmental temperature and humidity in your laundry room, or notifying you when...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4985)
[Related Guides to the Product](https://learn.adafruit.com/products/4985/guides)
![Top-down video of Adafruit Funhouse PCB. The TFT display shows a data readout, and the NeoPixel LEDs glow rainbow colors.](https://cdn-shop.adafruit.com/product-videos/640x480/4985-00.jpg)

### Adafruit CLUE - nRF52840 Express with Bluetooth® LE

[Adafruit CLUE - nRF52840 Express with Bluetooth® LE](https://www.adafruit.com/product/4500)
Do you feel like you just don't have a CLUE? Well, we can help with that - get a CLUE here at Adafruit by picking up this sensor-packed development board. We wanted to build some projects that have a small screen and a lot of sensors. To make it compatible with existing projects, we made...

In Stock
[Buy Now](https://www.adafruit.com/product/4500)
[Related Guides to the Product](https://learn.adafruit.com/products/4500/guides)
![Animated GIF showing CLUE board  displaying data from the many on-board sensors.](https://cdn-shop.adafruit.com/product-videos/640x480/4500-04.jpg)

### Adafruit PyPortal Titano

[Adafruit PyPortal Titano](https://www.adafruit.com/product/4444)
The **PyPortal Titano** is the big sister to our [popular PyPortal](https://www.adafruit.com/product/4116) now with _twice as many pixels!_ The PyPortal is our easy-to-use IoT device that allows you to create all the things for the “Internet of...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4444)
[Related Guides to the Product](https://learn.adafruit.com/products/4444/guides)
![Hand holding PyPortal Titano development board with SAMD51, ESP32 Wifi, and 3.5" touchscreen TFT display.](https://cdn-shop.adafruit.com/640x480/4444-10.jpg)

# Karel The Robot In CircuitPython

## Project Setup

Are you new to using CircuitPython? No worries,&nbsp;[there is a full getting-started guide here](https://learn.adafruit.com/welcome-to-circuitpython "Welcome to CircuitPython").

Plug the device into your computer with a known good USB cable (not a charge-only cable). The device will appear to your computer in File Explorer or Finder (depending on your operating system) as a flash drive named&nbsp; **CIRCUITPY**. If the drive does not appear, you can&nbsp;[install CircuitPython](https://learn.adafruit.com/welcome-to-circuitpython/installing-circuitpython)&nbsp;on your device and then return here.

Download the project files with the Download Project Bundle button below.&nbsp;Unzip the file and copy/paste the&nbsp; **code.py** &nbsp;and other project files to your&nbsp; **CIRCUITPY** &nbsp;drive using File Explorer or Finder (depending on your operating system).

## Drive Structure

After copying the files, your drive should look like the listing below. It can contain other files as well, but must contain these at a minimum.

![Karel](https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/folder-images/CircuitPython_Karel_The_Robot.png?raw=true )

## Code

The **code.py** file for the project is shown below.

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

# Karel The Robot In CircuitPython

## Programming Karel

## Loading Initial State

Once you've copied the project bundle to your device, you're ready to begin programming Karel. By default, the **code.py** file will load the world state for [Chapter 1](https://compedu.stanford.edu/karel-reader/docs/python/en/chapter1.html) of the Stanford guide. To load a different puzzle, simply update this line of the code to use a different valid puzzle data file name.&nbsp;

```python
chapter_data = load_state_file("chapters/karel_ch01.json")
```

Look inside of the **chapters/** directory within the project files to find the names of all of the puzzle data files. Here are all the ones that come with the project code:

```auto
karel_ch01.json
karel_ch02.json
karel_ch03a.json
karel_ch03b.json
karel_ch04.json
karel_ch05a.json
karel_ch05b.json
karel_ch05c.json
karel_ch06a.json
karel_ch06b.json
karel_ch07.json
karel_ch08.json
```

## Write Code For Karel

Your code goes inside of the `main()` function body. There are comments that designate the area to put your code.

```python
## START OF MAIN FUNCTION, YOUR CODE GOES BELOW HERE ##



## END OF MAIN FUNCTION, YOUR CODE GOES ABOVE HERE ##
```

Move your cursor to one of the blank lines between these comments when you start writing code for Karel.

CircuitPython runs your code automatically when you save it, so ave your file (click Save or press ctrl-S or cmd-S) when you're ready, and then watch the display to see how your Karel behaves with the current code.

At the end of the program, it will check the state of Karel and the world to see if they match the goal state for the current puzzle data. Look in the serial console for print messages like `Goal state reached? [True or False]`. Try to write the programs necessary to successfully reach the goal state and make it print `True`.

### Example Karel Program

Here is an example program that will move a few steps while picking up and then putting back down a beeper.

```python
## START OF MAIN FUNCTION, YOUR CODE GOES BELOW HERE ##

# take one step
move()

# if there is a beeper at this location
if beepers_present():
  # pick up the beeper
  pick_beeper()

# turn Karel to the left 
turn_left()

# take one step
move()

# put down a beeper
put_beeper()

## END OF MAIN FUNCTION, YOUR CODE GOES ABOVE HERE ##
```

See the [Stanford Python Karel reference page](https://compedu.stanford.edu/karel-reader/docs/python/en/reference.html "Stanford Python Karel Reference") for a complete list of available commands. Remember that you can also write your own functions to achieve more complex behaviors.

# Karel The Robot In CircuitPython

## Stanford Chapters

The [Stanford Python Karel guide](https://compedu.stanford.edu/karel-reader/docs/python/en/chapter1.html) contains a total of 11 chapters. The first 8 chapters include a puzzle that the student can attempt to solve by programming Karel. There are chapter data files included in the project code for all of the puzzles covered by those 8 chapters. The last few chapters contain extra features, an API reference, and a page that lets you code Karel live in the browser. They do not contain puzzles to be completed, but are still worth taking a look at.

The puzzles on this page are intended for you to do while you read the information presented in each chapter within the [Stanford Python Karel guide](https://compedu.stanford.edu/karel-reader/docs/python/en/chapter1.html). Load that guide in a browser tab and read through it as you work on the puzzles.&nbsp;

### Chapter 1

Load this puzzle from the file **chapters/karel\_ch01.json**. Your goal is to program Karel to pick up the beeper and walk up and around the obstruction in a U-turn shape, then put the beeper back down.

![](https://cdn-learn.adafruit.com/assets/assets/000/134/171/medium800/lcds___displays_ch01_img.png?1734460094)

### Chapter 2

Load this puzzle from the file **chapters/karel\_ch02.json**. Your goal is to program Karel to pick up the beeper and walk up onto the hill, place the beeper back down, and take another step forward to the last available corner.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/134/172/medium800/lcds___displays_ch02_img.png?1734460751)

### Chapter 3a

Load this puzzle from the file **chapters/karel\_ch03a.json**. Your goal is the same as the puzzle from Chapter 2, but you're intended to declare your own new function `turn_right()` in order to solve it this time.

Initial state and goal state are the same as depicted above.

### Chapter3b

Load this puzzle from the file **chapters/karel\_ch03b.json**. Your goal is to go around the wall and pick up the beeper. Then take the beeper to the opposite corner of the world and place it back down. Karel should remain at the same location as the beeper, and face west. This is a custom puzzle I created; it isn't included in the Stanford Chapter 3 page.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/134/173/medium800/lcds___displays_ch03b_img.png?1734461503)

### Chapter 4

Load this puzzle from the file **chapters/karel\_ch04.json**. Your goal is to fill the pothole by placing a beeper inside of it, then move Karel to the opposite side of the filled hole. Think about ways to break the challenge down into smaller components and then try to declare functions to carry out the tasks required by them.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/134/174/medium800/lcds___displays_ch04_img.png?1734462907)

### Chapter 5a

Load this puzzle from the file **chapters/karel\_ch05a.json**. Your goal is to use a `for` loop to put down 42 beepers and then move Karel one step past them.

![](https://cdn-learn.adafruit.com/assets/assets/000/134/175/medium800/lcds___displays_ch05a_img.png?1734463145)

### Chapter 5b

Load this puzzle from the file **chapters/karel\_ch05b.json**. Your goal is to place one beeper in each of the 4 corners of the world. Karel should end at the same location, and facing the same direction it was when it began.

![](https://cdn-learn.adafruit.com/assets/assets/000/134/176/medium800/lcds___displays_ch05b_img.png?1734463439)

### Chapter 5c

Load this puzzle from the file **chapters/karel\_ch05c.json**. Your goal is to place 5 beepers in each of the corners of the world. Try to declare a new function or two that make use of `for` loops inside of them to solve this puzzle.

![](https://cdn-learn.adafruit.com/assets/assets/000/134/177/medium800/lcds___displays_ch05c_img.png?1734463536)

### Chapter 6a

Load this puzzle from the file **chapters/karel\_ch06a.json**. Your goal is to move Karel forward as long as there is an empty space in front. Learn about, and use a `while` loop to solve this puzzle.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/134/178/medium800/lcds___displays_ch06a_img.png?1734463782)

### Chapter 6b

Load this puzzle from the file **chapters/karel\_ch06b.json**. Your goal is similar to the previous puzzle, but this time leave a trail of beepers on the ground at each location that Karel moves to. Solving this puzzle requires dealing with the fencepost bug.

![](https://cdn-learn.adafruit.com/assets/assets/000/134/179/medium800/lcds___displays_ch06b_img.png?1734464014)

### Chapter 7

Load this puzzle from the file **chapters/karel\_ch07.json**. Your goal is walk to the end of the row, inverting the beeper presence along the way. Any tile that was empty should have a beeper put down, and any tile that had a beeper already should have the beeper picked up, and be left empty. Learn about `if` statements and basic conditional to solve this puzzle.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/134/180/medium800/lcds___displays_ch07_img.png?1734464324)

### Chapter 8

Load this puzzle from the file **chapters/karel\_ch08.json**. Your goal is to move Karel along the bottom row, stopping to pick up the entire column of beepers that are present and then moving to the next column. Once all beepers are collected, put them down in the bottom right corner of the world. Finally, return Karel to the starting location and direction. This puzzle requires combining together knowledge from all of the previous chapters.&nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/134/181/medium800/lcds___displays_ch08_img.png?1734464673)

# Karel The Robot In CircuitPython

## Extra Features

## Paint Corner

In the [Stanford Python Karel guide chapter 9](https://compedu.stanford.edu/karel-reader/docs/python/en/chapter9.html), there is information about a `paint_corner()` function. At the time of writing this guide, I could not get the `paint_corner()` function to work for the in-browser Karel code environment on their web pages. However, the CircuitPython implementation of Karel does support `paint_corner()`. Call it and pass a color name to paint the color at Karel's current location. e.g. `paint_corner("blue")`.

![](https://cdn-learn.adafruit.com/assets/assets/000/134/183/medium800/lcds___displays_paint.png?1734476144)

Painted corners cannot be part of the `input` or `goal` states, but they sure are fun to play with and pretty to look at. The supported colors are listed below. You can also see them in the serial console by adding this statement inside your&nbsp;`main()` function: `print(COLOR_NAMES)`

```python
['white', 'black', 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink', 'light_gray', 'gray', 'brown', 'dark_green', 'turquoise', 'dark_blue', 'dark_red']
```

### Creating Custom Puzzles

The puzzles are encoded into JSON files. If you're not familiar with JSON, [this Real Python page](https://realpython.com/python-json/ "Real Python JSON Guide") can serve as a great guide covering the basics. The file contains an `input` state and `goal` state. Each state contains a grid representing the tiles in the world, the location and direction of Karel, and an optional list of locations that contain more than 1 beeper.&nbsp;

The numbers in the grid correspond to indexes within the sprite sheet.&nbsp;

- `7` = Empty black void tile&nbsp;
- `5` = Open corner tile that Karel can move to
- `4` = Beeper tile
- `6` = Wall tile that Karel cannot move to.

For Karel's location, the `x` and `y` use a zero-based origin of the bottom left corner. `"x":0`, `"y":0` is the bottom left corner of the world.

For `beeper_counts`, the configuration is a dictionary that has string keys which are comma separated x and y coordinates using the same zero-based origin as Karel. &nbsp;`"1, 0": 42` means 42 beepers located at tile `x:1`, `y:0`

To create your own custom puzzles, simply copy/paste an existing configuration file and change the grid tile indices as well as Karel's location and direction. If your puzzle requires multiple beepers at the same location, then add a `beeper_counts` object with appropriate values. See **chapters/karel\_ch05a.json** for an example configuration that uses multiple beepers at a location.

The configuration file for Chapter 1 is embedded below for reference.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/CircuitPython_Karel_The_Robot/chapters/karel_ch01.json


## Featured Products

### Adafruit PyPortal - CircuitPython Powered Internet Display

[Adafruit PyPortal - CircuitPython Powered Internet Display](https://www.adafruit.com/product/4116)
 **PyPortal** , our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface GUIs, all open-source, and Python-powered using&nbsp;tinyJSON / APIs to get news, stock, weather, cat photos,...

In Stock
[Buy Now](https://www.adafruit.com/product/4116)
[Related Guides to the Product](https://learn.adafruit.com/products/4116/guides)
### Adafruit FunHouse - WiFi Home Automation Development Board

[Adafruit FunHouse - WiFi Home Automation Development Board](https://www.adafruit.com/product/4985)
Home is where the heart is...it's also where we keep all our electronic bits. So why not wire it up with sensors and actuators to turn our house into an electronic wonderland. Whether it's tracking the environmental temperature and humidity in your laundry room, or notifying you when...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4985)
[Related Guides to the Product](https://learn.adafruit.com/products/4985/guides)
### Adafruit CLUE - nRF52840 Express with Bluetooth® LE

[Adafruit CLUE - nRF52840 Express with Bluetooth® LE](https://www.adafruit.com/product/4500)
Do you feel like you just don't have a CLUE? Well, we can help with that - get a CLUE here at Adafruit by picking up this sensor-packed development board. We wanted to build some projects that have a small screen and a lot of sensors. To make it compatible with existing projects, we made...

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

[Adafruit PyPortal Titano](https://www.adafruit.com/product/4444)
The **PyPortal Titano** is the big sister to our [popular PyPortal](https://www.adafruit.com/product/4116) now with _twice as many pixels!_ The PyPortal is our easy-to-use IoT device that allows you to create all the things for the “Internet of...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4444)
[Related Guides to the Product](https://learn.adafruit.com/products/4444/guides)
### Adafruit PyPortal Pynt - CircuitPython Powered Internet Display

[Adafruit PyPortal Pynt - CircuitPython Powered Internet Display](https://www.adafruit.com/product/4465)
The **PyPortal Pynt** is the little&nbsp;sister to our [popular PyPortal](https://www.adafruit.com/product/4116) - zapped with a shrink ray to take the design from a 3.2" diagonal down to 2.4" diagonal screen - but otherwise the same! The PyPortal is&nbsp;our...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/4465)
[Related Guides to the Product](https://learn.adafruit.com/products/4465/guides)

## Related Guides

- [Adafruit PyPortal - IoT for CircuitPython](https://learn.adafruit.com/adafruit-pyportal.md)
- [Adafruit PyPortal Titano](https://learn.adafruit.com/adafruit-pyportal-titano.md)
- [Introducing Adafruit CLUE](https://learn.adafruit.com/adafruit-clue.md)
- [Adafruit FunHouse](https://learn.adafruit.com/adafruit-funhouse.md)
- [PyPortal Event Countdown Clock](https://learn.adafruit.com/pyportal-event-countdown-clock.md)
- [Making a PyPortal User Interface with DisplayIO](https://learn.adafruit.com/making-a-pyportal-user-interface-displayio.md)
- [Pet Bowl Water Level Sensing](https://learn.adafruit.com/pet-bowl-water-level-sensing-with-the-funhouse-and-home-assistant.md)
- [PyPortal NASA Image of the Day Viewer](https://learn.adafruit.com/pyportal-nasa-image-of-the-day-viewer.md)
- [PyPortal Wake-Up Light Alarm Clock](https://learn.adafruit.com/pyportal-wake-up-light.md)
- [Digital Nose Milk Freshness Checker](https://learn.adafruit.com/digital-nose-gas-sensor-milk-freshness-checker.md)
- [PyPortal Discord Online Counter](https://learn.adafruit.com/pyportal-discord-online-count.md)
- [PyPortal IoT Weather Station](https://learn.adafruit.com/pyportal-iot-weather-station.md)
- [PyPortal 2FA TOTP Authentication Friend](https://learn.adafruit.com/pyportal-2fa-totp-authentication-friend.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)
- [CLUE Sensor Plotter in CircuitPython](https://learn.adafruit.com/clue-sensor-plotter-circuitpython.md)
- [PyPortal Case](https://learn.adafruit.com/pyportal-case.md)
- [PyPortal Winamp MP3 Player](https://learn.adafruit.com/pyportal-winamp-mp3-player.md)
- [AdaBox 011](https://learn.adafruit.com/adabox011.md)
- [A colorful CLUE slideshow purse with Bright Wearables](https://learn.adafruit.com/a-colorful-clue-slideshow-purse.md)
