Exemple #1
0
def playMinesweeper():

    os.system("clear")
    print("Welcome to Minesweeper, f****r.")

    toss = input("Enter your name: ")

    #out of bounds messages
    outOfBoundsMessages = [
        "Really?", "God you're dumb", "It's really not that hard.", "Wow.",
        "Oh. Okay. Yeah. Yeah that makes sense.    No."
    ]

    playing = True
    while playing:
        message = "Okay, 'Bitch', let's play."
        game = MineSweeper()
        while not game.gameOver:
            # os.system("clear")
            print(message)
            print("There are 99 total mines.")
            print(game.state)
            message = "You're still alive, somehow."
            coordinates = input("Enter coordinates: ")
            coordinates = [int(x) for x in coordinates.split(',')]
            # if isinstance(coordinates, tuple) and coordinates[0] > 0 and coordinates[0] <= game.dim1 and coordinates[1] >0 and coordinates[1] <= game.dim2:
            if coordinates[0] > 0 and coordinates[
                    0] <= game.dim1 and coordinates[1] > 0 and coordinates[
                        1] <= game.dim2:
                coordinates = (coordinates[0] - 1, coordinates[1] - 1)
                game.selectCell(coordinates)
            else:
                message = outOfBoundsMessages[np.random.randint(
                    0, len(outOfBoundsMessages), 1)[0]]
        if game.victory:
            os.system("clear")
            print(game.state)
            print(
                "I guess sometimes it's better to be lucky than good. Congratulations."
            )
        else:
            print("Game over idiot.")

        again = input("Play again? (y/n)")
        if again != "y":
            playing = False
            print("Yeah, this is probably not your game anyway.")
 def testMe(self, nGames):
     cellsRevealed = 0
     gamesWon = 0
     for i in range(nGames):
         if (i % 10) == 0:
             print("Playing game " + str(i + 1) + "...")
         # initiate game
         game = MineSweeper()
         # pick middle on first selection. better than corner.
         game.selectCell((int(self.dim1 / 2), int(self.dim2 / 2)))
         while not game.gameOver:
             # get data input from game state
             Xnow = self.getPredictorsFromGameState(game.state)
             X2now = np.array([np.where(Xnow[0] == 0, 1, 0)])
             # make probability predictions
             out = self.model.predict([np.array([Xnow]), np.array([X2now])])
             # choose best remaining cell
             orderedProbs = np.argsort(
                 out[0][0] + Xnow[0], axis=None
             )  # add Xnow[0] so that already selected cells aren't chosen
             selected = orderedProbs[0]
             selected1 = int(selected / self.dim2)
             selected2 = selected % self.dim2
             game.selectCell((selected1, selected2))
         cellsRevealed += self.totalCells - np.sum(np.isnan(game.state))
         if game.victory:
             gamesWon += 1
     meanCellsRevealed = float(cellsRevealed) / nGames
     propGamesWon = float(gamesWon) / nGames
     print("Proportion of games won, batch " + str(i) + ": " +
           str(propGamesWon))
     print("Mean cells revealed, batch " + str(i) + ": " +
           str(meanCellsRevealed))
 def watchMePlay(self):
     play = True
     while play:
         game = MineSweeper()
         os.system("clear")
         print("Beginning play")
         print("Game board:")
         print(game.state)
         #make first selection in the middle. better than corner.
         selected1 = int(self.dim1 / 2)
         selected2 = int(self.dim2 / 2)
         game.selectCell((selected1, selected2))
         time.sleep(0.1)
         os.system("clear")
         #now the rest
         while not game.gameOver:
             print("Last selection: (" + str(selected1 + 1) + "," +
                   str(selected2 + 1) + ")")
             if 'out' in locals():
                 print("Confidence: " + str(
                     np.round(100 *
                              (1 - np.amin(out[0][0] + Xnow[0])), 2)) + "%")
             print("Game board:")
             print(game.state)
             Xnow = self.getPredictorsFromGameState(game.state)
             X2now = np.array([np.where(Xnow[0] == 0, 1, 0)])
             # make probability predictions
             out = self.model.predict([np.array([Xnow]), np.array([X2now])])
             # choose best remaining cell
             orderedProbs = np.argsort(
                 out[0][0] + Xnow[0], axis=None
             )  # add Xnow[0] so that already selected cells aren't chosen
             selected = orderedProbs[0]
             selected1 = int(selected / self.dim2)
             selected2 = selected % self.dim2
             game.selectCell((selected1, selected2))
             time.sleep(0.1)
             os.system("clear")
         print("Last selection: (" + str(selected1 + 1) + "," +
               str(selected2 + 1) + ")")
         print("Confidence: " +
               str(np.round(100 *
                            (1 - np.amin(out[0][0] + Xnow[0])), 2)) + "%")
         print("Game board:")
         print(game.state)
         if game.victory:
             print("Victory!")
         else:
             print("Game Over")
         get = input("Watch me play again? (y/n): ")
         if get != "y":
             play = False
 def learnMineSweeper(self,
                      nSamples,
                      nBatches,
                      nEpochsPerBatch,
                      verbose=True):
     X = np.zeros(
         (nSamples, 11, self.dim1, self.dim2)
     )  # 11 channels: 1 for if has been revealed, 1 for is-on-board, 1 for each number
     X2 = np.zeros((nSamples, 1, self.dim1, self.dim2))
     y = np.zeros((nSamples, 1, self.dim1, self.dim2))
     for i in range(nBatches):
         cellsRevealed = 0
         gamesPlayed = 0
         gamesWon = 0
         samplesTaken = 0
         while samplesTaken < nSamples:
             # initiate game
             game = MineSweeper()
             #pick middle on first selection. better than corner.
             game.selectCell((int(self.dim1 / 2), int(self.dim2 / 2)))
             while not (game.gameOver or samplesTaken == nSamples):
                 # get data input from game state
                 Xnow = self.getPredictorsFromGameState(game.state)
                 X[samplesTaken] = Xnow
                 X2now = np.array([np.where(Xnow[0] == 0, 1, 0)])
                 X2[samplesTaken] = X2now
                 # make probability predictions
                 out = self.model.predict(
                     [np.array([Xnow]), np.array([X2now])])
                 # choose best remaining cell
                 orderedProbs = np.argsort(
                     out[0][0] + Xnow[0], axis=None
                 )  #add Xnow[0] so that already selected cells aren't chosen
                 selected = orderedProbs[0]
                 selected1 = int(selected / self.dim2)
                 selected2 = selected % self.dim2
                 game.selectCell((selected1, selected2))
                 # find truth
                 truth = out
                 truth[0, 0, selected1, selected2] = game.mines[selected1,
                                                                selected2]
                 y[samplesTaken] = truth[0]
                 samplesTaken += 1
             if game.gameOver:
                 gamesPlayed += 1
                 cellsRevealed += self.totalCells - np.sum(
                     np.isnan(game.state))
                 if game.victory:
                     gamesWon += 1
         if gamesPlayed > 0:
             meanCellsRevealed = float(cellsRevealed) / gamesPlayed
             propGamesWon = float(gamesWon) / gamesPlayed
         if verbose:
             print("Games played, batch " + str(i) + ": " +
                   str(gamesPlayed))
             print("Mean cells revealed, batch " + str(i) + ": " +
                   str(meanCellsRevealed))
             print("Proportion of games won, batch " + str(i) + ": " +
                   str(propGamesWon))
         #train
         self.model.fit([X, X2],
                        y,
                        batch_size=nSamples,
                        epochs=nEpochsPerBatch)
         #save it every 100
         if (i + 1) % 100 == 0:
             self.model.save("trainedModels/" + self.name + ".h5")
