Skip to content

AR (Augmented Reality) Game

AR (Augmented Reality) Game is a Python project that uses computer vision to create interactive augmented reality experiences. The application features object tracking, game logic, and a CLI interface, demonstrating best practices in AR development and computer vision.

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of computer vision and AR
  • Required libraries: opencv-python, numpy

Install Python and the required libraries:

Install dependencies
pip install opencv-python numpy
  1. Create a folder named ar-augmented-reality-game.
  2. Open the folder in your code editor or IDE.
  3. Create a file named ar_augmented_reality_game.py.
  4. Copy the code below into your file.
AR (Augmented Reality) Game pch.viewSource
AR (Augmented Reality) Game
"""
AR (Augmented Reality) Game

Features:
- Marker detection
- Interactive gameplay
- Modular design
- GUI (OpenCV)
- Error handling
"""
import cv2
import numpy as np
import sys
import random

class ARGame:
    def __init__(self):
        self.marker_color = (0,255,0)
        self.score = 0
    def detect_marker(self, frame):
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        lower = np.array([40, 40, 40])
        upper = np.array([80, 255, 255])
        mask = cv2.inRange(hsv, lower, upper)
        cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        if cnts:
            c = max(cnts, key=cv2.contourArea)
            x, y, w, h = cv2.boundingRect(c)
            return (x, y, w, h)
        return None
    def play(self):
        cap = cv2.VideoCapture(0)
        while True:
            ret, frame = cap.read()
            if not ret:
                break
            marker = self.detect_marker(frame)
            if marker:
                x, y, w, h = marker
                cv2.rectangle(frame, (x, y), (x+w, y+h), self.marker_color, 2)
                self.score += 1
                cv2.putText(frame, f"Score: {self.score}", (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 2)
            show_or_save('AR Game', frame)
            if wait_or_skip(1) & 0xFF == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows() if "--show" in __import__("sys").argv else None

def wait_or_skip(delay=0):
    """cv2.waitKey needs a window; without one it raises. Skip it instead."""
    import sys

    if "--show" in sys.argv:
        return cv2.waitKey(delay)
    return -1


def show_or_save(title, image, _counter=[0]):
    """Display the frame, or write it to a file when no window is available.

    Headless OpenCV has no GUI at all, and even a full build cannot open a
    window over SSH or inside a container. Falling back to a file keeps the
    project runnable everywhere and leaves something to look at afterwards.
    """
    import os
    import re as _re

    if "--show" in __import__("sys").argv:
        cv2.imshow(title, image)
        return None
    _counter[0] += 1
    stem = _re.sub(r"\W+", "_", title).strip("_").lower() or "frame"
    name = f"{stem}.png" if _counter[0] == 1 else f"{stem}_{_counter[0]}.png"
    cv2.imwrite(name, image)
    print(f"saved {name}  ({os.path.getsize(name):,} bytes)")
    return name


if __name__ == "__main__":
    try:
        game = ARGame()
        game.play()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
Run AR game
python ar_augmented_reality_game.py

Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.

diagram Diagram mermaid
  • Object Tracking: Uses computer vision for AR interaction.
  • Game Logic: Implements interactive AR gameplay.
  • Error Handling: Validates inputs and manages exceptions.
  • CLI Interface: Interactive command-line usage.
  1. What it imports (lines 11–14)
ar_augmented_reality_game.py
import cv2
import numpy as np
import sys
import random
  1. ARGame — the class (lines 16–47)
ar_augmented_reality_game.py
class ARGame:
    def __init__(self):
        self.marker_color = (0,255,0)
        self.score = 0
    def detect_marker(self, frame):
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        lower = np.array([40, 40, 40])
        upper = np.array([80, 255, 255])
        mask = cv2.inRange(hsv, lower, upper)
        cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        if cnts:
            c = max(cnts, key=cv2.contourArea)
            x, y, w, h = cv2.boundingRect(c)
            return (x, y, w, h)
        return None
    def play(self):
        cap = cv2.VideoCapture(0)
        while True:
                # ... 8 more lines in the file ...
                cv2.putText(frame, f"Score: {self.score}", (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0), 2)
            cv2.imshow('AR Game', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        cap.release()
        cv2.destroyAllWindows()

The file defines 1 top-level symbol in all; the whole thing is above under Write the Code.

  • AR Game Development: Interactive augmented reality gameplay
  • Object Tracking: Uses computer vision for AR
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Enhance the project by:

  • Supporting more AR interactions
  • Creating a GUI with Tkinter or a web app with Flask
  • Adding game levels and scoring
  • Unit testing for reliability

This project teaches:

  • AR Development: Object tracking and game logic
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code
  • AR Games
  • Educational Tools
  • Interactive Media

AR (Augmented Reality) Game demonstrates how to build a scalable and interactive AR game using Python. With modular design and extensibility, this project can be adapted for real-world applications in gaming, education, and more. For more advanced projects, visit Python Central Hub.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading