One of the other things the Adafruit LED Backpacks are bundled with is an 8×8 LED matrix. As I no longer needed my Time Circuit project I removed a backpack from the setup and ordered a Red/Green matrix from CPC. I purposely bought the bi colour matrix as the red, green and yellow (r+g) gives me scope to play around more.
So what first? Well, I needed to wire it up; and as I am using the Adafruit Python libraries again I need to make sure the red and green pins were wired according to their code (red = a0 – a7, green = a8 – a15). To make sure everything was in order I ran the example Python code from the library which cycles through each LED in red, green then yellow.
Let’s Code
In my code there are four main variables
snake – a list object containing the x,y coordinates of each piece of the snake at any one time. These are in head to tail order.
food – contains the x,y coordinates of the current ‘food’ block on the display
direction – a string that holds the direction of travel of our snake r(ight), l(eft), u(p) or d(own)
grid – an instance of the Adafruit 8×8 grid library
The main function then has the following actions:
- Check for key press; see if we need to change direction
- Identify the next square the snake will move to
- Check to see if it’s hit the edge or itself
- Check to see if we’ve ‘eaten’ the food
- Update the snake object to move it on one square
- Draw the snake
To manage the snake the list object is used as a queue or First In First Out, aka FIFO, structure (that’s a proper programming term and everything kids!). So every move is done in two steps, insert the new head location into the first position (or push) and remove (or pop) the last item in the queue.
Before the insert happens the new coordinate is checked to see if we need to do anything special.
- If the new head is outside the grid (hit the edge) or is the same location as part of the snake body then the code walks the snake list object and turns each coordinate red.
- If the snake eats the food then the tail coordinate stays on the queue, extending the body by 1
That’s about it really. The only other thing to note is that without using PyGame and an interactive screen capturing the keys is not quite as straight forward as you would hope. There are two functions keyPress and control that I borrowed from the interwebs (there’s stacks of examples) to capture the key presses on a separate thread so that the main display loop (move snake, redraw etc) doesn’t hang waiting for a key press.