Skip to content

Commit a2dc331

Browse files
authoredSep 27, 2022
Merge pull request #96 from sanjail3/mbranch
Added snake game
2 parents b13afe5 + 93047dd commit a2dc331

15 files changed

+265
-0
lines changed
 

‎.idea/.gitignore

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.idea/Beginners-Python-Examples.iml

+12
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.idea/inspectionProfiles/Project_Default.xml

+43
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.idea/inspectionProfiles/profiles_settings.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.idea/misc.xml

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.idea/modules.xml

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.idea/vcs.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎snake game/.idea/.gitignore

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎snake game/.idea/inspectionProfiles/profiles_settings.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎snake game/.idea/misc.xml

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎snake game/.idea/modules.xml

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎snake game/.idea/snake game.iml

+10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎snake game/donut.png

5.09 KB
Loading

‎snake game/index.html

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html>
3+
4+
5+
<body>
6+
<h1>Live streaming</h1>
7+
<div>
8+
9+
<img src="{{ url_for('video') }}" width="50%"/>
10+
</div>
11+
12+
</body>
13+
14+
15+
</html>

‎snake game/main.py

+134
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import math
2+
import random
3+
import cvzone
4+
import cv2
5+
import numpy as np
6+
from cvzone.HandTrackingModule import HandDetector
7+
from flask import Flask,render_template,Response
8+
9+
app=Flask(__name__)
10+
cap = cv2.VideoCapture(0)
11+
cap.set(3, 1280)
12+
cap.set(4, 720)
13+
14+
detector = HandDetector(detectionCon=0.8, maxHands=1)
15+
16+
17+
class SnakeGameClass:
18+
def __init__(self, pathFood):
19+
self.points = [] # all points of the snake
20+
self.lengths = [] # distance between each point
21+
self.currentLength = 0 # total length of the snake
22+
self.allowedLength = 150 # total allowed Length
23+
self.previousHead = 0, 0 # previous head point
24+
25+
self.imgFood = cv2.imread(pathFood, cv2.IMREAD_UNCHANGED)
26+
self.hFood, self.wFood, _ = self.imgFood.shape
27+
self.foodPoint = 0, 0
28+
self.randomFoodLocation()
29+
30+
self.score = 0
31+
self.gameOver = False
32+
33+
def randomFoodLocation(self):
34+
self.foodPoint = random.randint(100, 1000), random.randint(100, 600)
35+
36+
def update(self, imgMain, currentHead):
37+
38+
if self.gameOver:
39+
cvzone.putTextRect(imgMain, "Game Over", [300, 400],
40+
scale=7, thickness=5, offset=20)
41+
cvzone.putTextRect(imgMain, f'Your Score: {self.score}', [300, 550],
42+
scale=7, thickness=5, offset=20)
43+
else:
44+
px, py = self.previousHead
45+
cx, cy = currentHead
46+
47+
self.points.append([cx, cy])
48+
distance = math.hypot(cx - px, cy - py)
49+
self.lengths.append(distance)
50+
self.currentLength += distance
51+
self.previousHead = cx, cy
52+
53+
# Length Reduction
54+
if self.currentLength > self.allowedLength:
55+
for i, length in enumerate(self.lengths):
56+
self.currentLength -= length
57+
self.lengths.pop(i)
58+
self.points.pop(i)
59+
if self.currentLength < self.allowedLength:
60+
break
61+
62+
# Check if snake ate the Food
63+
rx, ry = self.foodPoint
64+
if rx - self.wFood // 2 < cx < rx + self.wFood // 2 and \
65+
ry - self.hFood // 2 < cy < ry + self.hFood // 2:
66+
self.randomFoodLocation()
67+
self.allowedLength += 50
68+
self.score += 1
69+
print(self.score)
70+
71+
# Draw Snake
72+
if self.points:
73+
for i, point in enumerate(self.points):
74+
if i != 0:
75+
cv2.line(imgMain, tuple(self.points[i - 1]), tuple(self.points[i]), (0, 0, 255), 20)
76+
cv2.circle(imgMain, tuple(self.points[-1]), 20, (0, 255, 0), cv2.FILLED)
77+
78+
# Draw Food
79+
imgMain = cvzone.overlayPNG(imgMain, self.imgFood,
80+
(rx - self.wFood // 2, ry - self.hFood // 2))
81+
82+
cvzone.putTextRect(imgMain, f'Score: {self.score}', [50, 80],
83+
scale=3, thickness=3, offset=10)
84+
85+
# Check for Collision
86+
pts = np.array(self.points[:-2], np.int32)
87+
pts = pts.reshape((-1, 1, 2))
88+
cv2.polylines(imgMain, [pts], False, (0, 255, 0), 3)
89+
minDist = cv2.pointPolygonTest(pts, (cx, cy), True)
90+
91+
if -1 <= minDist <= 1:
92+
print("Hit")
93+
self.gameOver = True
94+
self.points = [] # all points of the snake
95+
self.lengths = [] # distance between each point
96+
self.currentLength = 0 # total length of the snake
97+
self.allowedLength = 150 # total allowed Length
98+
self.previousHead = 0, 0 # previous head point
99+
self.randomFoodLocation()
100+
101+
return imgMain
102+
103+
104+
game = SnakeGameClass("donut.png")
105+
106+
def game1():
107+
while True:
108+
success, img = cap.read()
109+
img = cv2.flip(img, 1)
110+
hands, img = detector.findHands(img, flipType=False)
111+
112+
if hands:
113+
lmList = hands[0]['lmList']
114+
pointIndex = lmList[8][0:2]
115+
img = game.update(img, pointIndex)
116+
cv2.imshow("Image", img)
117+
key = cv2.waitKey(1)
118+
if key == ord('r'):
119+
game.gameOver = False
120+
yield (b'--frame\r\n'
121+
b'Content-Type: image/jpeg\r\n\r\n' + img+ b'\r\n')
122+
123+
@app.route('/')
124+
def index():
125+
return render_template('index.html')
126+
127+
128+
@app.route('/video')
129+
def video():
130+
return Response(game1())
131+
132+
133+
if __name__=='__main__':
134+
app.run()

0 commit comments

Comments
 (0)
Failed to load comments.