Exemple #5
0
from MineSweeper import MineSweeper


# gets player's input
def turn(minesweeper):
    print('insert coordinates. (IE. row,column)')
    user = input('>')
    ##self.cls()

    # get the coords then plot the section
    minesweeper.point = user.split(',')
    if int(minesweeper.point[0]) >= 0 and int(minesweeper.point[1]) < minesweeper.width + 1:
        minesweeper.calculateGameboard(minesweeper.coordsX, minesweeper.coordsY, minesweeper.height, minesweeper.width)
        drawBoardFinish(m, True)


if __name__ == '__main__':
    m = MineSweeper(9, 9)
    m.bombs(m.coordsX, m.coordsY, m.height, m.width)
    m.calculateGameboard(m.coordsX, m.coordsY, m.height, m.width)
    drawBoardFinish(m, True)

    while True:
        turn(m)
        if m.graph[int(m.point[0])][int(m.point[1])] == 9:
            drawBoardFinish(m, True)
            print('you hit a bomb ur dead')
            print('GAME OVER')
            break
    # needs a way to finish the game
 def setUp(self):
     self.minesweeper = MineSweeper(3, 3)
Exemple #7
0
            elif len(target[2]) != 0 and min(target[2]) < p_land:
                position = game.num_to_position(target[0][np.argmin(
                    target[2])])
                game.player.open(position[0], position[1])
            else:
                game.open_land()

    return game.player.clear


