Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from minesweeper import *
- def exampleSolveGame(grid):
- """
- This is an intentionally crappy AI to solve a game on Minesweeper. It
- may not play well, but it does illustrate the basics of how to code an AI.
- It'll be easiest if you write your own AI in a function like this one, but
- hopefully it'll be better.
- Here's the basic form your function should take. The input parameter
- `grid' will be a Minefield object (see minesweeper.py for more info):
- def myAwesomeSolveGame(grid):
- while not grid.isSolved():
- <put awesome code here to calculate which row and column coordinates to choose here>
- grid.guess(row, column)
- """
- while not grid.isSolved():
- # This dictionary will map the coordinates of a square to
- # an estimate of the probability that the square has a mine
- # on it. We start with a baseline probability based on
- # how many mines there in total.
- baselineProbability = grid.nMines() / float(grid.nHidden())
- hiddenSquareProbabilities = dict(((r,c), baselineProbability) for r,c in grid.iterHidden())
- # For each visible square, check if it has a nonzero number of hidden
- # squares surrounding it. Use the number of mines surrounding the square
- # as well as the number of curenly hidden squares around to update
- # the estimate of the probability that the square has a mine on it.
- for r,c in grid.iterVisible():
- if grid.nHiddenAround(r,c) > 0:
- mineProb = grid.nMinesAround(r,c) / float(grid.nHiddenAround(r,c))
- for r2,c2 in grid.iterNeighbors(r,c):
- if (r2,c2) in hiddenSquareProbabilities:
- hiddenSquareProbabilities[(r2,c2)] = max(hiddenSquareProbabilities[(r2,c2)], mineProb)
- # Pick the square with the lowest estimated probability.
- availableSquares = [(prob,(r,c)) for (r,c),prob in hiddenSquareProbabilities.iteritems()]
- availableSquares.sort()
- row, column = availableSquares[0][1]
- grid.guess(row, column)
- def main():
- # Set this to True if you want to play a game of Minesweeper with a
- # crappy text interface. Set this to False if you want to test
- # how good the example AI is (spoiler: not very).
- doYouWantToPlayAGame = False
- if doYouWantToPlayAGame:
- playGame(9, 9, 10)
- else:
- testSolver(exampleSolveGame)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement