Skip to main content

How to Make Gesture Controlled Snake Game in Python || Python code for snake game - Creation Code

 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

  1. Our first work will be to againcognising the hand
  2. Then find the point of the finger
  3. Now we will going to create a point with the finger
  4. We need to create a logic where the point will increase as we move the finger
  5. Next step is to stop the snake game when the coordinate of the points clash with each other
  6. 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👇






Comments

Popular posts from this blog

Create Ping Pong Game in Python

  Ping Pong Game: Table tennis , also known as  ping-pong  and  whiff-whaff , is a sport in which two or four players hit a lightweight ball, also known as the ping-pong ball, back and forth across a table using small rackets. The game takes place on a hard table divided by a net. Except for the initial serve, the rules are generally as follows: players must allow a ball played toward them to bounce once on their side of the table and must return it so that it bounces on the opposite side at least once. A point is scored when a player fails to return the ball within the rules. Play is fast and demands quick reactions. Spinning the ball alters its trajectory and limits an opponent's options, giving the hitter a great advantage. We can make it using pygame but I keep it more simple we will create this game using only the turtle module so let's drive into the code without wasting any time Code: # Import required library import turtle # Create screen sc = turtle . Screen () sc .

Draw Minecraft Charater in Python

  Minecraft  is a  sandbox video game  developed by the Swedish video game developer  Mojang Studios . The game was created by  Markus "Notch" Persson  in the  Java programming language . Following several early private testing versions, it was first made public in May 2009 before fully releasing in November 2011, with  Jens Bergensten  then taking over development.  Minecraft  has since been ported to several other platforms and is the  best-selling video game of all time , with over 238 million copies sold and nearly 140 million  monthly active users  as of 2021 . We gonna build a character of Minecraft using our creativity and coding skills so let's drive into the code: Code: import turtle as t def eye ( r , a ):     t . fillcolor ( 'brown' )     t . begin_fill ()     t . circle ( r , a )     t . end_fill () t . begin_fill () t . fillcolor ( '#8a00e6' ) t . penup () t . goto ( 0 ,- 50 ) t . pendown () t . right ( 90 ) t . f

How To Draw BMW Logo - In Python

 I know I don't need to introduce BMW as it is a very popular luxury car. Today we gonna draw the BMW logo in python. I know that you can draw it using a pencil and other tools like AutoCAD etc. But we are programmers we talk with computers so let's tell our computer to draw this logo for use with the help of python. Module The only module we will use is that turtle Code: import turtle as t t.begin_fill() t.fillcolor( '#008ac9' ) for i in range ( 50 ):     t.forward( 4 )     t.left( 2 ) t.right(- 80 ) t.forward( 116 ) t.right(- 90 ) t.forward( 132 ) t.end_fill() t.penup() t.pendown() t.right( 90 ) for i in range ( 50 ):     t.forward( 4 )     t.left(- 2 ) t.right( 80 ) t.forward( 116 ) t.forward(- 116 ) t.right( 90 ) t.begin_fill() t.fillcolor( '#008ac9' ) for j in range ( 45 ):     t.forward(- 4 )     t.left(- 2 ) t.right(- 90 ) t.forward( 116 ) t.end_fill() t.right( 180 ) t.forward( 116 ) t.right( 90 ) for i in range ( 47 ):     t.forward( 4 )     t.