Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Python use gesture recognition to realize gluttonous Snake Game

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how Python uses gesture recognition to achieve gluttonous snake game". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how Python uses gesture recognition to realize gluttonous snake game" can help you solve the problem.

Project introduction 1, the operation mode of the game

Gluttonous snake game is well known, computer vision is little known, computer vision + gluttonous snake game will bring people more sense of participation and freshness, this project is mainly using gesture recognition to complete the simple game of gluttonous snake. In this game, the computer captures our gestures through the camera and determines whether to move or not. Players move their hands to manipulate gluttonous snakes to get random food on the screen. Every time they get a food, it will be counted as a point. Score will be added 1 and displayed in the screen. When players accidentally make the snake's head and body collide in the process of operation, then it will show GameOver! Press the'r 'key to restart the game.

2. matters needing attention in the process of development

(1) the problem of left and right of the image

Because we use gestures to control the movement of the snake, but the camera screen shows other people's point of view, so this is the opposite of the player's left and right consciousness, so we need to flip the image read by the camera. In principle, it is to change the position of the left and right pixels, but in Python you can use a cv2.flip () function to achieve mirror flipping.

(2) the picture size of the camera

Pass

We need to play games on the images obtained by the camera, so too small the screen will lead to a shortage of game space. At the beginning, we can preprocess the size of the screen and set a more reasonable size, so that the final picture will not appear cramped when playing the game. The width and height of the picture can be set through the function cap.set (3, m) cap.set (4, n).

There will be some other considerations in this project, such as judging the collision, judging the acquisition of food, etc., which I will introduce later in the project process.

Third, the main points of the realization of the game 1. Select the third-party library.

Some of the third-party libraries used:

Import mathimport randomimport cvzoneimport cv2import numpy as npfrom cvzone.HandTrackingModule import HandDetector

In this project, we mainly use the above libraries, in which random library is used to randomly select pixels to place food doughnuts, hand recognition in cvzone is used to detect player gestures, cv2 is used for some basic image operations, and other libraries are also useful, which are described later.

2. Find the key point and mark it

In this game, we chose a hand as the target node, so when we detect the appearance of the hand in the screen, we need to mark the key point, and this key point happens to be the head of our gluttonous serpent. Because we are the third-party library called, and this library can mark the hand in 3D, but we only need two coordinate values of xQuery. The following functions are mainly used to mark the key nodes of the hand:

# detect the first hand and mark the position of the hand if hands: lmList = hands [0] ['lmList'] pointIndex = lmList [8] [0:2] # the x, y value of the eighth coordinate point, where the z value is not included in cv2.circle (img, pointIndex, 20, (200,0,200), cv2.FILLED) # draw a dot at the key point and fill it (here is just a demonstration Create a class to save all the functions about the game

The game we need to implement is a combination of many functions, if we want to use functions to achieve these functions, then it will be very troublesome, when we use class to complete, because a lot of things are saved in the same class, it will be less difficult. In this class, we will create many important lists to store some of the key points we can use, such as all the points on the body of the gluttonous snake, the length of the gluttonous snake, the overall distance of the snake, the placement of food, scores, etc.:

Class SnakeGameClass: def _ init__ (self, pathFood): self.points = [] # all points on a gluttonous snake self.lengths = [] # distance between points self.currentLength = 0 # current snake length self.allowedLength = 50 # maximum allowable length (threshold) self.previousHead = 0 0 # the first point after the hand key point self.imgFood = cv2.imread (pathFood, cv2.IMREAD_UNCHANGED) # defines the food self.hFood, self.wFood, _ = self.imgFood.shape self.foodPoint = 0,0 self.randomFoodLocation () self.score = 0 self.gameOver = False4, and the definition function is constantly updated

As our hands move, the length and location of the gluttonous snake will change, so we need to create a function to constantly update to meet the changing needs (this part is also done in the big class created earlier):

Def update (self, imgMain, currentHead): # Game over Printed text if self.gameOver: cvzone.putTextRect (imgMain, "Game Over", [300,400], scale=7, thickness=5, offset=20) cvzone.putTextRect (imgMain, f'Your Score: {self.score}', [300,550], scale=7, thickness=5, offset=20) else: px Py = self.previousHead cx, cy = currentHead self.points.append ([cx, cy]) distance = math.hypot (cx-px, cy-py) self.lengths.append (distance) self.currentLength + = distance self.previousHead = cx, cy # length reduced 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 # check whether the gluttonous snake has touched the food rx Ry = self.foodPoint if rx-self.wFood / / 2 < cx < rx + self.wFood / / 2 and\ ry-self.hFood / / 2 < cy < ry + self.hFood / / 2: self.randomFoodLocation () self.allowedLength + = 50 self.score + = 1 print (self.score) # use lines to draw gluttonous snakes if self.points: for I Point in enumerate (self.points): if I! = 0: cv2.line (imgMain, self.points [I-1], self.points [I], (0,0,255), 20) cv2.circle (imgMain, self.points [- 1], 20, (0,255,0) Cv2.FILLED) # shows food imgMain = cvzone.overlayPNG (imgMain, self.imgFood, (rx-self.wFood / / 2, ry-self.hFood / / 2)) cvzone.putTextRect (imgMain, f'Score: {self.score}', [50,80], scale=3, thickness=3 Offset=10) # detect whether collision pts = np.array (self.points [:-2], np.int32) pts = pts.reshape ((- 1,1,2)) cv2.polylines (imgMain, [pts], False, (0,255,0), 3) minDist = cv2.pointPolygonTest (pts, (cx, cy), True) if-1

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report