here are my configurations for a minesweeper ai player. create an actual logic for playing minesweeper and detecting numbers. dont save images, we have grid coordinates and we can store everything in memory. use ocr to identify numbers in cells and store them in the grid array, then we just apply a standart minesweeper optimal algorithm. start by clicking in the center somewhere. only start the main program when 'u' is pressed. configurations:
import time
import mss
import pydirectinput
import keyboard
import pytesseract
import cv2
import numpy as np
from PIL import Image
import sys
Tesseract OCR: Download and install from here. Ensure the path is correctly set in the script.
Complete Script:
python
import time
import mss
import pydirectinput
import keyboard
import pytesseract
import cv2
import numpy as np
from PIL import Image
import sys
import threading
# ======================== Configuration ========================
# Specify the path to the Tesseract executable if not in PATH
# Uncomment and set the correct path if necessary
# Example for Windows:
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Game Grid Coordinates (Update these coordinates based on your screen resolution and Minesweeper window position)
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
# Click settings
CLICK_DELAY = 0.05 # Delay between clicks to prevent missing
REVEAL_BUTTON = 'left' # Button to reveal a cell
FLAG_BUTTON = 'right' # Button to flag a cell
# Define states for each cell
UNKNOWN = -1
FLAGGED = -2
# ======================== Utility Functions ========================
def get_tile_coordinates(row, col):
"""
Get the top-left coordinates of a specific tile based on its row and column.
"""
x = GRID_TOP_LEFT[0] + col * TILE_SIZE
y = GRID_TOP_LEFT[1] + row * TILE_SIZE
return (x, y)
def capture_tile(sct, row, col):
"""
Capture a specific tile from the screen.
"""
x, y = get_tile_coordinates(row, col)
bbox = {
'top': y,
'left': x,
'width': TILE_SIZE,
'height': TILE_SIZE
}
img = sct.grab(bbox)
img = Image.frombytes('RGB', img.size, img.rgb)
return img
def preprocess_image(image):
"""
Preprocess the image for better OCR accuracy.
"""
# Convert to grayscale
img = image.convert('L')
# Convert to numpy array
img = np.array(img)
# Apply thresholding to make the numbers stand out
_, img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
return img
def ocr_tile(image):
"""
Perform OCR on a preprocessed image to extract the number.
"""
config = '--psm 10 --oem 3 -c tessedit_char_whitelist=012345678'
text = pytesseract.image_to_string(image, config=config)
text = text.strip()
if text.isdigit():
return int(text)
else:
return UNKNOWN
# ======================== Minesweeper Logic ========================
class MinesweeperAI:
def __init__(self, width, height):
self.width = width
self.height = height
# Initialize the grid with UNKNOWN
self.grid = [[UNKNOWN for _ in range(width)] for _ in range(height)]
# Initialize flags
self.flags = set()
# Initialize revealed cells
self.revealed = set()
# Keep track of moves to make
self.to_reveal = set()
self.to_flag = set()
def update_grid(self, current_grid):
"""
Update the AI's internal grid with the latest captured numbers.
"""
for row in range(self.height):
for col in range(self.width):
if current_grid[row][col] >= 0:
self.grid[row][col] = current_grid[row][col]
self.revealed.add((row, col))
def get_neighbors(self, row, col):
"""
Get all valid neighbors for a cell.
"""
neighbors = []
for r in range(max(0, row-1), min(self.height, row+2)):
for c in range(max(0, col-1), min(self.width, col+2)):
if (r, c) != (row, col):
neighbors.append((r, c))
return neighbors
def analyze(self):
"""
Analyze the grid and decide which cells to reveal or flag.
"""
self.to_reveal.clear()
self.to_flag.clear()
for row, col in self.revealed:
number = self.grid[row][col]
neighbors = self.get_neighbors(row, col)
hidden = [n for n in neighbors if self.grid[n[0]][n[1]] == UNKNOWN]
flagged = [n for n in neighbors if n in self.flags]
if number == len(flagged) + len(hidden) and len(hidden) > 0:
# All hidden neighbors are mines
for cell in hidden:
self.to_flag.add(cell)
elif number == len(flagged) and len(hidden) > 0:
# All hidden neighbors are safe
for cell in hidden:
self.to_reveal.add(cell)
def make_moves(self):
"""
Execute the moves decided by the analyze method.
"""
for cell in self.to_flag:
if cell not in self.flags:
self.flags.add(cell)
self.click_cell(cell[0], cell[1], FLAG_BUTTON)
for cell in self.to_reveal:
if cell not in self.revealed and cell not in self.flags:
self.click_cell(cell[0], cell[1], REVEAL_BUTTON)
def click_cell(self, row, col, button):
"""
Simulate a mouse click on a specific cell.
"""
x, y = get_tile_coordinates(row, col)
# Click in the center of the tile
click_x = x + TILE_SIZE // 2
click_y = y + TILE_SIZE // 2
pydirectinput.click(x=click_x, y=click_y, button=button)
time.sleep(CLICK_DELAY)
def is_solved(self):
"""
Check if all non-mine cells are revealed.
"""
total_cells = self.width * self.height
# Assuming 10 mines for a 10x10 grid; adjust as needed
total_mines = 10
return len(self.revealed) == total_cells - total_mines
# ======================== Main Program ========================
def main():
print("Minesweeper AI is running.")
print("Press 'u' to start the AI.")
# Wait for 'u' key press to start
keyboard.wait('u')
print("'u' pressed. Starting Minesweeper AI...")
time.sleep(1) # Short delay before starting
# Initialize MSS for screenshot
sct = mss.mss()
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]
}
# Initialize AI
ai = MinesweeperAI(GRID_WIDTH, GRID_HEIGHT)
# Click the center cell to start
center_row = GRID_HEIGHT // 2
center_col = GRID_WIDTH // 2
ai.click_cell(center_row, center_col, REVEAL_BUTTON)
time.sleep(0.5) # Wait for the game to update
# Main Loop
while True:
start_time = time.time()
current_grid = [[UNKNOWN for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
# Capture the entire grid
img = sct.grab(monitor)
img = Image.frombytes('RGB', img.size, img.rgb)
# Analyze each cell
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
# Capture each tile
tile_img = capture_tile(sct, row, col)
# Preprocess the image
processed_img = preprocess_image(tile_img)
# Perform OCR
number = ocr_tile(processed_img)
current_grid[row][col] = number
# Update AI's internal grid
ai.update_grid(current_grid)
# Analyze and decide on moves
ai.analyze()
# Make the moves
ai.make_moves()
# Check if the game is solved
if ai.is_solved():
print("Congratulations! The AI has solved the game.")
break
# Optional: Add a condition to break if game is lost
# This would require detecting if a mine was triggered, possibly by checking for a specific screen state
# Sleep to control the loop speed
elapsed = time.time() - start_time
time.sleep(max(0.5 - elapsed, 0)) # Aim for ~0.5 seconds per iteration
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nMinesweeper AI terminated by user.")
sys.exit(0)
Explanation of the Script:
Configuration Section:
Tesseract Path: Ensure pytesseract.pytesseract.tesseract_cmd points to your Tesseract installation.
Grid Coordinates: Update GRID_TOP_LEFT and GRID_BOTTOM_RIGHT based on your Minesweeper window's position and resolution.
Grid Size:GRID_WIDTH, GRID_HEIGHT, and TILE_SIZE should match your game's grid.
Utility Functions:
get_tile_coordinates: Calculates the top-left pixel coordinates of a given cell based on its row and column.
capture_tile: Captures a specific cell's image using mss.
preprocess_image: Converts the image to grayscale and applies thresholding to enhance OCR accuracy.
ocr_tile: Uses pytesseract to extract the number from the preprocessed image. If OCR fails, it returns UNKNOWN.
MinesweeperAI Class:
Initialization: Sets up the grid, flags, and revealed cells.
update_grid: Updates the internal grid with the latest OCR results.
get_neighbors: Retrieves all valid neighboring cells for a given cell.
analyze: Implements the standard Minesweeper logic:
If the number of hidden neighbors equals the number on the cell, flag all hidden neighbors.
If the number of flagged neighbors equals the number on the cell, reveal all other hidden neighbors.
make_moves: Executes the decisions by simulating mouse clicks using pydirectinput.
click_cell: Handles the actual clicking on the game window.
is_solved: Determines if the game is solved based on revealed cells. Note: Adjust the total_mines as per your game settings.
Main Program Flow:
Wait for 'u' Key Press: The program starts when the user presses the 'u' key.
Additional Considerations:
Mine Count: Ensure that the total_mines variable in the is_solved method matches the actual number of mines in your game. Adjust it if necessary.
Game Loss Detection: Currently, the script does not handle game-over scenarios (e.g., clicking on a mine). To implement this, you can add additional OCR checks to detect specific game-over messages or visual cues and terminate the script accordingly.
OCR Accuracy: OCR might occasionally misread numbers, especially if the game's graphics are complex. You can improve accuracy by experimenting with different preprocessing techniques or adjusting Tesseract's configuration.
Performance Optimization: Depending on your system's performance, you might need to adjust the loop's delay (time.sleep) to balance speed and reliability.
Safety and Control: Always ensure that your script does not interfere with other applications. It's recommended to run the Minesweeper game in a controlled environment where automated clicks won't cause unintended actions in other applications.
Running the Script:
Setup:
Ensure Minesweeper is open and positioned correctly based on the GRID_TOP_LEFT and GRID_BOTTOM_RIGHT coordinates.
Make sure Tesseract OCR is installed and the path is correctly set in the script.
Execute:
Run the script using Python:
bash
python minesweeper_ai.py
Press the 'u' key to start the AI.
Observe:
The AI will click the center cell and begin solving the Minesweeper game automatically.
Final Notes:
This script provides a foundational AI for playing Minesweeper using screen capture and OCR. Depending on the game's complexity and variations, further enhancements might be necessary to handle more advanced scenarios, improve OCR accuracy, and ensure robust interaction with the game window.
Feel free to modify and expand upon this script to better fit your specific requirements and to incorporate more sophisticated Minesweeper-solving algorithms.
Not yet included in a published release.
Initialize Screen Capture: Sets up mss to capture the game grid.
Initialize AI: Creates an instance of MinesweeperAI.
Initial Click: Clicks the center cell to begin the game.
Main Loop:
Capture Grid: Takes a screenshot of the entire grid.
OCR Processing: Processes each cell to determine its state.
AI Update: Updates the internal grid and analyzes possible moves.
Execute Moves: Makes the necessary clicks to reveal or flag cells.
Check for Solution: Determines if the game has been successfully solved.
Loop Timing: Controls the loop to run at a manageable speed.