Exemple #1
0
    def select_difficulty(self):
        """Player can choose game's difficulty"""
        while True:
            for event in pygame.event.get():
                escape = event.type == KEYDOWN and event.key == K_ESCAPE
                if event.type == QUIT or escape:
                    exit()
                elif event.type == KEYDOWN:
                    if event.key == K_KP1 or event.key == K_1:
                        self.field = minesweeper.Minesweeper(BEGINNER)
                        self.difficulty = BEGINNER
                        return
                    if event.key == K_KP2 or event.key == K_2:
                        self.field = minesweeper.Minesweeper(INTERMEDIATE)
                        self.difficulty = INTERMEDIATE
                        return
                    if event.key == K_KP3 or event.key == K_3:
                        self.field = minesweeper.Minesweeper(ADVANCED)
                        self.difficulty = ADVANCED
                        return

            self.screen.blit(DIFF_BACKGROUND, (0, 0))
            self.screen.blit(FONT_TITLE.render(TITLE, True, WHITE), (200, 15))
            self.screen.blit(FONT.render(CHOOSE, True, WHITE), (300, 245))
            self.screen.blit(FONT.render(PRESS_1, True, WHITE), (300, 280))
            self.screen.blit(FONT.render(PRESS_2, True, WHITE), (300, 315))
            self.screen.blit(FONT.render(PRESS_3, True, WHITE), (300, 350))
            pygame.display.update()
def play_game():
    board = minesweeper.Minesweeper(9, 10)

    while True:
        clear()
        print("\nWelcome to minesweeper.\n")
        board.display_board()
        guess = input("\nMake an action: ")
        if not re.match(r'^[GMU][A-I][1-9]', guess):
            if guess == "exit":
                break
            print_help()
            continue
        if guess[0] == 'G':
            result = board.guess_square(int(guess[2]) - 1, ord(guess[1]) - 65)
            if result == "mine":
                clear()
                print("\nWelcome to minesweeper.\n")
                board.display_board()
                print("\nYOU LOSE\n")
                play_again = input("Play again? (Y/N)")
                if play_again == "Y":
                    board = minesweeper.Minesweeper(9, 10)
                    continue
                break
            if result == "marked":
                print(
                    "\nYou cannot guess a square that you have marked as a mine.\n"
                )
                _ = input("Hit any key to continue.")
                continue
            if result == "win":
                clear()
                print("\nWelcome to minesweeper.\n")
                board.display_board()
                print("\nYOU WIN\n")
                play_again = input("Play again? (Y/N)")
                if play_again == "Y":
                    board = minesweeper.Minesweeper(9, 10)
                    continue
                break
        if guess[0] == 'M':
            board.mark_square(int(guess[2]) - 1, ord(guess[1]) - 65)
            clear()
            board.display_board()
        if guess[0] == 'U':
            board.unmark_square(int(guess[2]) - 1, ord(guess[1]) - 65)
            clear()
            board.display_board()
Exemple #3
0
    def test_flag(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]
        A.flag((3, 3))

        self.assertTrue((3, 3) in A.flagged)
Exemple #4
0
 def __init__(self, level):
     self.level = level
     pg.init()
     self.height, self.width = c.BOARD_SIZE[self.level]
     self.window = pg.display.set_mode((self.width, self.height))
     pg.display.set_caption(c.TITLE)
     icon = pg.image.load(resource_path('icon.png'))
     pg.display.set_icon(icon)
     pg.font.init()
     self.fonts = {
         'grid_font': pg.font.Font(resource_path('FreeSansBold.ttf'), 20),
         'panel_font': pg.font.SysFont("lucidaconsole", 30),
         'menu_font': pg.font.SysFont("dejavuserif", 10),
         'large_menu_font': pg.font.SysFont("dejavuserif", 20)
     }
     self.ms = minesweeper.Minesweeper(level=self.level)
     self.flag = pg.image.load(resource_path('flag.bmp'))
     self.tp_btn_pos = int((self.width - c.TILESIZE) / 2)
     self.tp_bt_col = c.YELLOW
     self.timer_pos = int((self.width - 5 * c.TILESIZE) / 4)
     self.mine_pos = int(3 * (self.width - c.TILESIZE) / 4)
     self.scores = Scores(self.height, self.width, self.fonts,
                          "HIGH SCORES")
     self.diff_choice = Difficulties(self.height, self.width, self.fonts,
                                     "SET DIFFICULTY", self.level)
     self.down = False
     self.show_scores = False
     self.show_diff_choice = False
     self.reset = False
     self.menu = False
     self.on = True
