-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
92 lines (66 loc) · 2.59 KB
/
main.py
File metadata and controls
92 lines (66 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import cv2
import cvzone
from cvzone.HandTrackingModule import HandDetector
import numpy as np
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
imgBackground = cv2.imread("Resources/Background.png")
imgGameOver = cv2.imread("Resources/gameOver.png")
imgBall = cv2.imread("Resources/Ball.png", cv2.IMREAD_UNCHANGED)
imgBat1 = cv2.imread("Resources/bat1.png", cv2.IMREAD_UNCHANGED)
imgBat2 = cv2.imread("Resources/bat2.png", cv2.IMREAD_UNCHANGED)
detector = HandDetector(detectionCon=0.8, maxHands=2)
ballPos = [100, 100]
speedX = 15
speedY = 15
gameOver = False
score = [0, 0]
while True:
_, img = cap.read()
img = cv2.flip(img, 1)
imgRaw = img.copy()
hands, img = detector.findHands(img, flipType=False)
img = cv2.addWeighted(img, 0.2, imgBackground, 0.8, 0)
if hands:
for hand in hands:
x, y, w, h = hand['bbox']
h1, w1, _ = imgBat1.shape
y1 = y - h1 // 2
y1 = np.clip(y1, 20, 415)
if hand['type'] == "Left":
img = cvzone.overlayPNG(img, imgBat1, (59, y1))
if 59 < ballPos[0] < 59 + w1 and y1 < ballPos[1] < y1 + h1:
speedX = -speedX
ballPos[0] += 30
score[0] += 1
if hand['type'] == "Right":
img = cvzone.overlayPNG(img, imgBat2, (1195, y1))
if 1195 - 50 < ballPos[0] < 1195 and y1 < ballPos[1] < y1 + h1:
speedX = -speedX
ballPos[0] -= 30
score[1] += 1
if ballPos[0] < 40 or ballPos[0] > 1200:
gameOver = True
if gameOver:
img = imgGameOver
cv2.putText(img, str(score[1] + score[0]).zfill(2), (585, 360), cv2.FONT_HERSHEY_COMPLEX,
2.5, (200, 0, 200), 5)
else:
if ballPos[1] >= 500 or ballPos[1] <= 10:
speedY = -speedY
ballPos[0] += speedX
ballPos[1] += speedY
img = cvzone.overlayPNG(img, imgBall, ballPos)
cv2.putText(img, str(score[0]), (300, 650), cv2.FONT_HERSHEY_COMPLEX, 3, (255, 255, 255), 5)
cv2.putText(img, str(score[1]), (900, 650), cv2.FONT_HERSHEY_COMPLEX, 3, (255, 255, 255), 5)
img[580:700, 20:233] = cv2.resize(imgRaw, (213, 120))
cv2.imshow("Image", img)
key = cv2.waitKey(1)
if key == ord('r'):
ballPos = [100, 100]
speedX = 15
speedY = 15
gameOver = False
score = [0, 0]
imgGameOver = cv2.imread("Resources/gameOver.png")