๐ฏ Build AI Shooting Game Using Hand Tracking
In this tutorial, we build a real-time AI Shooting Game using Python, OpenCV and MediaPipe. You control the crosshair using your index finger and shoot by pinching your thumb and index finger together.
๐ฆ Install Required Libraries
pip install opencv-python mediapipe
๐ง How The Game Works
- Camera detects your hand
- Index finger controls crosshair
- Thumb + index pinch triggers shoot
- Flying disc moves across screen
- Hit disc → Score increases
๐ง๐ป Full Python Code
import cv2 import mediapipe as mp import random import math import time mp_hands = mp.solutions.hands hands = mp_hands.Hands(max_num_hands=1) cap = cv2.VideoCapture(0) cv2.namedWindow("AI Shooting Game", cv2.WND_PROP_FULLSCREEN) cv2.setWindowProperty("AI Shooting Game", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) score = 0 disc_radius = 30 disc_speed = 6 disc_x = 0 disc_y = 200 last_shot_time = 0 cooldown = 0.5 def new_disc(width, height): x = 0 y = random.randint(100, height - 100) return x, y while True: success, frame = cap.read() if not success: break frame = cv2.flip(frame, 1) height, width, _ = frame.shape rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) result = hands.process(rgb) cross_x = width // 2 cross_y = height // 2 shoot = False if result.multi_hand_landmarks: for hand_landmarks in result.multi_hand_landmarks: landmarks = hand_landmarks.landmark index_tip = landmarks[8] cross_x = int(index_tip.x * width) cross_y = int(index_tip.y * height) thumb_tip = landmarks[4] thumb_x = int(thumb_tip.x * width) thumb_y = int(thumb_tip.y * height) cv2.circle(frame, (cross_x, cross_y), 12, (0,255,0), -1) cv2.circle(frame, (thumb_x, thumb_y), 12, (255,0,0), -1) distance = math.sqrt((cross_x - thumb_x)**2 + (cross_y - thumb_y)**2) if distance < 40: current_time = time.time() if current_time - last_shot_time > cooldown: shoot = True last_shot_time = current_time disc_x += disc_speed if disc_x > width: disc_x, disc_y = new_disc(width, height) cv2.circle(frame, (disc_x, disc_y), disc_radius, (255,200,0), -1) if shoot: distance_to_disc = math.sqrt((cross_x - disc_x)**2 + (cross_y - disc_y)**2) if distance_to_disc < disc_radius: score += 1 disc_x, disc_y = new_disc(width, height) cv2.putText(frame, "Score: " + str(score), (50,70), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0,255,0), 3) cv2.imshow("AI Shooting Game", frame) if cv2.waitKey(1) == 27: break cap.release() cv2.destroyAllWindows()
๐ฎ How To Play
Move your index finger to aim.
Pinch thumb and index finger to shoot.
Hit flying discs to increase score.
Press ESC to exit.
Comments