if __name__ == "__main__":
    """
    easy   950/1000
    normal 823/1000
    hard    42/100
    """
    n_win = 0
    n_game = 100
    difficulty = 0
    import time
    s = time.time()

    for n in range(n_game):
        player = MineSweeper(difficulty)
        n_win += main(player)
        print("{}: winning {}".format(n + 1, n_win))
        print("")

    print("winning rate: {:.3f} %".format(100 * float(n_win) / float(n_game)))
    print(time.time() - s)
    def learnMineSweeper(self, nSamples, nBatches, nEpochsPerBatch, verbose=True, nhwcFormat=True):
        X = np.zeros((nSamples, 11, self.dim1, self.dim2))  # 11 channels: 1 for if has been revealed, 1 for is-on-board, 1 for each number
        X2 = np.zeros((nSamples, 1, self.dim1, self.dim2))
        y = np.zeros((nSamples, 1, self.dim1, self.dim2))

        cellsRevealedTimeSeries = open("log/%s-%d" % (self.name, time.time()), "w")
        cellsRevealedTimeSeriesAvg = open("log/%s-batch-mean-%d" % (self.name, time.time()), "w")


        for i in range(nBatches):
            # pdb.set_trace()
            totalCellsRevealed = 0
            gamesPlayed = 0
            gamesWon = 0
            samplesTaken = 0
            while samplesTaken < nSamples:
                # initiate game
                game = MineSweeper()
                #print("Starting new game")
                # pdb.set_trace()
                #pick middle on first selection. better than corner.
                game.selectCell((int(self.dim1 / 2), int(self.dim2 / 2)))
                while not (game.gameOver or samplesTaken == nSamples):
                    # get data input from game state
                    Xnow = self.getPredictorsFromGameState(game.state)
                    # pdb.set_trace()
                    X[samplesTaken] = Xnow
                    X2now = np.array([np.where(Xnow[0] == 0, 1, 0)])
                    X2[samplesTaken] = X2now

                    # make probability predictions
                    if nhwcFormat:
                        out = self.model.predict([np.array([Xnow.transpose((1, 2, 0))]), np.array([X2now.transpose((1, 2, 0))])])
                    else:
                        out = self.model.predict([np.array([Xnow]), np.array([X2now])])

                    # choose best remaining cell
                    # pdb.set_trace()
                    orderedProbs = np.argsort((out[0, :, :, 0] if nhwcFormat else out[0][0]) + Xnow[0], axis=None) #add Xnow0 so that already selected cells aren't chosen
                    selected = orderedProbs[0]
                    selected1 = int(selected / self.dim2)
                    selected2 = selected % self.dim2
                    # pdb.set_trace()
                    game.selectCell((selected1, selected2))
                    # find truth
                    truth = out
                    if nhwcFormat:
                        truth[0, selected1, selected2, 0] = game.mines[selected1, selected2]
                    else:
                        truth[0, 0, selected1, selected2] = game.mines[selected1, selected2]
                    y[samplesTaken] = truth[0].transpose([2, 0, 1]) if nhwcFormat else truth[0]
                    samplesTaken += 1

                    #print("At sample %d of %d" % (samplesTaken, nSamples))
                    #print("Cells revealed in current game: %d" % (self.totalCells - np.sum(np.isnan(game.state))))

                if game.gameOver:
                    gamesPlayed += 1
                    cellsRevealed = self.totalCells - np.sum(np.isnan(game.state))
                    #cellsRevealedTimeSeries.write(str(cellsRevealed))
                    #cellsRevealedTimeSeries.write('\n')
                    totalCellsRevealed += cellsRevealed
                    if game.victory:
                        gamesWon += 1
                    #print("Cells revealed in current game: %d" % cellsRevealed)
                    #print("Total cells trained on (revealed): %d" % totalCellsRevealed)
                    #print("Samples taken: %d" % samplesTaken)
                    #print("Games won: %d" % gamesWon)
                    #pdb.set_trace()

            #cellsRevealedTimeSeries.flush()
            meanCellsRevealed = -1
            propGamesWon = -1
            if gamesPlayed > 0:
                meanCellsRevealed = float(totalCellsRevealed) / gamesPlayed
                propGamesWon = float(gamesWon) / gamesPlayed
                cellsRevealedTimeSeriesAvg.write(str(meanCellsRevealed))
                cellsRevealedTimeSeriesAvg.write("\n")
                cellsRevealedTimeSeriesAvg.flush()
            if verbose:
                print("Games played, batch " + str(i) + ": " + str(gamesPlayed))
                print("Mean cells revealed, batch " + str(i) + ": " + str(meanCellsRevealed))
                print("Proportion of games won, batch " + str(i) + ": " + str(propGamesWon))
            #train
            self.model.fit([X.transpose((0, 2, 3, 1)), X2.transpose((0, 2, 3, 1))], y.transpose((0, 2, 3, 1)), batch_size=nSamples, epochs=nEpochsPerBatch)
            #save it every 2
            if (i+1) % 2 == 0:
                self.model.save("trainedModels/" + self.name + ".h5")
                #pdb.set_trace()
                print("Saved to %s" % (self.name + ".h5"))
 def test_oneline(self):
     input = '1 4\n....'
     expect = '0000'
     ms = MineSweeper()
     out = ms.resolve(input)
     self.assertEqual(expect, out)
 def test_threeline3mine(self):
     input = '3 5\n*....\n.*...\n..*..'
     expect = '*2100\n2*210\n12*10'
     ms = MineSweeper()
     out = ms.resolve(input)
     self.assertEqual(expect, out)
 def test_twoline1mine(self):
     input = '2 5\n*....\n.....'
     expect = '*1000\n11000'
     ms = MineSweeper()
     out = ms.resolve(input)
     self.assertEqual(expect, out)
Exemple #12
0
from MineSweeper import MineSweeper

a = MineSweeper()

print(a)
a.step(0, 0)
print(a)