Python Central HubSign in

Python Projects / Advanced

AR (Augmented Reality) Game

A Python application for building an augmented reality game, featuring computer vision, object tracking, and a CLI interface.

Abstract

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.

Prerequisites

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

Before you Start

Install Python and the required libraries:

Shell
pip install opencv-python numpy

Getting Started

Create a Project

  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.

Write the Code

AR (Augmented Reality) GameSource
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)

Example Usage

Shell
python ar_augmented_reality_game.py

How it fits together

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

Explanation

Key Features

  • 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.

Code Breakdown

  1. What it imports (lines 11–14)
Python
import cv2
import numpy as np
import sys
import random
  1. ARGame — the class (lines 16–47)
Python
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.

Features

  • 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

Next Steps

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

Educational Value

This project teaches:

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

Real-World Applications

  • AR Games
  • Educational Tools
  • Interactive Media

Checkpoint exercise

This exercise practises projecting 3D points to screen pixels with a pinhole camera, the maths behind placing AR objects.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Conclusion

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.

Was this page helpful?

Let us know how we did