I have done plenty of projects till date in almost every domain of Data Science, from ML, DL, Computer Vision to NLP, but this immortal snake game in Python is still one of my favorite projects because of its simplicity and user interaction. You will be totally amazed after watching the results in just around 100 lines of code.
Let’s do it…
Code for Immortal snake game in python…
import cv2 import imutils from collections import deque import numpy as np import time score = 0 max_score=20 list_capacity = 0 max_lc =20 l =  flag=0 apple_x = None apple_y = None center = None # distance function def dist(pt1,pt2): return np.sqrt((pt1-pt2)**2 + (pt1-pt2)**2) cap = cv2.VideoCapture(0) # Snake game in Python while 1: ret,frame = cap.read() img = imutils.resize(frame.copy(),width=600) img = cv2.GaussianBlur(img,(11,11),0) img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) if apple_x is None or apple_y is None: # assigning random coefficients for apple coordinates apple_x = np.random.randint(30,frame.shape-30) apple_y = np.random.randint(100,350) cv2.circle(frame,(apple_x,apple_y),3,(0,0,255),-1) # change this range acc to your need greenLower = (29, 86, 18) greenUpper = (93, 255, 255) # masking out the green color mask = cv2.inRange(img,greenLower,greenUpper) mask = cv2.erode(mask,None,iterations=2) mask = cv2.dilate(mask,None,iterations=2) # find contours cnts = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) if len(cnts)>0: ball_cont = max(cnts,key=cv2.contourArea) (x,y),radius = cv2.minEnclosingCircle(ball_cont) # find the minimum enclosing circle about the found contour M = cv2.moments(ball_cont) center = (int(M['m10']/M['m00']),int(M['m01']/M['m00'])) if radius>10: cv2.circle(frame,center,2,(0,0,255),3) if len(l)>list_capacity: l = l[1:] if prev_c and (dist(prev_c,center) >3.5): l.append(center) apple = (apple_x,apple_y) if dist(apple,center)<5: score+=1 if score==max_score: flag=1 list_capacity+=1 apple_x = None apple_y = None for i in range(1,len(l)): if l[i-1] is None or l[i] is None: continue r,g,b = np.random.randint(0,255,3) cv2.line(frame,l[i],l[i-1],(int(r),int(g),int(b)), thickness = int(len(l)/max_lc+2)+2) cv2.putText(frame,'Score :'+str(score),(450,100),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,203),2) if flag==1: cv2.putText(frame,'YOU WIN !!',(100,250),cv2.FONT_HERSHEY_SIMPLEX,3,(255,255,0),3) cv2.imshow('live feed',frame) cv2.imshow('mask',mask) prev_c = center if cv2.waitKey(1)==27: break cv2.destroyAllWindows() cap.release() # This was the code for snake game in Python
- Line 1-5 – Importing required libraries.
- Line 7-14 – Initialising some constants which we will be using further.
- Line 17-19 – Just declaring a distance function, which will simply find the distance between 2 points (x1,y1) and (x2,y2).
- Line 20 – Declaring the VideoCapture object to access the webcam.
- Let’s start the infinit loop to play the snake game in Python…
- Line 25 – Read the image from the webcam.
- Line 26 – Resize the image to a width of 600 and imutils library will maintain the aspect ratio.
- Line 27 – Blur the image to remove noise.
- Line 28 – Convert the BGR image to HSV mode, because we will be making masks in further steps and that works best in HSV mode.
- Line 30 – Just checking if it’s the starting of the loop, because in the starting only both apple_x and apple_y will be None. Here apple is the red dot that the snake eats to gain points.
- Line 33-34 – Randomly assigning integers to apple_x and apple_y, which together will tell the coordinates of the apple.
- Line 36 – Draw a circle or we can say place a dot/apple on the frame. A circle with a radius of 3 pixels will look like a dot.
- Line 39-40 – Set the range of Green color. This is a very sensitive step because taking the wrong range can totally destroy the working of the game. This range is tuned for the green color bottle cap which I am using in the video below. Tune it for the color of your object.
- Line 43 – This will create the mask. It will check every pixel of the image and will check if the color of that pixel is in the range(range specified above) or not. If it is in range mark it as a white pixel otherwise mark it as a black pixel.
- Line 44-45 We are eroding and dilating the image to remove any noise if present to enhance the response of the snake game in Python.
- Line 48-49 – We are simply detecting contours from the mask. Because of the fact that our bottle cap was round, our mask will also be round white on black background. So it will pick this white contour.
- Line 52 – We are checking if we found any contours or not.
- Line 53 – Pick the biggest contour in terms of the area because in many cases small noise contours are also picked up.
- Line 54 – Calculate the minimum enclosing circle of the contour.
- Line 56-57 – Calculate moments of the contour and find the centroid of the contour. This centroid will be the same as the center of the bottle cap.
- Line 59 – If the radius of the biggest contour we found is greater than 10, then we are sure that this is the bottle cap.
- Line 60 – Draw a circle of radius 2 (it will look like a point) at the center (you can see at the center of the bottle).
- Line 62-63 – Just do it :), did it for some tuning.
- Line 68-70 – We are just checking if the distance between our snake’s mouth(bottle center) and apple is less than 5 pixels, mark it as eaten, and increment the score.
- Line 71-72 – If the score reaches 20, set flag=1, which will print ‘YOU WIN’ on the screen.
- Line 73-75 – Increment the list capacity and reset the apple_x and apple_y to None.
- Line 77-82 – Build the snake. The list l will contain all the last n points through which our snake passed and draw the lines between them which will look like a snake. Line 80 is just assigning a random color to each line.
- Line 85 – Put the score on the frame.
- Line 86-87 – If flag=1 means you have reached 20 scores, print ‘YOU WIN’.
- Line 89-90 – Show the main image.
- Line 93-94 – If the user hits the ESC key, break the code.
Do let me know if there’s any query regarding the Snake game in Python by contacting me on email or LinkedIn.
So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time ?…
Read my previous post: HOW TO FIND THE MOST DOMINANT COLORS IN AN IMAGE IN PYTHON USING KMEANS CLUSTERING