Skip to content
This repository has been archived by the owner on Jul 11, 2024. It is now read-only.

Sense HAT(3)

alienzhangyw edited this page Apr 25, 2020 · 2 revisions

SNAKE game

This page introduces the classic Snake game on Sense HAT.

Draw snake

Use a list to save the coordinates of the snake's head, and a 2D list to save all the pixels of the body. The head is green and the body is blue.

It works like this:

Move the snake

Use a direction variable to save the direction the the snake moves to. next means the pixel that the head is moving to. When the head goes right, X coordinate increases by 1 (back to 0 if larger than 7) and Y stays the same. Former head pixel becomes the first of the body, and the new head is next. Then remove the last pixel of the body. Repeat drawing and moving and the snake will be moving on the LED matrix.

It works like this:

https://www.zhihu.com/video/1222903128753917952

Use joystick

Complete the code of other three direction in the move function, then add joystick control in the main program to change the direction.

It works like this:

https://www.zhihu.com/video/1222903425219928064

Draw apples

Create a draw_apple function to draw a red apple in random space. Be advised that the apple should not be drawn on the snake's head or body. The apple will refresh when the snake eats it.

Eat and grow

Use a score variable to record the apples be eaten. Modify the move function, increase score by 1 when the snake eats an apple. The body increases by 1 pixel every 5 apples be eaten, the last pixel will be kept, otherwise it will be removed.

It works like this:

https://www.zhihu.com/video/1222903602823741440

Speed up

The shorter time in the sleep block in the main loop, the faster the snake moves. Turn the pause time into a variable. It becomes shorter every 25 apples be eaten.

Game over

Use a dead flag. When you'er playing normally the dead is False; in move function, if the head bites her own body, you lose the game and dead changes to True. After that, show a message and your score, initialize all the variables and start the game again.

It works like this:

https://www.zhihu.com/video/1222903845682139136

Full program

The program save file is here(right-click then save-as).