OpenCV Project – Virtual Puzzle Game
Welcome to this virtual puzzle game. In this game, you will be solving a virtual jigsaw puzzle. The objective is to rearrange the shuffled puzzle pieces to recreate the original image. To play it, simply click on a puzzle piece and an adjacent puzzle piece to swap them. Keep moving the pieces around until the puzzle is solved. This game features three distinct levels, each accompanied by a unique image. The game’s challenge is as the level increases, the total time to solve the current puzzle level decreases. Hope you will enjoy the game once you build it.
Prerequisites for Python OpenCV Virtual Puzzle Game
Creating this game requires a strong grasp of Python and the OpenCV library, as well as the following system requirements.
1. Python 3.7 and above
2. Any Python editor (VS code, Pycharm, etc.)
Download Python OpenCV Virtual Puzzle Game Project
Please download the source code of Python OpenCV Virtual Puzzle Game Project: Python OpenCV Virtual Puzzle Game Project Code.
Installation
Open Windows cmd as administrator
1. Install the OpenCV library by running the command in the command prompt.
pip install opencv-python
Let’s Implement It
To implement this Virtual Puzzle game, follow the below steps.
1. In this game, some packages are required. First of all, we are importing it.
import cv2 import numpy as np import random import time
2. Create a list of the different images that will be used in the game and initialize the current_level variable with 0.
image_path = ['mahesh.jpeg','ms-dhoni.jpeg','apple.jpeg'] current_level = 0
3. Start the while loop.
while current_level < len(image_path):
4. It selects an image based on the current level, defines grid dimensions and cell size, sets a maximum time limit, reads and resizes the image, and shuffles the order of gris cells for the puzzle.
img_path = image_path[current_level] t_row, t_col = 3, 3 grid_w, grid_h = 250, 250 shuffle_iteration = 200 time_max = [90, 60, 30] max_time = time_max[current_level] img = cv2.imread(img_path) img = cv2. resize(img, (t_col * grid_w, t_row * grid_h))
5. This function randomly shuffles the order of the puzzle pieces within a 3*3 grid. It returns the shuffled grid, which represents the new order of the puzzle pieces.
def puz_shuffle():
grid = [(row,col) for row in range(t_row) for col in range(t_col)]
random.shuffle(grid)
return grid
grid_order = puz_shuffle()
6. This function displays the puzzle pieces in their shuffled order, highlights the selected piece in green color and displays the “congratulations” message if the puzzle is solved within time limit.
def draw_puz(img, grid_order, selected_grid, puz_solved,max_time):
puz_img = np.zeros_like(img)
grid_h, grid_w = img.shape[0] // t_row, img.shape[1] // t_col
for r in range(t_row):
for c in range(t_col):
row, col = grid_order[r * t_col + c]
grid = img[row * grid_h:(row+1) * grid_h, col * grid_w:(col+1) * grid_w]
puz_img[r * grid_h:(r+1) * grid_h, c*grid_w:(c+1)*grid_w] = grid
if selected_grid is not None:
r, c = selected_grid
cv2.rectangle(puz_img, (c*grid_w, r*grid_h), ((c+1) * grid_w, (r+1)*grid_h),(0,255,0),2)
if puz_solved:
cv2.putText(puz_img, "Congratulations! You solved the puzzle!", (30, grid_h // 2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
else:
cv2.putText(puz_img, "Time Remaining: {}s".format(max_time), (30, grid_h // 2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
return puz_img
7. This function is responsible for checking if the puzzle is solved or not by comparing the current grid order.
def is_puzzle_solved(grid_order):
return all(grid_order[i] == (i//t_col, i%t_col) for i in range(len(grid_order)))
8. Initialize two variables with none and false.
selected_grid = None puz_solved = False
9. This function handles mouse callback events, selects grids and swaps grids, checks for the solved puzzle flag, and updates the puzzle according to the user’s interactions.
def mouse_callback(event, x, y, flag, param):
global grid_order, selected_grid, puz_solved
if event == cv2.EVENT_LBUTTONDOWN:
col = x//grid_w
row = y//grid_h
emp_row, emp_col = grid_order[-1]
if (row, col) == (emp_row, emp_col):
return
if selected_grid is None:
selected_grid = (row, col)
else:
row_selected, col_selected = selected_grid
if abs(row - row_selected) + abs(col - col_selected) == 1:
selected_index = row_selected * t_col + col_selected
clicked_index = row * t_col + col
grid_order[selected_index], grid_order[clicked_index] = grid_order[clicked_index], grid_order[selected_index]
selected_grid = None
puz_solved = is_puzzle_solved(grid_order)
puzzle_image = draw_puz(img, grid_order, selected_grid, puz_solved, max_time - elapsed_time_seconds)
cv2.imshow('Virtual Puzzle By TechVidvan', puzzle_image)
10. This function creates the window using opencv. It sets up a mouse callback function to handle user interactions with the puzzle game. start_time is initialized to the current time.
cv2.namedWindow('Virtual Puzzle By TechVidvan')
cv2.setMouseCallback('Virtual Puzzle By TechVidvan', mouse_callback)
start_time = time.time()
11. This loop runs until the puzzle game is solved or the time limit is reached. It tracks the time. If the time limit is exceeded, it shows the “Time’s up! You lose” message. If the key ‘q’ is pressed, the game will stop executing.
while True:
elapsed_time_seconds = int(time.time() - start_time)
if elapsed_time_seconds >= max_time:
print("Time's up! You lose!")
cv2.putText(img, "Time's up! You lose!", (30, grid_h // 2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Virtual Puzzle By TechVidvan', img)
puzzle_solved = False
break
puzzle_image = draw_puz(img, grid_order, selected_grid, puz_solved, max_time - elapsed_time_seconds)
cv2.imshow('Virtual Puzzle By TechVidvan', puzzle_image)
if puz_solved:
break
key = cv2.waitKey(1)
if key == ord('q'):
break
cv2.waitKey(2000)
cv2.destroyAllWindows()
current_level += 1
Python OpenCV Virtual Puzzle Game Output:
Python OpenCV Virtual Puzzle Game Video Output
Object Detection
The function responsible for recognizing the completion of the object or image is is_puzzle_solved(). This function systematically evaluates the current arrangement of puzzle pieces by cross-referencing each pieces index with its expected original position within the grid. Should all pieces align correctly, the function returns a True value, indicating the puzzle is solved successfully.
Conversely, a false return signifies that the image is not fully assembled. Once the allocated total time is complete and the image is still not complete, it responds with a message: “Time’s up! You lose.”
Conclusion
In conclusion, a Virtual Puzzle Game using OpenCV provides an engaging and interactive experience. Players solve puzzles by rearranging pieces. The user-friendly interface has a time limit for added excitement. Players can quit or restart the game anytime. This game shows the capabilities of OpenCV’s image processing.



