def __init__(self, MainWindow): Ui_MainWindow.__init__(self) self.game = Minesweeper() self.timer = QtCore.QTimer(MainWindow) self.mouseTimer = QtCore.QTimer(MainWindow) self.mineFlagIcon = QtGui.QPixmap('flag.png') self.smileIcon = QtGui.QIcon(QtGui.QPixmap('smile.png')) self.winIcon = QtGui.QIcon(QtGui.QPixmap('win.png')) self.mineIcon = QtGui.QIcon(QtGui.QPixmap('mine.png')) self.openIcon = QtGui.QIcon(QtGui.QPixmap('open.png')) self.smiles = { 'smile': self.smileIcon, 'open': self.openIcon, 'mine': self.mineIcon, 'win': self.winIcon } self.currentSmile = 'smile' self.level = 0.13 self.size = (0, 0) self.minesText = str(int(self.level * 100)) + "%" self.timeText = '-- : --' self.setupUi(MainWindow) self.addAllConnections() self.updateWindow()
def __init__(self, difficulty, type_game): if (difficulty == 'easy'): dif = 1 elif (difficulty == 'intermediate'): dif = 2 elif (difficulty == 'expert'): dif = 3 self.game = Minesweeper(dif) print("Matrix: ", self.game.x, "x", self.game.y) #layout layout = [[sg.Text("Difficulty: " + difficulty)]] matrix_game = [] line = [] string_but = 1 for i in range(self.game.x): for j in range(self.game.y): line += [ sg.Button("", key=str(string_but), size=(3, 0), pad=(0, 0)) ] string_but += 1 matrix_game += [line] line = [] layout += matrix_game if (type_game == "multi"): layout += [[sg.Button("Update", key="upd")]] #window self.window = sg.Window("Minesweeper - Game").layout(layout)
class MyClient(discord.Client): async def on_ready(self): print('logged in as') print(self.user.name) print(self.user.id) print('-----------') self.ms = Minesweeper() async def on_message(self, message): if message.author.id == self.user.id: return # ..startgame 10 10 15 5d if message.content.startswith('..startgame'): self.ms.startGame(' '.join(message.content.split()[1:])) self.ms.clear(self.ms.firstMove) print(self.ms.nicePrint(self.ms.numbersGrid)) await message.channel.send(self.ms.showGrid()) if message.content.startswith('..break'): await message.channel.send( self.ms.clear(message.content.split()[1])) if message.content.startswith('..flag'): await message.channel.send(self.ms.flag(message.content.split()[1]) ) if message.content.startswith('..reset'): self.ms.reset() await message.channel.send('ok')
def init_game(self, width=None, height=None, mine_count=None): if not width or not height or not mine_count: if self.game: width = self.game.width height = self.game.height mine_count = self.game.mine_count else: width = width or 10 height = height or 10 mine_count = mine_count or 10 if self.canvas: self.canvas.grid_forget() self.canvas = None self.game = Minesweeper(width, height, mine_count) self.header['text'] = 'Minesweeper' self.score['text'] = self.game.mine_count canvas_width = self.CELL_WIDTH * self.game.width canvas_height = self.CELL_HEIGHT * self.game.height self.canvas = Canvas(self.root, width=canvas_width + self.PADDING, height=canvas_height + self.PADDING) self.canvas.grid(row=1, columnspan=2, padx=self.PADDING, pady=self.PADDING) self.draw_canvas()
def testCreateFieldRandomValue(self): F1 = Minesweeper() F1.createFeild(4, 4) expect = "+" result = F1.field[2][2] self.assertEqual( expect, result, "a field didn't created well,all field Value should be +")
def testCreateFieldValueTopLeft(self): F1 = Minesweeper() F1.createFeild(4, 4) expect = "+" result = F1.field[0][0] self.assertEqual( expect, result, "a field didn't created well, Value at Top Left should be +")
def testCreateFieldValueBottomRight(self): F1 = Minesweeper() F1.createFeild(4, 4) expect = "+" result = F1.field[3][3] self.assertEqual( expect, result, "a field didn't created well, Value at Bottom Left should be +")
class MinesweeperApp(wx.App): def __init__(self): super().__init__() frame = wx.Frame(None, title="Minesweeper", pos=(30, 30), size=(800, 600)) gameWidth = 10 gameHeight = 10 numMines = 15 self.resetButtonId = 100 self.settingsMenuId = 200 # Menu bar definitions menuBar = wx.MenuBar() menu = wx.Menu() resetGame = wx.MenuItem(menu, self.resetButtonId, "Reset") menu.Append(resetGame) openOptions = wx.MenuItem(menu, self.settingsMenuId, "Options") menu.Append(openOptions) menuBar.Append(menu, "Game") frame.SetMenuBar(menuBar) frame.Bind(wx.EVT_MENU, self.menuHandler) # Start of program body definitions verticalContainer = wx.BoxSizer(wx.VERTICAL) self.minesweeper = Minesweeper(gameWidth, gameHeight, numMines) gameInfo = GameInfoPanel(frame, self.minesweeper) gameInfo.updateLabel() # Make sure the label is updated when the game starts verticalContainer.Add(gameInfo, proportion=0, flag=wx.EXPAND) mineField = MinefieldPanel(frame, self.minesweeper) verticalContainer.Add(mineField, proportion=1, flag=wx.EXPAND) frame.SetSizer(verticalContainer) # Make sure application actually closes when user exits self.Bind(wx.EVT_CLOSE, self.OnExit) frame.Show() def menuHandler(self, event): if event.GetId() == self.resetButtonId: self.minesweeper.reset() elif event.GetId() == self.settingsMenuId: SettingsDialog()
def __init__(self, size, mines, reward_profile, alpha=0.05, gamma=0.9, epsilon=0.1): self.alpha = alpha self.gamma = gamma self.epsilon = epsilon self.env = Minesweeper(size, mines, reward_profile) self.q_table = np.zeros((self.env.numStates, self.env.numMoves))
class TestMinesweeper(unittest.TestCase): def createMatrix(self): self.minesweeper.createField(3, 4) def insertLayMine(self, row, col): self.minesweeper.layMine(row, col) def playTurn(self, row, col): self.minesweeper.play(row, col) def setUp(self): self.minesweeper = Minesweeper() self.createMatrix() def test_first_status(self): self.minesweeper.gameStatus = GameStatus.Playing def test_MatricesEqualDefault(self): self.assertEqual(self.minesweeper.matrix, self.minesweeper.board) def test_equal_matrix(self): self.playTurn(0, 2) self.assertEqual(self.minesweeper.matrix, self.minesweeper.board) def test_createField(self): self.assertEqual(self.minesweeper.rows, 3) self.assertEqual(self.minesweeper.columns, 4) def test_Inserting_a_bomb(self): self.insertLayMine(0, 0) self.assertEqual(self.minesweeper.board[0][0], '*') def test_winCheck(self): self.insertLayMine(0, 0) self.playTurn(0, 2) self.assertEqual(self.minesweeper.status(), "WIN") def test_Failed(self): self.insertLayMine(0, 0) self.playTurn(0, 0) self.assertEqual(self.minesweeper.status(), "LOST") def test_mines(self): self.insertLayMine(0, 0) self.insertLayMine(0, 2) self.assertEqual(self.minesweeper.count_mines(0, 1), 2) def test_domainCheck(self): self.insertLayMine(0, 0) self.assertEqual(self.minesweeper.domainCheck(0, 0), True) self.assertEqual(self.minesweeper.domainCheck(2, 2), False)
def main(): print("Welcome to Minesweeper") width = 10 height = 10 mine_count = getLevel() newGame = Minesweeper(width,height,mine_count) gameOver = False while not gameOver: os.system('clear') print("Bombs:",newGame.mine_count,"\t Flags:",newGame.getFlagCount()) print(newGame) row = input("Please enter the row (0 to {0})".format(width)) while not row.isdigit() or int(row) not in range(width): row = input("Please enter the row (0 to {0})".format(width)) col = input("Please enter the column (0 to {0})".format(height)) while not col.isdigit() or int(col) not in range(height): col = input("Please enter the column (0 to {0})".format(height)) row = int(row) col = int(col) flag = input("Do you want to flag this spot? y/n") if flag.lower() == 'y': newGame.setFlag(row,col) else: gameOver = newGame.uncover(row, col) or newGame.isWon() newGame.reveal() print(newGame)
def testRevealCell1(self): F1 = Minesweeper() F1.createFeild(4, 4) F1.layMine(0, 0) expect = "1" F1.play(2, 2) result = F1.exposed[1][1] self.assertEqual(expect, result, "The cell should be reveal")
def __init__(self, grid_size, num_of_mines): self.size = grid_size self.num_of_mines = num_of_mines self.button_size = 1 self.game = Minesweeper(self.size, self.num_of_mines) self.root = tk.Tk() self.root.title("DG Mines") self.root.resizable(width=False, height=False) self.button = [] self.pos = [] self.colors = [ "#000000", "#0000ff", "#00aa00", "#ff00ff", "#ffff00", "#000000", "#000000", "#000000", "#000000" ] self.add_buttons()
def testWinSituationPrint(self): F1 = Minesweeper() F1.createFeild(2, 2) F1.layMine(0, 0) F1.layMine(1, 1) F1.play(0, 1) F1.play(1, 0) expected = "WIN\n" capturedOutput = io.StringIO() sys.stdout = capturedOutput F1.status() sys.stdout = sys.__stdout__ actual = capturedOutput.getvalue() self.assertEqual(expected, actual, "the game status should be Win")
def is_won(self): """End game if won.""" if Minesweeper.is_won(self): messagebox.showinfo("YES.", "YOU WIN! B)") self.generate_board(width=MinesweeperGUI.default_width, height=MinesweeperGUI.default_height, mine_count=99)
def leftClick(): global minefield x = int(request.args.get('x')) y = int(request.args.get('y')) result = minefield.click(x, y, expand=True) if result == -2: # mine on first click while result == -2: # generate new map until its safe minefield = Minesweeper(minefield.width, minefield.height, minefield.nMines) result = minefield.click(x, y, expand=True) return redirect(url_for('play')) elif result == -1: return redirect(url_for('lost')) else: # if 'lastURL' in session: # return redirect(session['lastURL']) return redirect(url_for('play'))
def test_board_print(self): """Description """ test_game = Minesweeper(10, 10) test_game.board = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 1, 1, 0, 0, 0, 0], ['*', 1, 0, 1, '*', 1, 0, 0, 0, 0], [1, 1, 1, 2, 2, 1, 0, 0, 0, 0], [0, 1, 2, '*', 1, 0, 0, 0, 0, 0], [0, 1, '*', 3, 2, 1, 0, 0, 0, 0], [0, 1, 1, 2, '*', 1, 0, 0, 0, 0]] result = test_game.print_board() expected = '- - - - - - - - - - \n- - - - - - - - - - \n- - - - - - - - - - \n- - - - - - - - - - \n1 1 - 1 1 1 - - - - \n* 1 - 1 * 1 - - - - \n1 1 1 2 2 1 - - - - \n- 1 2 * 1 - - - - - \n- 1 * 3 2 1 - - - - \n- 1 1 2 * 1 - - - - \n' self.assertEquals(result, expected)
class TestMinesweeper(unittest.TestCase): def setUp(self): self.game = Minesweeper(10, 10, 10) def test_number_of_mines_correct(self): self.assertEqual(str(self.game), "Mines: 10") def test_hints_correct(self): self.game.place_hints(10, 10) h = len(self.game.minemap) w = len(self.game.minemap[0]) result = True for j in range(0, h): for i in range(0, w): # j = y, i = x mines = 0 if 0 < self.game.minemap[j][ i] < 10: # (y-1,x-1);(y-1,x);(y-1,x+1);(y,x-1);(y,x+1);(y+1,x-1);(y+1,x);(y+1,x+1) if j - 1 >= 0 and i - 1 >= 0: if self.game.minemap[j - 1][i - 1] == 10: mines += 1 if j - 1 >= 0: if self.game.minemap[j - 1][i] == 10: mines += 1 if j - 1 >= 0 and i + 1 < w: if self.game.minemap[j - 1][i + 1] == 10: mines += 1 if i - 1 >= 0: if self.game.minemap[j][i - 1] == 10: mines += 1 if i + 1 < w: if self.game.minemap[j][i + 1] == 10: mines += 1 if j + 1 < h and i - 1 >= 0: if self.game.minemap[j + 1][i - 1] == 10: mines += 1 if j + 1 < h: if self.game.minemap[j + 1][i] == 10: mines += 1 if j + 1 < h and i + 1 < w: if self.game.minemap[j + 1][i + 1] == 10: mines += 1 if mines != self.game.minemap[j][i]: print(mines, self.game.minemap[j][i]) result = False break self.assertEqual(result, True)
def setup(self): """ Setup the game """ try: # Check for valid input w = self.__width.get() h = self.__height.get() m = self.__minecount.get() if m < 0: self.__errorLabel.configure(text="Can't have negative mines!") return if w < 5 or h < 5: # Too small board self.__errorLabel.configure( text="width/height must be over 5!") return except tk.TclError: # User entered invalid argument self.__errorLabel.configure(text="Invalid input!") return # desrtoy menu and start the game self.__root.destroy() self.__window = tk.Tk() self.__window.title("Minesweeper") # Initialize game self.__game = Minesweeper(self, self.__window, self.__width.get(), self.__height.get(), self.__minecount.get()) l1 = tk.Label(self.__window, text="Options") l1.grid(row=0, column=0) self.__l2 = tk.Label(self.__window, text=":|") self.__l2.grid(row=1, column=self.__width.get() // 2, columnspan=5) # Create buttons self.createButtons() # Update game self.__game.update() self.updateText(self.__game.hasWon())
def testPrintFieldAtLOST(self): game = Minesweeper() game.createFeild(3, 3) game.layMine(0, 0) game.layMine(1, 1) game.play(0, 0) expected = "* . . \n. * . \n. . . \n" "* . . " ". * . " ". . . " capturedOutput = io.StringIO() sys.stdout = capturedOutput game.printField() sys.stdout = sys.__stdout__ actual = capturedOutput.getvalue() self.assertEqual(expected, actual, "the full field didn't print well when player lost")
def testPrintFieldAtStart(self): game = Minesweeper() game.createFeild(3, 3) game.layMine(0, 0) game.layMine(1, 1) expected = ". . . \n. . . \n. . . \n" capturedOutput = io.StringIO() sys.stdout = capturedOutput game.printField() sys.stdout = sys.__stdout__ actual = capturedOutput.getvalue() self.assertEqual(expected, actual, "the empty field didn't print well")
def testLayMine(self): F1 = Minesweeper() F1.createFeild(4, 4) F1.layMine(1, 1) expect = "*" result = F1.field[1][1] self.assertEqual(expect, result, "The mine didn't laid well")
def newMapCustom(): global minefield width = int(request.args.get('width')) height = int(request.args.get('height')) nMines = int(request.args.get('nMines')) # In case there are too many mines, flashes a message to the user if nMines > width * height / 2: flash( 'Too many Mines (cannot have more than half the field with mines)' ) return redirect(url_for('play')) minefield = Minesweeper(width, height, nMines) return redirect(url_for('play'))
def testLayMineCircle(self): F1 = Minesweeper() F1.createFeild(4, 4) F1.layMine(1, 1) expect = 1 result = F1.field[2][2] self.assertEqual(expect, result, "The circle around the mine update well")
def main(): """ main function for graphical minesweeper game """ if len(sys.argv) == 4: width = int(sys.argv[1]) height = int(sys.argv[2]) nbombs = int(sys.argv[3]) else: width = 10 height = 10 nbombs = 2 game = Minesweeper(width, height, nbombs) print_game(game) while game.get_state() == GameState.unfinished: actions(game) if game.get_state() == GameState.winning: print("Vous avez gagné !") elif game.get_state() == GameState.losing: print("Vous avez perdu..")
def start(self): self.sweeper = Minesweeper(SIZE, N_MINE) self.sweeper.start() self.sweeper.print_board() self.old_board = [[None for _ in range(SIZE)] for _ in range(SIZE)] self.set_color_bar() while True: self.print_visible() x, y = self.read_button() y -= 1 print("you choose", x, y) if not (0 <= x < SIZE and 0 <= y < SIZE): print("FUCKOFF") continue self.old_board = deepcopy(self.sweeper.is_visible) status = self.choose(x, y) print("status", status) if self.sweeper.status == 'G': self.game_over() break if self.sweeper.status == 'W': self.winner() break
def main(): """ main function for graphical minesweeper game """ if len(sys.argv) == 4: width = int(sys.argv[1]) height = int(sys.argv[2]) nbombs = int(sys.argv[3]) else: width = 20 height = 10 nbombs = 1 game = Minesweeper(width, height, nbombs) graphicalboard.create(game)
def main(): """ main function for graphical minesweeper game """ # Takes the argument from the console. if len(sys.argv) == 4: width = int(sys.argv[1]) height = int(sys.argv[2]) nbombs = int(sys.argv[3]) else: width = 20 height = 20 nbombs = int(0.2*(width*height)) game = Minesweeper(width, height, nbombs) graphicalboard.create(game)
def testLayTwoMine(self): F1 = Minesweeper() F1.createFeild(4, 4) F1.layMine(1, 1) F1.layMine(1, 2) expect = 2 result = F1.field[2][2] self.assertEqual( expect, result, "the circle around the mines update well to 2, with two bombs")
def play(): # session['lastURL'] = url_for('play') global minefield if minefield is None: # session['minefield'] = Minesweeper(20,10,30) minefield = Minesweeper(20, 10, 30) minefieldHTML = drawField() if request.args.get('assist') is not None: minefieldHTML += '<br>' + drawFieldOpen() else: minefieldHTML += ''' <br> <button type="button"> <a href="/?assist=yes">Show Minefield (use for guidance)</a> </button> ''' return render_template('play.html', minefieldHTML=minefieldHTML)
def main(): """ main function for graphical minesweeper game :return: none :UC: None """ if len(sys.argv) == 4: width = int(sys.argv[1]) height = int(sys.argv[2]) nbombs = int(sys.argv[3]) else: width = 8 height = 8 nbombs = 5 game = Minesweeper(width, height, nbombs) graphicalboard.create(game)