Jazmin Barrionuevo
3-minute read
Python
OpenCV
Numpy
Cvzone
So, I decided to make the Snake Game, but with a twist—I’m using hand tracking to control it! I’m working with the cvzone.HandTrackingModule.HandDetector class, which lets me detect hand landmarks like the tip of your index finger.
Basically, lmList is a list of landmarks (points) on the hand. Each landmark is represented by a list or tuple containing the x and y coordinates, and sometimes the z coordinate (which represents depth):
LIST [[248, 674, 0], [320, 623, -44], [368, 526, -58], [385, 437, -67], [409, 370, -76],
[303, 432, -28], [316, 338, -56], [326, 277, -81], [336, 224, -99], [249, 424, -25],
[242, 321, -51], [239, 249, -75], [240, 187, -92], [201, 438, -29], [194, 338, -60],
[194, 269, -83], [196, 212, -97], [156, 471, -37], [127, 400, -69], [108, 348, -86], [94, 301, -95]]
lmList[8] accesses the landmark point for the tip of the index finger (landmark 8). This is where I drew a filled circle on the image at the pointIndex coordinates.
I'm building the game with a class structure, where I've grouped all the game elements into a single class. This method makes sense because the game has a lot of interconnected parts and variables. Using functions alone would be too complicated, especially with the number of parameters that would need to be managed.
Now, there are three main things to focus on:
1. Snake Growth: First, I've set a specific total length for the snake. The snake will only grow when it consumes food, adding segments as it eats. This mechanic keeps the game challenging, as the snake becomes harder to maneuver the longer it gets.
1
2
3
4
5
6
7
8
if self.currentLength > self.allowedLength:
for i, length in enumerate(self.lengths):
self.currentLength -= length
self.lengths.pop(i)
self.points.pop(i)
if self.currentLength < self.allowedLength:
break
2. Random Food Generation: The food isn't just placed anywhere—it's generated at a random location each time. When the snake eats the food, it disappears and immediately reappears in a new random spot, keeping the game unpredictable and engaging.
3. Collision Detection: To make sure the snake doesn't run into itself, I’m using OpenCV’s pointPolygonTest() function. This function checks if any part of the snake’s body collides with the polygon formed by its own body. It’s a crucial part of the game that adds an extra layer of difficulty, especially as the snake grows longer.
You can find the full project on my github: Snake Game