Exemple #5
0
    def test_get_neighbours(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]
        expected_neighbours = set([(2, 2), (2, 3), (2, 4), (3, 2),
                                   (3, 4), (4, 2), (4, 3), (4, 4)])

        self.assertEqual(set(A.neighbours[(3, 3)]), expected_neighbours)
Exemple #6
0
    def test_smart_check(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]
        A.open((1, 4))
        A.flag((0, 4))
        A.smart_check((1, 4))

        self.assertTrue((1, 3) in A.opened)
Exemple #7
0
    def test_smart_open(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]

        self.assertFalse(A.smart_open((4, 2)))

        A.smart_open((3, 3))
        self.assertTrue((3, 3) in A.opened)
Exemple #8
0
    def test_check_for_win(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]
        for (x, y) in A.board:
            if (x, y) not in A.mines:
                A.open((x, y))

        self.assertTrue(A.check_for_win())
Exemple #9
0
 def test_random_board(self):
     for level in [1, 2, 3]:
         with self.subTest():
             self.game = MS.Minesweeper(level)
             count = 0
             for x in self.game.board:
                 for y in x:
                     if y == 9:
                         count += 1
             self.assertEqual(count, self.game.mines)
Exemple #10
0
    def test_smart_flag(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]
        A.flag((2, 0))

        self.assertFalse(A.smart_flag((2, 0)))

        A.smart_flag((0, 4))
        self.assertTrue((0, 4) in A.flagged)
Exemple #11
0
    def test_generate_board_negative_mines_errors(self):
        """Test the board generator fails when <0 mines supplied."""
        # arrange
        game = minesweeper.Minesweeper()
        width = 10
        height = 12
        mines = -1

        # act and expect error
        with self.assertRaises(ValueError):
            game.generate_board(width, height, mines)
Exemple #12
0
    def test_open(self):
        A = minesweeper.Minesweeper(B)
        A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                   (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]

        self.assertTrue(A.open((3, 3)))
        self.assertFalse(A.open((3, 3)))

        mine = A.mines[5]

        self.assertFalse(A.open(mine))

        self.assertTrue(A.open((3, 5)))
Exemple #13
0
 def setUp(self):
     self.game = MS.Minesweeper(1)
     self.game.revealed.clear()
     self.game.flagged.clear()
     self.game.level = 1
     self.game.size = 5
     self.game.mines = 4
     self.game.board = []
     mined = [[0, 0, 9, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 9],
              [0, 0, 0, 0, 0], [0, 9, 0, 0, 9]]
     self.game.board.extend(mined)
     self.game.put_numbers()
     self.moves = ['2 2', '2 4', '0 4 f']
Exemple #14
0
def main():
    # Inicjalizacja biblioteki Tkinter
    root = tk.Tk()
    # Zablokowanie możliwości zmiany rozmiaru okna
    root.resizable(width=False, height=False)
    # Tworzenie obiektu klasy GameWindow
    # Do konstruktora przekazywany jest główny widget
    gw = game_window.GameWindow(master=root)
    # Tworzenie obiektu klasy Board
    game_board = board.Board()
    # Tworzenie obiektu klasu Minesweeper
    # Do konstruktora przekazywany jest obiekt klasy GameWindow oraz obiekt klasy Board
    ms = minesweeper.Minesweeper(game_board, gw)
    # Rozpoczęcie gry
    ms.init_game()
    root.mainloop()
Exemple #15
0
    def test_generate_board_no_mines(self):
        """Test the board generates successfully with no mines."""
        # arrange
        game = minesweeper.Minesweeper()
        width = 10
        height = 12

        # act
        game.generate_board(width, height, 0)

        # assert
        self.assertEqual(width, len(game.board[0]), 'Board width incorrect.')
        self.assertEqual(height, len(game.board), 'Board height incorrect.')

        for row in range(height):
            self.assertFalse(any([s.is_mine for s in game.board[row]]),
                             ("Mine found when board was generated " +
                              "with mineCount = 0."))
Exemple #16
0
    def test_generate_board_height_equal_to_width(self):
        """Test the board generator at height == width."""
        # arrange
        game = minesweeper.Minesweeper()
        width = 20
        height = 20
        mines = int(width * height / 2)

        # act
        game.generate_board(width, height, mines)

        # assert
        self.assertEqual(width, len(game.board[0]), 'Board width incorrect.')
        self.assertEqual(height, len(game.board), 'Board height incorrect.')

        minesFound = (sum(game.board[row][col].is_mine for col in range(width)
                      for row in range(height)))
        self.assertEqual(mines, minesFound,
                         'Wrong number of mines found.')
