def callBot(game_info): lines = game_info.split('\n') victory_cell = lines[1].split(' ') cell = Board() cell.update(lines[3:11]) you = lines[12] return bot(victory_cell, cell, you)
def test_getResult(self): x = Board() x.data = np.array([['E', 'W', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'W', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'B', 'W', 'E', 'E', 'E', 'E'], ['E', 'E', 'B', 'W', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'W', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'B', 'W', 'E', 'E', 'E'], ['E', 'B', 'B', 'B', 'B', 'B', 'B', 'W'], ['E', 'B', 'B', 'B', 'B', 'B', 'B', 'B']]) self.assertEqual(x.getResult(), (20, 7))
def test_getRow(self): x = Board() y = ['1', '2', '3', '4', '5', '6', '7', '8'] x.data = np.array([['B'] * 8] * 8) r = np.random.permutation(8) for i in range(8): x.data[i, r[i]] = 'W' for i in range(8): z = x.getRow(y[i]) for j in range(8): if j == r[i]: self.assertEqual(z[j], 'W') else: self.assertEqual(z[j], 'B')
def test_getColumn(self): x = Board() y = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] x.data = np.array([['B'] * 8] * 8) r = np.random.permutation(8) for i in range(8): x.data[r[i], i] = 'W' for i in range(8): z = x.getColumn(y[i]) for j in range(8): if j == r[i]: self.assertEqual(z[j], 'W') else: self.assertEqual(z[j], 'B')
def __init__(self, row, col): self.nrows = row #Number of rows and columns in the game screen self.ncols = col #Board is a class. The next line initialises Board by supplying it with the no of rows and columns and returns the matrix #The matrix, here, refers to the mathematical matrix which can be compared to the graphical screen divided into rows and columns self.matrix = Board(row, col).create_matrix()
def test_isDirectionPlaceable(self): x = Board() x.data = np.array([['E', 'W', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'W', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'B', 'W', 'E', 'E', 'E', 'E'], ['E', 'E', 'B', 'W', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'W', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'B', 'W', 'E', 'E', 'E'], ['E', 'B', 'B', 'B', 'B', 'B', 'B', 'W'], ['E', 'B', 'B', 'B', 'B', 'B', 'B', 'B']]) for (r, c) in itertools.product(list('12345678'), list('abcdefgh')): position = c + r if position in ["a2", "a3", "b4", "c6", "a7"]: self.assertTrue(x.isDirectionPlaceable(position, (0, 1), 'W')) else: self.assertFalse(x.isDirectionPlaceable(position, (0, 1), 'W'))
def test_setNextTurn(self): x = Game() y = Board() x.winner = "DRAW" self.assertFalse(x.setNextTurn("d3")) x.winner = None self.assertTrue(x.setNextTurn("d3")) y.data = np.array([['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'B', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'B', 'B', 'E', 'E', 'E'], ['E', 'E', 'E', 'B', 'W', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E']]) self.assertTrue(np.array_equal(x.board.data, y.data)) self.assertEqual(x.history, ["d3"]) self.assertFalse(x.setNextTurn("e6")) self.assertTrue(x.setNextTurn("NULL")) self.assertEqual(x.getWinner(), "BLACK")
def compute_heuristic_score(victory_cell, cell, you): p1_score = 0 p2_score = 0 p1_cell = 0 p2_cell = 0 empty_cell = 0 my_victory_cell = 0 opp_victory_cell = 0 my_corner = 0 new_board = Board() board_scores = [[120, -20, 20, 5, 5, 20, -20, 120], [-20, -40, -5, -5, -5, -5, -40, -20], [20, -5, 15, 3, 3, 15, -5, 20], [5, -5, 3, 3, 3, 3, -5, 5], [5, -5, 3, 3, 3, 3, -5, 5], [20, -5, 15, 3, 3, 15, -5, 20], [-20, -40, -5, -5, -5, -5, -40, -20], [120, -20, 20, 5, 5, 20, -20, 120]] for i in [0, 7]: for j in [0, 7]: if cell[i][j] == you: my_corner += 1 for i in victory_cell: c = new_board.getColumnId(i[0]) r = new_board.getRowId(i[1]) if cell[r][c] == you: my_victory_cell += 1 elif cell[r][c] != 'E': opp_victory_cell += 1 if (opp_victory_cell >= 3 and my_victory_cell == 0) or (my_victory_cell == 0 and my_corner > 0) or \ (my_victory_cell == 4 and my_corner >= 2): for i in victory_cell: c = new_board.getColumnId(i[0]) r = new_board.getRowId(i[1]) if board_scores[r][c] <= 0: board_scores[r][c] += 20 else: board_scores[r][c] += 60 for r in range(8): for c in range(8): if cell[r][c] == you: p1_cell += 1 p1_score += board_scores[r][c] elif cell[r][c] != 'E': p2_cell += 1 p2_score += board_scores[r][c] else: empty_cell += 1 if empty_cell > 0: return p1_score - p2_score else: return p1_cell - p2_cell
def test_getValue(self): x = Board() x.data = np.array([['B'] * 8] * 8) r = np.random.choice(64, 5, replace=False) for i in r: x.data[i // 8, i % 8] = 'W' for i, a in enumerate(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']): for j, b in enumerate(['1', '2', '3', '4', '5', '6', '7', '8']): if i + 8 * j in r: self.assertEqual(x.getValue(a + b), 'W') else: self.assertEqual(x.getValue(a + b), 'B')
def test_getDirectionFlips(self): x = Board() x.data = np.array([['E', 'W', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'W', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'B', 'W', 'E', 'E', 'E', 'E'], ['E', 'E', 'B', 'W', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'W', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'B', 'W', 'E', 'E', 'E'], ['E', 'B', 'B', 'B', 'B', 'B', 'B', 'W'], ['E', 'B', 'B', 'B', 'B', 'B', 'B', 'B']]) for (r, c) in itertools.product(list('12345678'), list('abcdefgh')): position = c + r if position == "a2": self.assertEqual( set(x.getDirectionFlips(position, (0, 1), 'W')), set([(1, 1)])) elif position == "a3": self.assertEqual( set(x.getDirectionFlips(position, (0, 1), 'W')), set([(2, 1), (2, 2)])) elif position == "b4": self.assertEqual( set(x.getDirectionFlips(position, (0, 1), 'W')), set([(3, 2)])) elif position == "c6": self.assertEqual( set(x.getDirectionFlips(position, (0, 1), 'W')), set([(5, 3)])) elif position == "a7": self.assertEqual( set(x.getDirectionFlips(position, (0, 1), 'W')), set([(6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)])) else: self.assertEqual(x.getDirectionFlips(position, (0, 1), 'W'), [])
def test_isOutOfRange(self): x = Board() for i in range(-1, 9): for j in range(-1, 9): if i < 0: self.assertTrue(x.isOutOfRange(i, j)) elif j < 0: self.assertTrue(x.isOutOfRange(i, j)) else: try: x.data[i, j] self.assertFalse(x.isOutOfRange(i, j)) except: self.assertTrue(x.isOutOfRange(i, j))
def test_update(self): x = Board() y = Board() x.update([ "E E E E E E E E", "B E E E E E E E", "E B E E E E E E", "E E B E B E E E", "W B B E W E E E", "E E E B B E E E", "E B E E E W E E", "W E E W E E E E" ]) y.data = np.array([['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['B', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'B', 'E', 'B', 'E', 'E', 'E'], ['W', 'B', 'B', 'E', 'W', 'E', 'E', 'E'], ['E', 'E', 'E', 'B', 'B', 'E', 'E', 'E'], ['E', 'B', 'E', 'E', 'E', 'W', 'E', 'E'], ['W', 'E', 'E', 'W', 'E', 'E', 'E', 'E']]) self.assertTrue(np.array_equal(x.data, y.data))
def test_place(self): x = Board() y = Board() x.data = np.array([['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['B', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'B', 'E', 'B', 'E', 'E', 'E'], ['W', 'B', 'B', 'E', 'W', 'E', 'E', 'E'], ['E', 'E', 'E', 'B', 'B', 'E', 'E', 'E'], ['E', 'B', 'E', 'E', 'E', 'W', 'E', 'E'], ['W', 'E', 'E', 'W', 'E', 'E', 'E', 'E']]) y.data = np.array([['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['B', 'E', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'B', 'E', 'E', 'E', 'E', 'E', 'E'], ['E', 'E', 'B', 'E', 'B', 'E', 'E', 'E'], ['W', 'W', 'W', 'W', 'W', 'E', 'E', 'E'], ['E', 'E', 'E', 'B', 'W', 'E', 'E', 'E'], ['E', 'B', 'E', 'E', 'E', 'W', 'E', 'E'], ['W', 'E', 'E', 'W', 'E', 'E', 'E', 'E']]) x.place("d5", 'W') self.assertTrue(np.array_equal(x.data, y.data))
def minimax_max(victory_cell, cell, you, depth): possible_positions = [] if type(cell) is tuple: new_board = Board() for i in range(8): for j in range(8): new_board.data[i][j] = cell[i][j] for (r, c) in itertools.product(list('12345678'), list('abcdefgh')): if new_board.isPlaceable(c + r, you): possible_positions.append(c + r) move_states = { move: play_move(new_board, you, new_board.getColumnId(move[0]), new_board.getRowId(move[1])) for move in possible_positions } else: for (r, c) in itertools.product(list('12345678'), list('abcdefgh')): if cell.isPlaceable(c + r, you): possible_positions.append(c + r) move_states = { move: play_move(cell, you, cell.getColumnId(move[0]), cell.getRowId(move[1])) for move in possible_positions } best_move = None best_value = None if len(possible_positions) > 0: if depth == 1: for move, state in move_states.items(): if best_move == None or minimax_min(victory_cell, state, you, depth + 1) > best_value: best_move = move best_value = minimax_min(victory_cell, state, you, depth + 1) return best_move else: for move, state in move_states.items(): if best_move == None or minimax_min(victory_cell, state, you, depth + 1) > best_value: best_value = minimax_min(victory_cell, state, you, depth + 1) return best_value return compute_heuristic_score(victory_cell, cell, you)
def minimax(curState, depth, alpha, beta, isMax): global bot global color global competitor global c_color game = Board() game.update(curState) result = evaluated(game) if (result != 'CONTINUE'): if (result == bot): return 999999 elif result == 'DRAW': return 0 else: return -999999 score = 0 if (depth == 0): b_nstep, c_nstep = numberOfStep(game, color) t_p, b_p, c_p = positionScore(game, color) score = findScoreCalculator(game, color) v_score = viectoryCellScore(game, color) if (b_p > c_p): score += 50 if (t_p < 20): if (b_nstep > c_nstep): score += 150 else: score += 50 else: if (b_nstep > c_nstep): score += 200 else: score += 100 else: # c_p > t_p score -= 50 if (t_p < 20): if (b_nstep > c_nstep): score -= 50 else: score -= 150 else: if (b_nstep > c_nstep): score -= 100 else: score -= 200 score += v_score if isMax: return score else: return -score if isMax: best = -999999 listPosiblePositions = posiblePositions(game, color) for step in listPosiblePositions: newGame = Board() newGame.update(curState) newGame.place(step, color) newState = newGame.getCellLineList() best = max(best, minimax(newState, depth - 1, alpha, beta, False)) alpha = max(alpha, best) if (beta <= alpha): break # print('max:', best) return best else: best = 999999 listPosiblePositions = posiblePositions(game, c_color) for step in listPosiblePositions: newGame = Board() newGame.update(curState) newGame.place(step, c_color) newState = newGame.getCellLineList() best = min(best, minimax(newState, depth - 1, alpha, beta, True)) beta = min(beta, best) if (beta <= alpha): break # print('min:', best) return best
def test_getRowId(self): x = Board() y = ['1', '2', '3', '4', '5', '6', '7', '8'] for i in range(8): self.assertEqual(x.getRowId(y[i]), i)
def test_getColumnId(self): x = Board() y = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] for i in range(8): self.assertEqual(x.getColumnId(y[i]), i)
def minimax(victory_cell, cur_state, you, depth, isMax, alpha, beta): game = Board() game.update(cur_state) color = 'W' if you == "BLACK" else 'B' final = evaluated(victory_cell, game, color) if final == you: return 9999 elif final != 'DRAW' and final != None: return -9999 elif final == 'DRAW': return 0 if depth == 0 and game.isPlayable(color): if isMax: return heuristic(victory_cell, game, you, True) else: return heuristic(victory_cell, game, you, False) if isMovesLeft(game, color) == False: return 0 if isMax: best = -9999 for (x, y) in itertools.product(list('12345678'), list('abcdefgh')): if game.isPlaceable(y + x, color): new_game = Board() new_game.update(cur_state) new_game.place(y + x, color) new_state = new_game.getCellLineList() best = max( best, minimax(victory_cell, new_state, you, depth - 1, False, alpha, beta)) alpha = max(alpha, best) if beta <= alpha: break # print('max:', best) return best else: best = 9999 for (x, y) in itertools.product(list('12345678'), list('abcdefgh')): if game.isPlaceable(y + x, color): new_game = Board() new_game.update(cur_state) new_game.place(y + x, color) new_state = new_game.getCellLineList() best = min( best, minimax(victory_cell, new_state, you, depth - 1, True, alpha, beta)) beta = min(beta, best) if beta <= alpha: break # print('min:', best) return best
def findBestMove(state, depth): global best global color global victory_cells game = Board() game.update(state) bestMoveVal = -999999 listPosiblePositions = posiblePositions(game, color) bestStep = listPosiblePositions[0] for step in listPosiblePositions: global best best = 0 # create new game newGame = Board() newGame.update(state) newGame.place(step, color) # get state newState = newGame.getCellLineList() # get score of move moveVal = minimax(newState, depth, -999999, 999999, True) # update step if (moveVal > bestMoveVal): bestMoveVal = moveVal bestStep = step print('step:', bestStep) return bestStep
def minBot(victory_cell, cell_line, you, alpha, beta, depth): cell = Board() cell.update(cell_line) color = 'W' if you == "BLACK" else 'B' result = is_end(victory_cell, cell, color) if depth == 0 or result != None and result != you: return Heuristic(victory_cell, cell, color, False) # elif result != None and result != you: # return 999998, None, None elif result == you: return -999998, None, None minv = 999999 px = None py = None cur_weight = getWeightSquares(cell, color) for (x, y) in itertools.product(list('12345678'), list('abcdefgh')): if cell.isPlaceable(y + x, color): new_cell = Board() new_cell.update(cell_line) new_cell.place(y + x, color) new_state = new_cell.getCellLineList() competitior = 'BLACK' if you != "BLACK" else 'WHITE' (m, max_x, max_y) = maxBot(victory_cell, new_state, competitior, alpha, beta, depth - 1) m -= cur_weight if m < minv: minv = m px = x py = y if minv <= alpha: return (minv, px, py) if minv < beta: beta = minv return minv, px, py
def BestMove(victory_cell, cur_state, you, depth): global best game = Board() game.update(cur_state) color = 'W' if you == "BLACK" else 'B' px = None py = None bestVal = -9999 for (x, y) in itertools.product(list('12345678'), list('abcdefgh')): if game.isPlaceable(y + x, color): global best best = 0 new_game = Board() new_game.update(cur_state) new_game.place(y + x, color) new_state = new_game.getCellLineList() moveVal = minimax(victory_cell, new_state, you, depth, True, -9999, 9999) + prior_spot(y + x) / 2 if moveVal > bestVal: px = x py = y bestVal = moveVal return px, py