Certainly! Below is a complete Python script that integrates with your existing configuration to perform pattern matching for counting visible "1"s and "2"s on a Minesweeper board. The script listens for the 'u' key press to start the counting process.
Overview
- Screen Capture: Uses
mss to capture the specified grid area of the Minesweeper game.
- Template Matching: Compares each tile in the grid with the provided "1" and "2" templates using OpenCV's
matchTemplate function.
- Counting: Increments counters based on successful matches.
- Keyboard Listener: Utilizes the
keyboard library to trigger the counting process when the 'u' key is pressed.
Complete Code
import time
import mss
import pydirectinput
import keyboard
import cv2
import numpy as np
from PIL import Image
from datetime import datetime
# Configuration
GRID_TOP_LEFT = (798, 408) # (x, y)
GRID_BOTTOM_RIGHT = (1121, 731) # (x, y)
GRID_WIDTH = 10 # Number of columns
GRID_HEIGHT = 10 # Number of rows
TILE_SIZE = 32 # Size of each tile in pixels
# Load templates for "one", "two", and "three"
template_one = cv2.imread('1.png', cv2.IMREAD_UNCHANGED) # Include transparency
template_two = cv2.imread('2.png', cv2.IMREAD_UNCHANGED)
template_three = cv2.imread('3.png', cv2.IMREAD_UNCHANGED)
# Check if templates are loaded correctly
if template_one is None:
raise FileNotFoundError("Template image '1.png' not found.")
if template_two is None:
raise FileNotFoundError("Template image '2.png' not found.")
if template_three is None:
raise FileNotFoundError("Template image '3.png' not found.")
# Preprocess templates: Convert to grayscale
template_one_gray = cv2.cvtColor(template_one, cv2.COLOR_BGRA2GRAY)
template_two_gray = cv2.cvtColor(template_two, cv2.COLOR_BGRA2GRAY)
template_three_gray = cv2.cvtColor(template_three, cv2.COLOR_BGRA2GRAY)
# Optional: Apply threshold to templates to make matching more robust
_, template_one_thresh = cv2.threshold(template_one_gray, 127, 255, cv2.THRESH_BINARY)
_, template_two_thresh = cv2.threshold(template_two_gray, 127, 255, cv2.THRESH_BINARY)
_, template_three_thresh = cv2.threshold(template_three_gray, 127, 255, cv2.THRESH_BINARY)
def count_numbers():
"""
Capture the screen, process the grid, and count the number of "1"s and "2"s.
"""
with mss.mss() as sct:
# Define the region of the screen to capture
monitor = {
"top": GRID_TOP_LEFT[1],
"left": GRID_TOP_LEFT[0],
"width": GRID_BOTTOM_RIGHT[0] - GRID_TOP_LEFT[0],
"height": GRID_BOTTOM_RIGHT[1] - GRID_TOP_LEFT[1],
}
# Capture the screen
screenshot = sct.grab(monitor)
img = np.array(screenshot)
# Convert image from BGRA to BGR
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
# Convert to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# Optionally, apply threshold to the captured grid to enhance matching
_, img_thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
count_one = 0
count_two = 0
# Iterate over each tile in the grid
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
# Calculate the position of the current tile
x_start = col * TILE_SIZE
y_start = row * TILE_SIZE
x_end = x_start + TILE_SIZE
y_end = y_start + TILE_SIZE
# Extract the tile from the grid
tile = img_thresh[y_start:y_end, x_start:x_end]
# Ensure the tile has the correct size
if tile.shape[0] != TILE_SIZE or tile.shape[1] != TILE_SIZE:
continue # Skip incomplete tiles
# Match with "1" template
res_one = cv2.matchTemplate(tile, template_one_thresh, cv2.TM_CCOEFF_NORMED)
_, max_val_one, _, _ = cv2.minMaxLoc(res_one)
# Match with "2" template
res_two = cv2.matchTemplate(tile, template_two_thresh, cv2.TM_CCOEFF_NORMED)
_, max_val_two, _, _ = cv2.minMaxLoc(res_two)
# Define similarity thresholds (these may need adjustment)
threshold = 0.8
# Increment counters based on matching scores
if max_val_one >= threshold:
count_one += 1
elif max_val_two >= threshold:
count_two += 1
# Uncomment below if you want to count "3"s as well
# elif max_val_three >= threshold:
# count_three += 1
print(f"[{datetime.now().strftime('%H:%M:%S')}] Found {count_one} '1's and {count_two} '2's on the board.")
def on_u_press(event):
"""
Callback function triggered when 'u' is pressed.
"""
if event.name == 'u' and event.event_type == 'down':
count_numbers()
def main():
"""
Main function to set up the keyboard listener.
"""
print("Minesweeper AI Player is running.")
print("Press 'u' to count the number of '1's and '2's on the board.")
print("Press 'esc' to exit.")
# Register the 'u' key event
keyboard.on_press(on_u_press)
# Keep the program running until 'esc' is pressed
keyboard.wait('esc')
print("Exiting Minesweeper AI Player.")
if __name__ == "__main__":
main()
Detailed Explanation
-
Template Loading and Preprocessing
# Load templates for "one", "two", and "three"
template_one = cv2.imread('1.png', cv2.IMREAD_UNCHANGED) # Include transparency
template_two = cv2.imread('2.png', cv2.IMREAD_UNCHANGED)
template_three = cv2.imread('3.png', cv2.IMREAD_UNCHANGED)
# Check if templates are loaded correctly
if template_one is None:
raise FileNotFoundError("Template image '1.png' not found.")
if template_two is None:
raise FileNotFoundError("Template image '2.png' not found.")
if template_three is None:
raise FileNotFoundError("Template image '3.png' not found.")
# Preprocess templates: Convert to grayscale
template_one_gray = cv2.cvtColor(template_one, cv2.COLOR_BGRA2GRAY)
template_two_gray = cv2.cvtColor(template_two, cv2.COLOR_BGRA2GRAY)
template_three_gray = cv2.cvtColor(template_three, cv2.COLOR_BGRA2GRAY)
# Apply threshold to templates
_, template_one_thresh = cv2.threshold(template_one_gray, 127, 255, cv2.THRESH_BINARY)
_, template_two_thresh = cv2.threshold(template_two_gray, 127, 255, cv2.THRESH_BINARY)
_, template_three_thresh = cv2.threshold(template_three_gray, 127, 255, cv2.THRESH_BINARY)
- Loading Templates: The script loads the template images for "1", "2", and "3". It raises an error if any template is not found.
- Grayscale Conversion: Templates are converted to grayscale to simplify the matching process.
- Thresholding: Applying a binary threshold helps in making the template matching more robust against variations in lighting or rendering.
-
Counting Function
def count_numbers():
# ... [Code as above]
- Screen Capture: Captures the specified grid region using
mss.
- Preprocessing: Converts the captured image to grayscale and applies a binary threshold.
- Tile Iteration: Loops through each tile in the grid based on
GRID_WIDTH, GRID_HEIGHT, and TILE_SIZE.
- Template Matching: Uses
cv2.matchTemplate to compare each tile with the "1" and "2" templates.
- Thresholding: Determines if a match is successful based on a predefined similarity threshold (
threshold = 0.8). You may need to adjust this value based on your templates and screen resolution.
- Counting: Increments
count_one and count_two accordingly and prints the result with a timestamp.
-
Notes and Recommendations
-
Threshold Adjustment: The threshold value in the count_numbers function is set to 0.8. Depending on the quality and variance of your templates and screen captures, you might need to tweak this value for optimal performance.
-
Template Size: Ensure that your template images (1.png, 2.png, 3.png) perfectly match the size (TILE_SIZE x TILE_SIZE) of the tiles on the Minesweeper board. Mismatched sizes can lead to poor matching results.
-
Performance Optimization: For larger grids or more frequent captures, consider optimizing the code by pre-processing templates or using multi-threading.
-
Error Handling: The script includes basic error handling for missing template images. Depending on your use case, you might want to add more robust error management.
-
Extensibility: Currently, the script counts "1"s and "2"s. You can extend it to count "3"s or other numbers by following similar steps.
Dependencies
Ensure you have the required Python libraries installed. You can install them using pip:
pip install mss pydirectinput keyboard opencv-python numpy pillow
Usage
-
Prepare Templates: Ensure that 1.png, 2.png, and 3.png are in the same directory as your script and accurately represent the Minesweeper tiles without backgrounds.
-
Run the Script: Execute the script. It will wait for you to press the 'u' key.
-
Trigger Counting: Press 'u' while the Minesweeper game is active and visible on the screen within the specified coordinates.
-
Exit: Press 'esc' to terminate the script.
Example Output
Minesweeper AI Player is running.
Press 'u' to count the number of '1's and '2's on the board.
Press 'esc' to exit.
[14:23:45] Found 12 '1's and 8 '2's on the board.
[14:24:10] Found 13 '1's and 9 '2's on the board.
This output indicates the count of "1"s and "2"s detected each time you press 'u'.
Feel free to modify and expand upon this script to suit your specific needs for your Minesweeper AI player. If you encounter any issues or have further questions, don't hesitate to ask!