Exemple #17
0
    def test_generate_board_max_mines(self):
        """Test the board generator with the max number of mines."""
        # arrange
        game = minesweeper.Minesweeper()
        width = 10
        height = 12

        # act
        game.generate_board(width, height, width * height - 1)

        # assert
        self.assertEqual(width, len(game.board[0]), 'Board width incorrect.')
        self.assertEqual(height, len(game.board), 'Board height incorrect.')

        minesFound = (sum(1 for row in range(height)
                      for col in range(width) if game.board[row][col].is_mine))

        self.assertEqual(width * height - 1, minesFound,
                         'Wrong number of mines found.')
Exemple #18
0
    def test_generate_board_width_greater_than_height(self):
        """Test the board generator succeeds with width > height."""
        # arrange
        game = minesweeper.Minesweeper()
        width = 19
        height = 10
        mines = int(width * height / 2)

        # act
        game.generate_board(width, height, mines)

        # assert
        self.assertEqual(width, len(game.board[0]), 'Board width incorrect.')
        self.assertEqual(height, len(game.board), 'Board height incorrect.')

        minesFound = (sum(game.board[row][col].is_mine for col in range(width)
                      for row in range(height)))

        self.assertEqual(mines, minesFound,
                         'Wrong number of mines found.')
Exemple #19
0
def main():
    _print_welcome()
    sel = _get_selection()

    if sel == "q":
        sys.exit(1)
    elif sel == "s":
        _print_scores()
    elif sel == "p":
        player = _get_player()
        size_x, size_y = _get_grid_size()
        mines = _get_mines(size_x, size_y)
        game = ms.Minesweeper(grid.Grid(size_x, size_y, mines))
        game.start_timer()
        lost, won = game.get_status()

        while not lost and not won:
            _clear()
            game.print_grid()
            x, y = _get_coordinates(size_x, size_y)
            game.guess(x, y)
            lost, won = game.get_status()

        game.game_over()
        game.stop_timer()
        _clear()
        game.print_grid()

        gametime = game.get_time()
        gamedate = game.get_date()
        gamescore = game.get_score()

        if lost:
            print("You lost!")
        else:
            print("Congratulations {}, you won!".format(player))
            print("Your score is {:.2f} points.".format(gamescore))
            print("The game lasted {:.2f} seconds.".format(gametime))
            print("The date is {}".format(_format_date(gamedate, DATE_FORMAT)))
            print("Saving score to file.")
            _write_scores(SCOREFILE, [[player, gamescore, gamedate]])
Exemple #20
0
    def __init__(self, size):
        super().__init__()
        self.size = size
        self.grid = q.QGridLayout()
        self.buttons = [[q.QPushButton(" ") for i in range(size)] for j in range(size)]
        self.row = [q.QHBoxLayout() for i in range(size)]
        self.mapper = QSignalMapper()
        self.msw = minesweeper.Minesweeper(size)
        self.mswlog = minesweeperlog.MinesweeperLog()
        for i in range(size):
            for j in range(size):
                # self.buttons[i][j].setEnabled(False)
                self.buttons[i][j].setMaximumSize(30, 30)
                self.buttons[i][j].setMinimumSize(30, 30)
                self.buttons[i][j].setStyleSheet('background-color: blue; color: black')
                self.grid.addWidget(self.buttons[i][j], i, j)
                self.mapper.setMapping(self.buttons[i][j], i * size + j)
                QObject.connect(self.buttons[i][j], SIGNAL('clicked()'), self.mapper, SLOT('map()'))

        QObject.connect(self.mapper, SIGNAL('mapped(int)'), self, SLOT('on_click(int)'))
        self.setLayout(self.grid)
        self.setMaximumSize(35 * size, 35 * size)
Exemple #21
0
def main():
    game = msw.Minesweeper(10, 10, 20)
    status = msw.MOVE
    cmda = re.compile(r'(?P<cmd>[dfurDFUR]) ?(?P<row>\d+), ?(?P<col>\d+)')
    cmds = re.compile(r'(?P<cmd>[qhQH])')

    while msw.status_ok(status):
        game.print()
        print(msw.get_message(status))
        cmd_str = input("> ")
        match = cmda.match(cmd_str)
        if not match:
            match = cmds.match(cmd_str)
        if not match:
            continue

        if match.group('cmd').upper() == 'D':
            status = game.dig(int(match.group('row')), int(match.group('col')))
        elif match.group('cmd').upper() == 'R':
            status = game.reveal(int(match.group('row')),
                                 int(match.group('col')))
        elif match.group('cmd').upper() == 'U':
            status = game.unflag(int(match.group('row')),
                                 int(match.group('col')))
        elif match.group('cmd').upper() == 'F':
            status = game.flag(int(match.group('row')),
                               int(match.group('col')))
        elif match.group('cmd').upper() == 'Q':
            return
        elif match.group('cmd').upper() == 'H':
            help()

        if game.won():
            status = msw.WON
            break

    print(msw.get_message(status))
