def main(): board = Board() try: while True: main_loop(board) except GameOver, go: if go.status == GameOver.CANNOT_PUT: if go.looser == 'human': print u'\(^o^)/' else: print 'you win!' elif go.status == GameOver.COMPLETE: human = 0 for row, col in iter_points(): if board.get(row, col) == BLACK: human += 1 all_count = 8 * 8 print 'Result human:%d computer:%d' % (human, all_count - human) if human > all_count // 2: print 'you win!' elif human == half // 2: print 'draw...' else: print u'\(^o^)/' else: assert False
def test_init(self): game = Othello(4) self.assertEqual(game.board, Board(4)) self.assertEqual(game.active_color, 'black') game = Othello(8) self.assertEqual(game.board, Board(8)) self.assertEqual(game.active_color, 'black')
def evaluate(db, model): s = 0.0 n = 0.0 for moves, result in db.games: if np.random.rand() > 0.1: continue b = Board() for p, r, c in moves: b.flip(r, c, p) s += (model(b) - result) * (model(b) - result) n += 1.0 return (n, math.sqrt(s / n))
def test_init(self): board = Board(4) finder = flipFinder(board.size, board.positions, 'white') self.assertEqual(finder.size, board.size) self.assertEqual(finder.positions, board.positions) self.assertEqual(finder.color, 'white') board = Board(8) finder = flipFinder(board.size, board.positions, 'black') self.assertEqual(finder.size, board.size) self.assertEqual(finder.positions, board.positions) self.assertEqual(finder.color, 'black')
def test_init(self): board = Board(4) self.assertEqual(board.size, 4) self.assertEqual(board.center, Point(1, 1)) self.assertEqual(board.positions, INITIALIZED_4X4_BOARD) self.assertEqual(board.black_tiles, 2) self.assertEqual(board.white_tiles, 2) board = Board(8) self.assertEqual(board.size, 8) self.assertEqual(board.center, Point(3, 3)) self.assertEqual(board.positions, INITIALIZED_8X8_BOARD) self.assertEqual(board.black_tiles, 2) self.assertEqual(board.white_tiles, 2)
def test_find_flips_se(self): # Set up move validators for black and white board = Board(8) board.record_tile(Point(5, 3), 'white') board.record_tile(Point(5, 2), 'white') board.record_tile(Point(6, 1), 'black') board.record_tile(Point(6, 0), 'white') board.record_tile(Point(7, 5), 'white') flips_w = flipFinder(board.size, board.positions, 'white') flips_b = flipFinder(board.size, board.positions, 'black') # Test good input (1+ tiles flipped) one_flip = flips_w.find_flips_se(Point(3, 5)) three_flips = flips_b.find_flips_se(Point(2, 5)) self.assertEqual(one_flip, [Point(4, 4)]) self.assertEqual(three_flips, [Point(3, 4), Point(4, 3), Point(5, 2)]) # Test bad input (moves with no valid flips: # 1. Hits friendly tile without finding opposing tiles, or # 2. Hits edge of board or empty square without finding friendly tile # 3. Move is outside the board friendly_tile = flips_b.find_flips_se(Point(3, 5)) empty_space = flips_w.find_flips_se(Point(2, 4)) edge_south = flips_b.find_flips_se(Point(5, 1)) edge_east = flips_b.find_flips_se(Point(6, 6)) outside = flips_w.find_flips_se(Point(-100, 100)) self.assertEqual(friendly_tile, []) self.assertEqual(empty_space, []) self.assertEqual(edge_south, []) self.assertEqual(edge_east, []) self.assertEqual(outside, [])
def test_initialize_positions(self): board = Board(4) expected_output = INITIALIZED_4X4_BOARD self.assertEqual(board.initialize_positions(), expected_output) board = Board(8) expected_output = INITIALIZED_8X8_BOARD self.assertEqual(board.initialize_positions(), expected_output) board = Board(0) expected_output = [] self.assertEqual(board.initialize_positions(), expected_output)
def test_find_center(self): board = Board(4) center = board.find_center() self.assertEqual(center, Point(1, 1)) board = Board(8) center = board.find_center() self.assertEqual(center, Point(3, 3)) board = Board(12) center = board.find_center() self.assertEqual(center, Point(5, 5))
def print_board(board : othello.Board)->None: print("White total: %d\tBlack total: %d" % (board.num_white_pieces, board.num_black_pieces)) print(" -", end="") for i in range(board.cols): print((i + 1), end="") print("-") for y in range(board.rows): print("%0d|" % (y + 1), end="") for x in range(board.cols): board_piece = board.piece_at(othello.Point(x,y)) if board_piece == othello.Piece.WHITE: print("W", end="") elif board_piece == othello.Piece.BLACK: print("B", end="") else: print("-", end="") print("|") print(" ", end="") for _ in range(board.cols + 2): print("-", end="") print()
def validate(db): import random for moves, result in db.games: if random.random() < 0.9: continue b = Board() for p, r, c in moves: assert b.is_feasible(r, c, p) b.flip(r, c, p) black_score = b.score(Board.BLACK) white_score = b.score(Board.WHITE) score = black_score if b.score(Board.BLACK) > b.score(Board.WHITE): score = b.score(Board.BLANK) + black_score assert result in (black_score - white_score, 2 * score - 64)
def test_find_flips_all(self): # Set up a testable board board = Board(8) board.record_tile(Point(2, 2), 'white') board.record_tile(Point(5, 4), 'black') board.record_tile(Point(6, 5), 'black') board.record_tile(Point(7, 5), 'white') board.record_tile(Point(6, 6), 'white') board.record_tile(Point(5, 6), 'black') board.record_tile(Point(5, 7), 'black') board.record_tile(Point(4, 6), 'black') flips_b = flipFinder(board.size, board.positions, 'white') # Test good input (a move that results in a variety of flips or lack # thereof in each direction) test_move = flips_b.find_flips_all(Point(5, 5)) expected_outcome = [Point(6, 5), Point(4, 4), Point(3, 3)] self.assertEqual(test_move, expected_outcome) # Test behavior for a move outside of the board outside_board_test = flips_b.find_flips_all(Point(100, 100)) self.assertEqual(outside_board_test, [])
def test_get_initial_tiles_to_draw(self): expected_outcome = [(Point(-4, -25), 'black'), (Point(46, -25), 'white'), (Point(46, 25), 'black'), (Point(-4, 25), 'white')] board = Board(4) tiles = board.get_initial_tiles_to_draw() self.assertEqual(tiles, expected_outcome) board = Board(8) tiles = board.get_initial_tiles_to_draw() self.assertEqual(tiles, expected_outcome)
def main(): main_board = Board({ (half_x, half_y): Color.black, (half_x, half_y + 1): Color.white, (half_x + 1, half_y): Color.white, (half_x + 1, half_y + 1): Color.black }) return render_template('othello.html', board_x_size=Board.board_x_size, board_y_size=Board.board_y_size, stone_dict=main_board.get_stone_dict(), put_dict=main_board.get_put_dict(Color.black), status_dict=main_board.get_status_dict(), is_finish=main_board.is_finish(), Color=Color)
def perft(b: othello.Board, c: othello.Color, depth: int, passed: bool): if (depth == 0): return 1 moves = b.get_moves(c) # moves1 = b.old_get_moves(c) # if moves != moves1: # print(b.pretty()) # print(c.value, moves) # print(c.value, moves1) # print() if len(moves) == 0: if passed: return 1 return perft(b, c.opp(), depth - 1, True) nodes = 0 for m in moves: b1 = copy.deepcopy(b) b1.make_move(m, c) nodes += perft(b1, c.opp(), depth - 1, True) return nodes
def _alpha_beta_search(self, board, player, alpha, beta, depth, is_maximizing_player): if board.is_terminal_state() or depth == 0: return self._evaluator(board), None act = None if is_maximizing_player: r = AlphaBeta.MIN_VAL else: r = AlphaBeta.MAX_VAL actions = board.feasible_pos(player) opponent = Board.opponent(player) if len(actions) > 0: for i, j in actions: with board.flip2(i, j, player): v, _ = self._alpha_beta_search(board, opponent, alpha, beta, depth - 1, not is_maximizing_player) if is_maximizing_player: if r < v: act = (i, j) alpha = max(v, alpha) r = max(r, v) else: if r > v: act = (i, j) beta = min(v, beta) r = min(r, v) if alpha >= beta: break else: r, _ = self._alpha_beta_search(board, opponent, alpha, beta, depth, not is_maximizing_player) return r, act
def step_impl(context): context.board = Board()
def _read_thor_file(self, file_name): file_header_size = 16 record_header_size = 8 shots = 60 record_size = 68 games = [] with open(file_name, "rb") as f: c = f.read() board_size = _byte_to_int(c[12]) if board_size == 8 or board_size == 0: for i in xrange(file_header_size, len(c), record_size): moves = [] b = Board() player = Board.BLACK black_score = _byte_to_int(c[i + 6]) for j in xrange(record_header_size, record_size): play = _byte_to_int(c[i + j]) if play > 0: column = (play % 10) - 1 row = (play // 10) - 1 if not b.is_feasible(row, column, player): player = Board.opponent(player) moves.append((player, row, column)) b.flip(row, column, player) player = Board.opponent(player) score = b.score(Board.BLACK) if b.score(Board.BLACK) > b.score(Board.WHITE): score += b.score(Board.BLANK) if score == black_score: games.append((moves, black_score * 2 - 64)) else: self.inconsistencies += 1 return games
boards = [mem["states"][i] for i in indexes] actions = idx2onehot([mem["actions"][i] for i in indexes]) rewards = [mem["rewards"][i] for i in indexes] return np.array(boards).reshape( (size, boardDim)), actions, np.array(rewards) reset_graph() batchSize = 32 epochs = 100 gamma = 0.99 boardDim = 8 * 8 hLayersDim = [128, 256, 128] b = Board() p = buildGraph(boardDim, tf.float32, hLayersDim) replayMemory = {"states": [], "actions": [], "rewards": []} losses = [] with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for j in range(epochs): for i in range(batchSize): boards, moves, rewards = playGame(b, gamma) replayMemory["states"].extend(boards) replayMemory["actions"].extend(moves) replayMemory["rewards"].extend(rewards) boards, actions, rewards = sampleBatch(replayMemory, batchSize)
from flask import Flask from flask import render_template, flash from othello import Board, Color app = Flask(__name__) # 初期マップ half_x = Board.board_x_size // 2 half_y = Board.board_y_size // 2 main_board = Board({ (half_x, half_y): Color.black, (half_x, half_y + 1): Color.white, (half_x + 1, half_y): Color.white, (half_x + 1, half_y + 1): Color.black }) @app.route('/') def main(): main_board = Board({ (half_x, half_y): Color.black, (half_x, half_y + 1): Color.white, (half_x + 1, half_y): Color.white, (half_x + 1, half_y + 1): Color.black }) return render_template('othello.html', board_x_size=Board.board_x_size, board_y_size=Board.board_y_size, stone_dict=main_board.get_stone_dict(), put_dict=main_board.get_put_dict(Color.black), status_dict=main_board.get_status_dict(),
# -*- coding: utf-8 -*- import sys sys.path.append("../") import os from flask import Flask, request, send_from_directory, jsonify import json from othello import Board from value import ModelScorer, ScorerWrapper from ai import Bot board = Board() model_file = "../model/model.cpt.npy.6" scorer = ModelScorer(model_file) black_bot = Bot(scorer, 4, 10, Board.BLACK) white_bot = Bot(scorer, 4, 10, Board.WHITE) role_mapping = { "black": (black_bot, Board.BLACK), "white": (white_bot, Board.WHITE) } def _opponent(role): if role == Board.BLACK: return Board.WHITE, "white" else: return Board.BLACK, "black"
def self_play(n, model): b = Board() for t in xrange(1, n+1): b.init_board() p = Board.BLACK while not b.is_terminal_state(): options = b.feasible_pos(p) vals = [] if len(options) > 0: for i,j in options: with b.flip2(i, j, p): if b.is_terminal_state(): vals.append(b.score(Board.BLACK) - b.score(Board.WHITE)) else: vals.append(model(b)) (a0, a1), v = epsilon_greedy(0.07, options, vals, p == Board.BLACK) model.update(b, v) b.flip(a0, a1, p) p = Board.opponent(p) if t % 100 == 0: logging.info("Number of games played: {}".format(t)) logging.info(b.cache_status()) if t % 1000 == 0: model.save("./model/model.cpt") model.save("./model/model.cpt")
from othello import Board, Color # ここからがメイン部分だよ half_x = Board.board_x_size // 2 half_y = Board.board_y_size // 2 main_board = Board({ (half_x, half_y): Color.black, (half_x, half_y + 1): Color.white, (half_x + 1, half_y): Color.white, (half_x + 1, half_y + 1): Color.black }) while True: print(main_board.get_string()) print(main_board.get_status_dict()) if main_board.is_finish(): print("おしまい!") exit(0) # 自分の置ける石 player_dict = main_board.get_put_dict(Color.black) print("今の●の置ける位置:") print(player_dict) if player_dict: input_x = input("縦位置を入力してみてください(1~%d):" % Board.board_x_size) input_y = input("横位置を入力してみてください(1~%d):" % Board.board_y_size) if (int(input_x), int(input_y)) not in list(player_dict.keys()): print("置けないのでやり直し!") continue
def step_impl(context): context.board = Board(initial_position=False)
def test_eq(self): # Set up test boards with different attributes board_one = Board(4) board_two = Board(4) board_three = Board(8) board_four = Board(4) board_four.center = Point(3, 3) board_five = Board(4) board_five.positions = INITIALIZED_8X8_BOARD board_six = Board(4) board_six.black_tiles = 10 board_seven = Board(4) board_seven.white_tiles = 10 # Test for equality or lack thereof self.assertEqual(board_one, board_two) self.assertNotEqual(board_one, board_three) self.assertNotEqual(board_one, board_four) self.assertNotEqual(board_one, board_five) self.assertNotEqual(board_one, board_six) self.assertNotEqual(board_one, board_seven)
def test_is_full(self): # Test for boards of size 4 and 8 that are completely full board = Board(4) board.white_tiles = 9 board.black_tiles = 7 self.assertTrue(board.is_full()) board = Board(8) board.white_tiles = 40 board.black_tiles = 24 self.assertTrue(board.is_full()) # Test for boards of size 4 and 8 that have an open space board = Board(4) board.white_tiles = 8 board.black_tiles = 7 self.assertFalse(board.is_full()) board = Board(8) board.white_tiles = 39 board.black_tiles = 24 self.assertFalse(board.is_full())
def test_is_a_square(self): board = Board(4) # Test for inside and outside of board range self.assertTrue(board.is_a_square(Point(0, 0))) self.assertTrue(board.is_a_square(Point(3, 3))) self.assertTrue(board.is_a_square(Point(1, 2))) self.assertFalse(board.is_a_square(Point(5, 0))) self.assertFalse(board.is_a_square(Point(-1, 0))) self.assertFalse(board.is_a_square(Point(0, 4))) self.assertFalse(board.is_a_square(Point(0, -1))) board = Board(8) # Test for inside and outside of board range self.assertTrue(board.is_a_square(Point(0, 0))) self.assertTrue(board.is_a_square(Point(7, 7))) self.assertTrue(board.is_a_square(Point(1, 2))) self.assertFalse(board.is_a_square(Point(8, 0))) self.assertFalse(board.is_a_square(Point(-1, 0))) self.assertFalse(board.is_a_square(Point(0, 8))) self.assertFalse(board.is_a_square(Point(0, -1)))
def test_is_empty_square(self): # Set up a board with various tiles board = Board(4) board.record_tile(Point(3, 1), 'black') board.record_tile(Point(2, 2), 'white') board.record_tile(Point(2, 0), 'black') # Test for empty and non-empty sauares self.assertTrue(board.is_empty_square(Point(0, 2))) self.assertTrue(board.is_empty_square(Point(2, 3))) self.assertTrue(board.is_empty_square(Point(1, 3))) self.assertFalse(board.is_empty_square(Point(3, 1))) self.assertFalse(board.is_empty_square(Point(2, 2))) self.assertFalse(board.is_empty_square(Point(2, 0))) # Test for postions outside of board self.assertFalse(board.is_empty_square(Point(5, 0))) self.assertFalse(board.is_empty_square(Point(-1, 0))) self.assertFalse(board.is_empty_square(Point(0, 4))) self.assertFalse(board.is_empty_square(Point(0, -1)))
def test_record_tile(self): board = Board(4) # Inputs that result in a tile placement board.record_tile(Point(1, 3), 'white') board.record_tile(Point(0, 2), 'black') board.record_tile(Point(1, 2), 'black') # Inputs that don't result in a tile placement board.record_tile(Point(4, 3), 'white') board.record_tile(Point(1, 1), 'black') board.record_tile(Point(-1, 3), 'black') board.record_tile(Point(0, 5), 'black') board.record_tile(Point(0, -1), 'white') board.record_tile(Point(1, 2), 'red') expected_output = [[0, 0, 'black', 0], [0, 'black', 'black', 'white'], [0, 'white', 'black', 0], [0, 0, 0, 0]] self.assertEqual(board.positions, expected_output) self.assertEqual(board.black_tiles, 4) self.assertEqual(board.white_tiles, 2) board = Board(8) # Inputs that result in a tile placement board.record_tile(Point(6, 2), 'white') board.record_tile(Point(0, 7), 'black') board.record_tile(Point(3, 4), 'black') # Inputs that don't result in a tile placement board.record_tile(Point(3, 3), 'black') board.record_tile(Point(8, 3), 'white') board.record_tile(Point(-1, 3), 'black') board.record_tile(Point(0, 10), 'black') board.record_tile(Point(0, -1), 'white') board.record_tile(Point(2, 4), 'green') expected_output = [[0, 0, 0, 0, 0, 0, 0, 'black'], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 'black', 'black', 0, 0, 0], [0, 0, 0, 'white', 'black', 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 'white', 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] self.assertEqual(board.positions, expected_output) self.assertEqual(board.black_tiles, 4) self.assertEqual(board.white_tiles, 2)
def test_convert_turtle_to_square(self): board = Board(4) # Testing function normally # Good inputs square_one = board.convert_turtle_to_square(Point(-27, -74)) square_two = board.convert_turtle_to_square(Point(0, 0)) # Bad inputs - point is outside of the board in various ways square_three = board.convert_turtle_to_square(Point(-101, 50)) square_four = board.convert_turtle_to_square(Point(101, 50)) square_five = board.convert_turtle_to_square(Point(50, 101)) square_six = board.convert_turtle_to_square(Point(50, -101)) self.assertEqual(square_one, Point(1, 0)) self.assertEqual(square_two, Point(2, 2)) self.assertIsNone(square_three) self.assertIsNone(square_four) self.assertIsNone(square_five) self.assertIsNone(square_six) # Testing reverse version of function # Good inputs turtle_one = board.convert_turtle_to_square(Point(0, 0), 'r') turtle_two = board.convert_turtle_to_square(Point(3, 1), 'r') # Bad inputs - point is outside of the board in various ways turtle_three = board.convert_turtle_to_square(Point(4, 0), 'r') turtle_four = board.convert_turtle_to_square(Point(-1, 0), 'r') turtle_five = board.convert_turtle_to_square(Point(0, 4), 'r') turtle_six = board.convert_turtle_to_square(Point(0, -1), 'r') self.assertEqual(turtle_one, Point(-54, -75)) self.assertEqual(turtle_two, Point(96, -25)) self.assertIsNone(turtle_three) self.assertIsNone(turtle_four) self.assertIsNone(turtle_five) self.assertIsNone(turtle_six) board = Board(8) # Testing function normally # Good inputs square_one = board.convert_turtle_to_square(Point(199, -101)) square_two = board.convert_turtle_to_square(Point(-199, 158)) # Bad inputs - point is outside of the board in various ways square_three = board.convert_turtle_to_square(Point(201, 0)) square_four = board.convert_turtle_to_square(Point(-201, 0)) square_five = board.convert_turtle_to_square(Point(0, 201)) square_six = board.convert_turtle_to_square(Point(0, -201)) self.assertEqual(square_one, Point(7, 1)) self.assertEqual(square_two, Point(0, 7)) self.assertIsNone(square_three) self.assertIsNone(square_four) self.assertIsNone(square_five) self.assertIsNone(square_six) # Testing reverse version of function # Good inputs turtle_one = board.convert_turtle_to_square(Point(7, 5), 'r') turtle_two = board.convert_turtle_to_square(Point(5, 7), 'r') # Bad inputs - point is outside of the board in various ways turtle_three = board.convert_turtle_to_square(Point(8, 1), 'r') turtle_four = board.convert_turtle_to_square(Point(-1, 0), 'r') turtle_five = board.convert_turtle_to_square(Point(6, 8), 'r') turtle_six = board.convert_turtle_to_square(Point(6, -1), 'r') self.assertEqual(turtle_one, Point(196, 75)) self.assertEqual(turtle_two, Point(96, 175)) self.assertIsNone(turtle_three) self.assertIsNone(turtle_four) self.assertIsNone(turtle_five) self.assertIsNone(turtle_six)