this initial minesweeper playing code works, now add the actual logic. use number recognition to identify the numbers and locate them on screen and suggest ways to actually play minesweeper. use 1 second action delay! ask needed questions if any. code:
import time
import mss
import pydirectinput
import keyboard # New library for key detection
def capture_grid():
"""Captures the Minesweeper grid from the screen."""
with mss.mss() as sct:
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],
}
sct_img = sct.grab(monitor)
return sct_img # Returns an MSS image object
def get_tile_center(row, col):
"""Calculates the pixel coordinates of the center of a tile."""
x = GRID_TOP_LEFT[0] + (col * TILE_SIZE) + (TILE_SIZE // 2)
y = GRID_TOP_LEFT[1] + (row * TILE_SIZE) + (TILE_SIZE // 2)
return x, y
def click_tile(row, col):
"""Clicks on the center of a specified tile."""
x, y = get_tile_center(row, col)
pydirectinput.moveTo(x, y)
pydirectinput.click()
def main():
"""Main game loop."""
while True:
# 1. Capture the current grid
grid_image = capture_grid()
code
# 2. (We will add logic here to analyze the grid and find a safe tile)
# For now, let's just click the top-left tile as a test
click_tile(0, 0)
# 3. Wait 1 second
time.sleep(1)
if name == "main":
print("Press 'U' to start the Minesweeper automation.")
# Wait for 'U' key press
keyboard.wait('u') # Blocks until 'U' is pressed
main()
Assistant
To enhance your Minesweeper automation script with number recognition and implement actual game-playing logic, we'll follow these steps:
Integrate OCR for Number Recognition:
We'll use pytesseract, a Python wrapper for Google's Tesseract-OCR Engine, to recognize numbers on the Minesweeper grid.
Dependencies: You'll need to install pytesseract and have Tesseract-OCR installed on your system.
Parse the Grid Image:
Capture the grid image and divide it into individual tiles.
Use OCR to identify numbers on each tile.
Represent the grid as a 2D array where each cell holds the number of adjacent mines or indicates if it's flagged as a mine.
Implement Minesweeper Logic:
Analyze the grid to determine safe tiles to click or tiles to flag as mines based on standard Minesweeper deduction rules.
Automate Clicks with Delay:
Implement a 1-second delay between actions to mimic human interaction.
Before proceeding, please ensure you have Tesseract-OCR installed on your system:
Windows: Download the installer from here and follow the installation instructions.
macOS: Use Homebrew: brew install tesseract
Linux: Install via package manager, e.g., sudo apt-get install tesseract-ocr
Also, install the required Python packages if you haven't already:
Now, here's the enhanced script with the described functionality:
python
import time
import mss
import pydirectinput
import keyboard
import pytesseract
import cv2
import numpy as np
from PIL import Image
# Optional: Specify the path to the Tesseract executable if not in PATH
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Game Grid Coordinates
GRID_TOP_LEFT = (798, 408)
GRID_BOTTOM_RIGHT = (1121, 731)
GRID_WIDTH = 10
GRID_HEIGHT = 10
TILE_SIZE = 32
# OCR Configuration
# Configuring pytesseract to recognize digits only
custom_config = r'--oem 3 --psm 10 outputbase digits'
def capture_grid():
"""Captures the Minesweeper grid from the screen."""
with mss.mss() as sct:
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],
}
sct_img = sct.grab(monitor)
# Convert to a format suitable for OpenCV
img = np.array(sct_img)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
return img
def get_tile_center(row, col):
"""Calculates the pixel coordinates of the center of a tile."""
x = GRID_TOP_LEFT[0] + (col * TILE_SIZE) + (TILE_SIZE // 2)
y = GRID_TOP_LEFT[1] + (row * TILE_SIZE) + (TILE_SIZE // 2)
return x, y
def click_tile(row, col, button='left'):
"""Clicks on the center of a specified tile."""
x, y = get_tile_center(row, col)
pydirectinput.moveTo(x, y)
pydirectinput.click(button=button)
def process_grid_image(grid_img):
"""
Processes the captured grid image and returns a 2D array representing the grid.
Each cell can have:
- A number (0-8) indicating adjacent mines
- -1 indicating an unopened tile
- -2 indicating a flagged mine
"""
grid_state = [[-1 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
# Crop the tile image
x_start = col * TILE_SIZE
y_start = row * TILE_SIZE
tile_img = grid_img[y_start:y_start + TILE_SIZE, x_start:x_start + TILE_SIZE]
# Preprocess the tile image for better OCR accuracy
gray = cv2.cvtColor(tile_img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
# Resize to make OCR more accurate
resized = cv2.resize(thresh, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
# Convert to PIL Image
pil_img = Image.fromarray(resized)
# OCR to detect number
text = pytesseract.image_to_string(pil_img, config=custom_config)
text = text.strip()
if text.isdigit():
grid_state[row][col] = int(text)
else:
# Check if tile is flagged (you might need to adjust based on flag icon)
# Here, we'll assume that flagged tiles have no digits
# You might need a better way to detect flags, such as template matching
grid_state[row][col] = -2 # Flagged
return grid_state
def find_safe_moves(grid):
"""
Analyzes the grid and returns a list of safe tiles to click.
Also returns a list of tiles to flag as mines.
"""
safe_moves = []
flag_moves = []
# Iterate through each cell in the grid
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
cell = grid[row][col]
if cell > 0:
# Get neighbors
neighbors = get_neighbors(row, col)
flagged = 0
hidden = []
for n_row, n_col in neighbors:
if grid[n_row][n_col] == -2:
flagged += 1
elif grid[n_row][n_col] == -1:
hidden.append((n_row, n_col))
# If number of flagged neighbors equals the cell number, hidden neighbors are safe
if flagged == cell:
safe_moves.extend(hidden)
# If number of flagged + hidden equals the cell number, hidden neighbors are mines
if flagged + len(hidden) == cell:
flag_moves.extend(hidden)
# Remove duplicates
safe_moves = list(set(safe_moves))
flag_moves = list(set(flag_moves))
return safe_moves, flag_moves
def get_neighbors(row, col):
"""Returns the list of neighboring cell coordinates."""
neighbors = []
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
n_row, n_col = row + dr, col + dc
if 0 <= n_row < GRID_HEIGHT and 0 <= n_col < GRID_WIDTH:
neighbors.append((n_row, n_col))
return neighbors
def mark_mines(flag_moves):
"""Right-clicks on the specified tiles to flag them as mines."""
for move in flag_moves:
row, col = move
click_tile(row, col, button='right')
time.sleep(1) # 1 second delay between actions
def reveal_safe_tiles(safe_moves):
"""Left-clicks on the specified safe tiles to reveal them."""
for move in safe_moves:
row, col = move
click_tile(row, col, button='left')
time.sleep(1) # 1 second delay between actions
def main():
"""Main game loop."""
while True:
# 1. Capture the current grid
grid_img = capture_grid()
# 2. Process grid image to get grid state
grid_state = process_grid_image(grid_img)
# Optional: Print the grid state for debugging
print_grid(grid_state)
# 3. Analyze the grid to find safe moves and flag moves
safe_moves, flag_moves = find_safe_moves(grid_state)
# 4. Execute flagging first
if flag_moves:
print(f"Flagging mines at: {flag_moves}")
mark_mines(flag_moves)
continue # Re-analyze after flagging
# 5. Execute safe moves
if safe_moves:
print(f"Revealing safe tiles at: {safe_moves}")
reveal_safe_tiles(safe_moves)
continue # Re-analyze after revealing
# 6. If no safe moves found, make a random click (can be improved)
print("No safe moves found. Making a random click.")
random_move = get_random_move(grid_state)
if random_move:
row, col = random_move
click_tile(row, col, button='left')
time.sleep(1)
else:
print("No moves left to make. Ending automation.")
break
# 7. Wait 1 second before next iteration
time.sleep(1)
def print_grid(grid):
"""Prints the grid state to the console."""
for row in grid:
row_str = ''
for cell in row:
if cell == -1:
row_str += '□ ' # Unopened
elif cell == -2:
row_str += '⚑ ' # Flagged
else:
row_str += f'{cell} '
print(row_str)
print('\n')
def get_random_move(grid):
"""Selects a random unopened tile."""
hidden_tiles = [(r, c) for r in range(GRID_HEIGHT) for c in range(GRID_WIDTH) if grid[r][c] == -1]
if hidden_tiles:
return hidden_tiles[0] # You can implement better random selection
return None
if __name__ == "__main__":
print("Press 'U' to start the Minesweeper automation.")
# Wait for 'U' key press
keyboard.wait('u') # Blocks until 'U' is pressed
main()
Explanation of the Enhancements
OCR Integration with pytesseract:
The process_grid_image function captures the grid image, divides it into individual tiles, preprocesses each tile for better OCR accuracy (grayscale conversion, thresholding, resizing), and uses pytesseract to recognize numbers.
If a number is recognized, it's stored in the grid_state array. If not, the tile is assumed to be either unopened (-1) or flagged (-2). Currently, tiles without recognized digits are marked as flagged by default (-2), but this may need refinement, such as implementing template matching to detect flag icons accurately.
Grid Representation:
The grid is represented as a 2D list grid_state where each cell holds:
-1: Unopened tile
-2: Flagged tile
0-8: Number indicating adjacent mines
Minesweeper Logic (find_safe_moves function):
For each revealed tile with a number (cell > 0), the script checks its neighbors.
Flagging Logic: If the number of flagged neighbors equals the cell's number, any remaining hidden neighbors are safe to reveal.
Flag Identification: If the number of flagged neighbors plus hidden neighbors equals the cell's number, the hidden neighbors are mines and should be flagged.
Executing Moves:
Flagging Mines: Right-click on tiles identified as mines.
Revealing Safe Tiles: Left-click on tiles identified as safe.
A 1-second delay (time.sleep(1)) is enforced between each action to mimic human behavior.
Random Move Handling:
If no safe moves or flagging moves are found, the script performs a random left-click on an unopened tile. This is a basic implementation and can be enhanced with more sophisticated guessing strategies if needed.
Grid Visualization:
The print_grid function prints the current state of the grid to the console for debugging and monitoring purposes.
Potential Improvements and Considerations
Flag Detection: Currently, the script assumes that tiles without recognized digits are flagged. This might not always be accurate. Implementing template matching with images of flag icons can improve flag detection reliability.
Error Handling: Incorporate error handling to manage scenarios where OCR fails or Tesseract isn't installed correctly.
Advanced Minesweeper Logic: Implement more advanced deduction techniques to handle complex scenarios beyond the basic rules.
Performance Optimization: Optimize the OCR preprocessing steps for faster performance, especially for larger grids.
User Interface: Provide a more interactive user interface to display the grid state or allow manual overrides.
Dynamic Grid Detection: If the Minesweeper grid position or size changes, consider implementing dynamic grid detection rather than using fixed coordinates.
Final Notes
Automating Minesweeper through screen analysis and simulated clicks involves several challenges, especially with accurate OCR and reliable game state detection. Depending on the Minesweeper version and visual style, you might need to adjust the preprocessing steps or OCR configurations to achieve optimal results.
Feel free to test the script and adjust parameters such as grid coordinates, tile size, and OCR configurations to match your specific Minesweeper setup. If you encounter any issues or have further questions, feel free to ask!