Exemple #22
0
import minesweeper
import solver
import time

m = minesweeper.Minesweeper(16, 30, 99)
s = solver.Solver()
m.Display()

while True:
    move = raw_input("Enter a move as (column, row): ")
    if move == "auto":
        while True:
            #(move, bombs, covered) = s.GetNextMove(b)
            #result = m.Probe(move[0], move[1])
            [column, row] = s.GetNextMove(m.board)
            result = m.Probe(column, row)
            if result == 1:
                print "\r\n\r\n-----------\r\n You win!\r\n-----------\r\n"
                quit()
            elif result == -1:
                print "\r\n\r\n---------------\r\n You lose...\r\n---------------\r\n"
                quit()
    else:
        splitmove = move.split(", ")
        column = int(splitmove[0][1:])
        row = int(splitmove[1][:-1])
        m.Probe(column, row)
Exemple #23
0
 def test_set_mines(self):
     A = minesweeper.Minesweeper(B)
     A.mines = [(4, 2), (0, 4), (2, 0), (5, 4), (4, 6),
                (2, 1), (7, 2), (7, 8), (1, 1), (1, 7)]
     self.assertEqual(len(A.mines), 10)
Exemple #24
0
def getprivateboard():
    global ms
    if ms is None:
        ms = minesweeper.Minesweeper()
        ms.setup()
    return ms.get_private_board()
Exemple #25
0
def getpublicboard():
    global ms
    if ms is None:
        ms = minesweeper.Minesweeper()
        ms.setup()
    return ms.get_public_board()
Exemple #26
0
def hello():
    global ms
    ms = minesweeper.Minesweeper()
    ms.setup()
    return ms.get_public_board()
