Completely Automating Minesweeper with Python

AutoSweeper In Action

Pudding is more delicious, so read ahead only if you really want to know how I automated minesweeper with Python.


I wrote this tool because I literally loathe Minesweeper and I was somehow playing a lot of it and losing.  And I doubt I'm the first person to do this, but it was still an interesting exercise of Python on Windows.  In order to make use of this, you need the following things:

  • Python 2.7
  • PyWin32
  • Python Image Library

You can contribute to this by forking/downloading the code here:

Once you have the code and the prerequisite libraries in place, set your minesweeper instance to be at the "advanced" level and place the window (in its smallest form) flush against the top left part of your screen.  It must be exactly against the wall for the numbers to be read correctly.  Yes, I know this is inconvenient, but if you want to fix it, the code is right above this.

How Does AutoSweeper Work!?

The tool is incredibly simple and quite stupid, right now.  Basically, I use PyWin32 to place the mouse on the top left tile and have the mouse click to start the game.  I then use the Python Image Library to grab a screen shot of the game and then go through one tile at a time looking for a change against the un-altered tiles and then I investigate if that change has resulted in a number.  I identify numbers by looking for a specifically colored pixel in a box of 9 pixels (to account for weirdness in the minesweeper rendering, actually).  After I've collected information about the minefield, I then start reviewing each of the tiles where I have a number and placing flags on mines I know with  some right click action.  I also look for tiles where the number is satisfied and there are still unclicked tiles adjacent and engage the middle click option to quickly reveal adjacent tiles.  I repeat this process over and over again until I am out of moves.

When I am out of 100% probably moves, I then implement a stupid guessing technique where I choose a random tile that's not been clicked and click it.  I left click twice to get through the mines exploding quickly (when I'm wrong) and look to see if the play again option comes up.  If it does, I click play again and I keep trying.

Right now, this method is yielding about a 0.5% win rate.  Most people, I supect, play the game with less success than this tool.  The next iteration of this software will include a probabilistic guessing strategy (i.e., click a tile that has the least likely chance of being wrong instead of any tile at random).