How to make a snake game in python?
History of Snake Game:
Snake is a video game genre where the player maneuvers a growing line that becomes a primary obstacle to itself. The concept originated in the 1975 two-player arcade game Blockade from Gremlin Industries, and the ease of implementation has led to hundreds of versions (some of which have the word snake or worm in the title) for many segments. After a variant was preloaded on Nokia mobile phones in 1998, there was a resurgence of interest in snake games as it found a larger audience. There are several hundred snake games for iOS alone.
Modules:
- cv2
- cvzone
- matplotlib
- scipy
- sklearn
Roadmap:
Problems
- Our first work will be to againcognising the hand
- Then find the point of the finger
- Now we will going to create a point with the finger
- We need to create a logic where the point will increase as we move the finger
- Next step is to stop the snake game when the coordinate of the points clash with each other
- Create random foods for the snake in the snake game
Solutions
- We can againcognise the hand very easily by using this module
from cvzone.HandTrackingModule import HandDetector
- We also can get the point of the fingers using this module (cvzone)
- In this module we will get the coordinate of the points so we will store them into an array and as we move the finger it will add the corresponding value of the point and we can use the array
class SnakeGameClass:
def __init__(self,pathFood):
self.points = []
- The 3rd method is the solution
- To mark the snake game is over we will create a function where we will take two-points and see the gap between them if they are close enough we will stop the snake game loop
- To create random foods we will take the help of the random module of python
We will use a donut image as the food of the snake in this snake game you can download it from here👇
Now time to make the gesture control snake game
import math
import random
from socket import gaierror
from cv2 import sepFilter2D
import cvzone
import cv2
from matplotlib.pyplot import sca
import numpy as np
from cvzone.HandTrackingModule import HandDetector
from scipy.fftpack import cc_diff
from sklearn.preprocessing import scale
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
detector = HandDetector(detectionCon=0.8,maxHands=1)
class SnakeGameClass:
def __init__(self,pathFood):
self.points = [] #list of all points of the snake
self.lengths = [] # distance between each point
self.currentLength = 0 # total length of the snake
self.allowedLength = 150 #total allowed length
self.previousHead = 0, 0 # previous head point
self.imgFood = cv2.imread(pathFood, cv2.IMREAD_UNCHANGED)
self.hFood, self.wFood, _ = self.imgFood.shape
self.foodPoint = 0, 0
self.randomFoodLocatioin()
self.score = 0
self.gameOver = False
def randomFoodLocatioin(self):
self.foodPoint = random.randint(100, 1000), random.randint(100, 600)
def update(self, imgMain, currentHead):
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,500],
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 Reduction
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 if the snake eat the food
rx, ry = self.foodPoint
if rx - self.wFood//2 < cx < rx + self.wFood//2 and ry - self.hFood<cy<
ry + self.hFood + self.hFood:
self.randomFoodLocatioin()
self.allowedLength += 50
self.score += 1
#Draw Snake
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(img, self.points[-1], 20, (200, 0, 200), cv2.FILLED)
# Draw Food
imgMain = cvzone.overlayPNG(imgMain, self.imgFood, (rx - self.wFood//2,
ry-self.hFood//2))
cvzone.putTextRect(imgMain, f"Your score: {self.score}", [50,80],
scale= 3, thickness=3, offset=10)
# Check for collision
pts = np.array(self.points[:-2], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(imgMain, [pts],False,(0,200,0), 3)
mindistance = cv2.pointPolygonTest(pts,(cx,cy),True)
if -1 < mindistance <=1:
self.gameOver = True
self.points = [] #list of all points of the snake
self.lengths = [] # distance between each point
self.currentLength = 0 # total length of the snake
self.allowedLength = 150 #total allowed length
self.previousHead = 0, 0 # previous head point
self.randomFoodLocatioin()
return imgMain
game = SnakeGameClass("Donut.png")
while True:
success, img = cap.read()
img = cv2.flip(img, 1)
hands,img = detector.findHands(img, flipType=False)
if hands:
lmList = hands[0]['lmList']
pointIndex = lmList[8][0:2]
img = game.update(img,pointIndex)
cv2.imshow('Image', img)
key = cv2.waitKey(1)
if key == ord('r'):
game.gameOver = False
Hope you like this blog and find it usefull🙏
Please share this with your friends and make my day😘
For any query visit my socials👇
Instagram - https://www.instagram.com/python.math/
Twitter - https://twitter.com/Pritish369
Comments
Post a Comment