Exemple #27
0
    def __init__(self, bot=False):
        pygame.init()

        self.win_height = 275
        self.win_width = 255
        self.bot = bot
        self.window = pygame.display.set_mode(
            (self.win_width, self.win_height))
        self.window.fill(WHITE)
        pygame.display.flip()

        self.clock = Clock()
        while True:
            mouse = pygame.mouse.get_pos()
            if 62 < mouse[1] < 62 + 50 and 77 < mouse[0] < 77 + 100:
                pygame.draw.rect(self.window, LGREY,
                                 (77, 62, 100, 50))  #left,top,w,h
            else:
                pygame.draw.rect(self.window, (128, 128, 128),
                                 (77, 62, 100, 50))
            if 117 < mouse[1] < 117 + 50 and 77 < mouse[0] < 77 + 100:
                pygame.draw.rect(self.window, LGREY, (77, 117, 100, 50))
            else:
                pygame.draw.rect(self.window, (128, 128, 128),
                                 (77, 117, 100, 50))
            if 172 < mouse[1] < 172 + 50 and 77 < mouse[0] < 77 + 100:
                pygame.draw.rect(self.window, LGREY, (77, 172, 100, 50))
            else:
                pygame.draw.rect(self.window, (128, 128, 128),
                                 (77, 172, 100, 50))

            font = pygame.font.SysFont("Arial", 40)
            text = font.render("EASY", True, (0, 0, 0))
            self.window.blit(text, ((55 + (50 / 2)), (15 + (100 / 2))))

            font = pygame.font.SysFont("Arial", 27)
            text = font.render("NORMAL", True, (0, 0, 0))
            self.window.blit(text, ((55 + (50 / 2)), (77 + (100 / 2))))

            font = pygame.font.SysFont("Arial", 40)
            text = font.render("HARD", True, (0, 0, 0))
            self.window.blit(text, ((55 + (50 / 2)), (125 + (100 / 2))))

            font = pygame.font.SysFont("Arial", 40)
            text = font.render("LEVELS", True, (0, 0, 0))
            self.window.blit(text, ((255 / 4), 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        if 62 < mouse[1] < 62 + 50 and 77 < mouse[0] < 77 + 100:
                            game = minesweeper.Minesweeper(10, 10, 10)
                            if self.bot:
                                bot = SolverBot(10, 10, game)
                                gameloop = minesweeper.MSGameLoop(
                                    game, 10, 10, bot)
                            else:
                                gameloop = minesweeper.MSGameLoop(game, 10, 10)
                            gameloop.start(10, 10)
                        elif 117 < mouse[1] < 117 + 50 and 77 < mouse[
                                0] < 77 + 100:
                            game = minesweeper.Minesweeper(16, 16, 40)
                            if self.bot:
                                bot = SolverBot(16, 16, game)
                                gameloop = minesweeper.MSGameLoop(
                                    game, 16, 16, bot)
                            else:
                                gameloop = minesweeper.MSGameLoop(game, 16, 16)
                            gameloop.start(16, 16)
                        elif 172 < mouse[1] < 172 + 50 and 77 < mouse[
                                0] < 77 + 100:
                            game = minesweeper.Minesweeper(30, 16, 99)
                            if self.bot:
                                bot = SolverBot(30, 16, game)
                                gameloop = minesweeper.MSGameLoop(
                                    game, 30, 16, bot)
                            else:
                                gameloop = minesweeper.MSGameLoop(game, 30, 16)
                            gameloop.start(30, 16)

            pygame.display.flip()
            self.clock.tick(60)
Exemple #28
0
    def __init__(self, w, h, mines, play_time, win, bot=None):
        pygame.init()

        self.win_height = 275
        self.win_width = 255
        self.window = pygame.display.set_mode(
            (self.win_width, self.win_height))
        self.window.fill(WHITE)
        self.bot = bot
        self.win = win
        self.clock = Clock()
        self.time = play_time

        while True:
            mouse = pygame.mouse.get_pos()
            if 62 < mouse[1] < 62 + 50 and 77 < mouse[0] < 77 + 100:
                pygame.draw.rect(self.window, LGREY,
                                 (77, 62, 100, 50))  #left,top,w,h
            else:
                pygame.draw.rect(self.window, (128, 128, 128),
                                 (77, 62, 100, 50))
            if 117 < mouse[1] < 117 + 50 and 77 < mouse[0] < 77 + 100:
                pygame.draw.rect(self.window, LGREY, (77, 117, 100, 50))
            else:
                pygame.draw.rect(self.window, (128, 128, 128),
                                 (77, 117, 100, 50))
            if 172 < mouse[1] < 172 + 50 and 77 < mouse[0] < 77 + 100:
                pygame.draw.rect(self.window, LGREY, (77, 172, 100, 50))
            else:
                pygame.draw.rect(self.window, (128, 128, 128),
                                 (77, 172, 100, 50))

            font = pygame.font.SysFont("Arial", 40)
            text = font.render("RETRY", True, (0, 0, 0))
            self.window.blit(text, ((55 + (50 / 2)), (15 + (100 / 2))))

            font = pygame.font.SysFont("Arial", 27)
            text = font.render("CHANGE LEVEL", True, (0, 0, 0))
            self.window.blit(text, ((55 + (50 / 2)), (77 + (100 / 2))))

            font = pygame.font.SysFont("Arial", 40)
            text = font.render("BACK", True, (0, 0, 0))
            self.window.blit(text, ((55 + (50 / 2)), (125 + (100 / 2))))

            font = pygame.font.SysFont("Arial", 40)
            if self.win:
                text = font.render("YOU WIN" + self.time, True, (0, 0, 0))
            else:
                text = font.render("YOU LOSE" + self.time, True, (0, 0, 0))
            self.window.blit(text, (0, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        if 62 < mouse[1] < 62 + 50 and 77 < mouse[0] < 77 + 100:
                            game = minesweeper.Minesweeper(w, h, mines)
                            if self.bot is not None:
                                bot = SolverBot(w, h, game)
                                gameloop = minesweeper.MSGameLoop(
                                    game, w, h, bot)
                            else:
                                gameloop = minesweeper.MSGameLoop(game, w, h)
                            gameloop.start(w, h)
                        elif 117 < mouse[1] < 117 + 50 and 77 < mouse[
                                0] < 77 + 100:
                            if self.bot is not None:
                                Levels(True)
                            else:
                                Levels()
                        elif 172 < mouse[1] < 172 + 50 and 77 < mouse[
                                0] < 77 + 100:
                            StartWindow()

            pygame.display.flip()
            self.clock.tick(60)
Exemple #29
0
import minesweeper as ms

msgame = ms.Minesweeper()
msgame.print()

# Print the locations of all mines
print(msgame.mines)