Esempio n. 1
0
 def hack_q_table(self):
     logger.info('hacking qtable')
     board = Board()
     board.board[0][2] = CellState.PLAYER_X
     # minmax has to choose (1, 1)
     board_rep = self.q_table.representation(board)
     self.q_table.set(board_rep, (GameResult.DRAW, (0, 1)))
Esempio n. 2
0
    def board_initialization(self):
        # initializes the board, places the mines and pre-evaluate the numbers of neigbouring mines in each cell.
        self.board = Board(r=self.rows, c=self.cols, m=self.mines)

        self.board.init_board()
        self.board.place_mines()
        self.board.eval_nums()
Esempio n. 3
0
 def Update(self, terminalGame):
     """ Update this node - increment the visit count by one, and increase the win count by the result of terminalState for self.playerJustMoved.
     """
     self.visits += 1
     self.Q = self.W / self.visits
     if Game.getGameEnded(terminalGame, self.playerJustMoved) != 0:
         self.W += Game.getGameEnded(terminalGame, self.playerJustMoved)
     else:
         self.W += self.v
Esempio n. 4
0
    def run(self, verbose=True):
        board = Board()
        self.players[0].start_game(CellState.PLAYER_X)
        self.players[1].start_game(CellState.PLAYER_O)

        if verbose:
            board.print_board()
        stone = CellState.PLAYER_X
        for i in range(9):
            player = self.players[i % 2]

            row, col = player.next_move(board)

            if board.board[row][col] != CellState.EMPTY:
                print '%s made an invalid move: (%d, %d)' % (player.name(),
                                                             row, col)
                raise Exception('Debug now!')
            board.board[row][col] = stone
            if verbose:
                print '%dth move, %s picked row %d, col %d' % (
                    i, player.name(), row, col)
                board.print_board_with_last_move(row, col)
            stone = stone.reverse_role()

            verdict = board.evaluate()
            if verdict != GameResult.UNFINISHED:
                break

        if verbose:
            print verdict.announce()
        # end game
        for player in self.players:
            player.end_game(verdict)
        return verdict
Esempio n. 5
0
    def __init__(self, strategy=BlueprintBase):
        self.board = Board()
        
        self.rack = []
        self.distribution = distribution[:]
        self.drawTiles()
            
        self.checkWord = self.board.checkWord
        self.extraList = self.board.extraList

        self.score = 0

        self.BlueprintCreator = strategy
        
        self.name = "CPU"
Esempio n. 6
0
    def test_open_game(self):
        board = Board([[1, 2, 0], [0, 0, 0], [0, 0, 0]])
        # X's move
        result, move = self.strat.eval_board(board, 1)
        self.assertEqual(result, 3)
        print move

        board.board[1][1] = 1
        result, move = self.strat.eval_board(board, 2)
        print result, move

        role = CellState.PLAYER_O
        for i in range(4):
            row, col = move
            board.board[row][col] = role
            role = role.reverse_role()
            result, move = self.strat.eval_board(board, role)
            print role, result, move
Esempio n. 7
0
def save_minmax_qtable():
    strat = strategies.MinMaxWithQTable()

    board = Board()
    best_result, best_move = strat.eval_board(board, CellState.PLAYER_X)
    # 3964 states: once we find a win, no need to explore other branches
    print strat.q_table.stats()
    print strat.q_table.stats_by_num_stones().items()

    strat.q_table.save('/tmp/minmax.qtable')
Esempio n. 8
0
    def test_mid_game(self):
        board = Board([[1, 2, 2], [2, 0, 1], [1, 0, 0]])
        # X's move
        result, move = self.strat.eval_board(board, 1)
        self.assertEqual(result, 1)
        self.assertEqual(move, (2, 2))

        # O's move
        result, move = self.strat.eval_board(board, 2)
        self.assertEqual(result, 0)
Esempio n. 9
0
    def test_qtable(self):
        board = Board()
        best_result, best_move = self.strat.eval_board(board,
                                                       CellState.PLAYER_X)
        print best_result, best_move
        # MinMaxCrude: 3964 states: once we find a win, no need to explore other branches
        # MinMax: 4520 states
        print self.strat.q_table.stats()
        print self.strat.q_table.stats_by_num_stones().items()

        self.strat.q_table.save('/tmp/minmax.qtable')
Esempio n. 10
0
    def test_end_game(self):
        board = Board([[1, 2, 2], [2, 2, 1], [1, 0, 0]])
        # defensive move
        result, move = self.strat.eval_board(board, 1)
        self.assertEqual(result, 0)
        self.assertEqual(move, (2, 1))

        # offensive move
        result, move = self.strat.eval_board(board, 2)
        self.assertEqual(result, 2)
        self.assertEqual(move, (2, 1))
Esempio n. 11
0
    def exploit(self, board):
        q_best = -1e10
        best_moves = []
        score_board = board.empty_score_board()
        for row, col in board.next_empty_square():
            board.board[row][col] = self.role
            _, q_val, update_count = self._lookup_qtable_or_init(board)
            score_board[row][col] = '%.1f %g' % (10 * q_val, update_count)
            if q_val > q_best:
                q_best = q_val
                best_moves = [(row, col)]
            elif q_val == q_best:  #
                best_moves.append((row, col))
            board.board[row][col] = CellState.EMPTY

        # randomize among best moves
        move = random.choice(best_moves)
        if self.debug:
            Board.print_score_board_with_highlight(score_board, move[0],
                                                   move[1])
        return q_best, move
Esempio n. 12
0
    def _move_is_legal(self, received_fen, last_saved_fen):
        if received_fen in ONE_MOVE_AFTER_START_FENS:
            try:
                received_fen = ONE_MOVE_AFTER_START_FENS_UNSANITIZED_DICT[
                    received_fen]
            except KeyError:
                pass
            return True, received_fen, True

        last_saved_board = Board(last_saved_fen)
        legal_moves = [move for move in last_saved_board.legal_moves]

        if not received_fen:
            self.send_error(500)
        for move in legal_moves:
            last_saved_board.push(move)
            sanitized_fen = last_saved_board.fen()
            unsanitized_fen = last_saved_board.unsanitized_fen()
            if sanitized_fen == received_fen or unsanitized_fen == received_fen:
                return True, sanitized_fen, False
            last_saved_board = Board(last_saved_fen)

        return False, None, False
Esempio n. 13
0
class BasicTest(TestCase):
    def setUp(self):
        self.board = Board()

    def testPrintBoard(self):
        self.board.print_board()

    def testEvaluateGame(self):
        verdict = self.board.evaluate()
        print 'empty board: ', verdict
        self.assertEqual(verdict, GameResult.UNFINISHED)

        for i in range(3):
            self.board.board[1][i] = CellState.PLAYER_O
        verdict = self.board.evaluate()
        print 'second row all O:', verdict
        self.assertEqual(verdict, GameResult.O_WINS)

    def testDiagonal(self):
        self.board.board[0][2] = CellState.PLAYER_X
        self.board.board[1][1] = CellState.PLAYER_X
        self.assertEqual(self.board.evaluate(), GameResult.UNFINISHED)

        self.board.board[2][0] = CellState.PLAYER_X
        verdict = self.board.evaluate()
        self.assertEqual(verdict, GameResult.X_WINS)

    def test_cmp_safety(self):
        self.assertEqual(GameResult.X_WINS, CellState.PLAYER_X)
        self.assertEqual(GameResult.O_WINS, CellState.PLAYER_O)
        self.assertNotEqual(GameResult.X_WINS, CellState.PLAYER_O)

    def test_board_rep(self):
        q_table = QTable()
        tpl1 = (1, 0, 2)
        tpl2 = (CellState.PLAYER_X, CellState.EMPTY, CellState.PLAYER_O)
        tpl3 = (1, 0, CellState.PLAYER_O)
        print hash(tpl1)
        self.assertEqual(hash(tpl1), hash(tpl2))
        self.assertEqual(hash(tpl1), hash(tpl3))

    def test_state_counts(self):
        self.assertEqual(StateCount.num_states_for_step(1), 9)
        print[StateCount.num_states_for_step(i) for i in xrange(1, 10)]
        # [9, 72, 252, 756, 1260, 1680, 1260, 630, 126]
        total_num_states_for_x = StateCount.total_num_states_for_X()
        total_num_states_for_o = StateCount.total_num_states_for_O()
        print 'total #states for X', total_num_states_for_x
        print 'total #states for O', total_num_states_for_o
        print '3**9 =', 3**9
        self.assertEqual(total_num_states_for_x, 2907)
        self.assertEqual(total_num_states_for_o, 3138)
Esempio n. 14
0
class SimpleTest(TestCase):
    def setUp(self):
        self.board = Board()
        self.board.board[0][0] = CellState.PLAYER_X
        self.board.board[0][1] = CellState.PLAYER_X
        # [1, 1, EMPTY],
        # [EMPTY, EMPTY, EMPTY],
        # [EMPTY, EMPTY, EMPTY]]

    def test_difloc(self):
        self.assertEqual(difloc(0, 2), 1)
        self.assertEqual(difloc(1, 2), 0)

    def test_Robert_Strat1(self):
        strat = RobertStrat1()
        strat.start_game(1)
        row, col = strat.next_move(self.board)
        self.assertEqual((row, col), (0, 2))

    def testIterateOverEmptySpots(self):
        print[(row, col) for (row, col) in self.board.next_empty_square()]
Esempio n. 15
0
def initGameLogic(skip1):
	board=Board(skip1)
	board.clock.tick()
	return board
Esempio n. 16
0
import PySimpleGUIWeb as sg
from random import randint
import numpy as np
from time import sleep
from utils import Board

while True:
    h = 10
    w = 10
    board = Board(w, h)
    game_lost = False
    previous_display = board.display.copy()
    exited = False
    mines = board.num_mines
    mode_on = ('black', 'green')
    mode_off = ('black', 'red')
    clear_mode = True

    button_grid = [[
        sg.Button('?', size=(4, 2), key=(i, j), pad=(0, 0)) for j in range(w)
    ] for i in range(h)]
    mode_toggle = [[
        sg.Text("Click Mode: "),
        sg.Button('Mine', button_color=mode_off, key='mine_mode', pad=(0, 0)),
        sg.Button('Clear', button_color=mode_on, key='clear_mode', pad=(0, 0))
    ]]
    top_row = [
        sg.Text("Mines Remaining:"),
        sg.Text(f"{mines}",
                pad=(50, 0),
                text_color='red',
Esempio n. 17
0
    def getBestAction(self, rootstate, itermax, verbose=False, temp=1):
        """ Conduct an ISMCTS search for itermax iterations starting from rootstate.
            Return the best move from the rootstate.
        """

        rootnode = Node(self.nnet)

        for i in range(itermax):
            node = rootnode
            # Determinize
            game = self.CloneAndRandomize(rootstate)
            # Select
            while Game.getGameEnded(
                    game.current_player, game) == 0 and node.GetUntriedMoves(
                        Game.GetValidMoves(
                        )) == []:  # node is fully expanded and non-terminal
                node = node.SelectChild(Game.GetValidMoves())
                Game.getNextState(game, game.current_player, node.move)

            #
            untriedMoves = node.GetUntriedMoves(
                Game.getValidMoves(game) * node.pi)
            if untriedMoves != []:  # if we can expand (i.e. state/node is non-terminal)
                m = random.choice(untriedMoves)
                player = game.current_player
                Game.getNextState(game, player, m)
                node = node.AddChild(
                    m, player,
                    Game.getState(game))  # add child and descend tree

            # Simulate
            while Game.getGameEnded(node.playerJustMoved,
                                    game) == 0:  # while state is non-terminal
                Game.getNextState(game, game.current_player,
                                  random.choice(np.argwhere(node.pi == 1)))

            # Backpropagate
            while node != None:  # backpropagate from the expanded node and work back to the root node
                node.Update(game)
                node = node.parentNode

        # Output some information about the tree - can be omitted
        # if verbose:
        #     print(rootnode.TreeToString(0){})
        # else:
        #     print(rootnode.ChildrenToString())
        return max(rootnode.childNodes, key=lambda c: c.visits**1 / temp
                   ).move  # return the move that was most visited
Esempio n. 18
0
def train(model_path=config.model_save_path,
          statistic_path=config.statistic_save_path,
          path_label=config.path_label_train,
          path_mask=config.path_mask_train,
          sub_name=config.sub_dataset_train,
          ifboard=config.ifboard):
    '''模型设置'''

    model = getattr(Networks, config.model)(config.input_band, 1)  #创立网络对象
    model.apply(weights_init)
    if config.model_load_path:  #加载模型
        model.load(config.model_load_path)

    if config.use_gpu:  #使用gpu
        model = model.cuda()
    '''数据加载'''
    transform_img = config.transform_img
    transform_label = config.transform_label
    train_data = WaterDataset(train=True,
                              val=False,
                              transforms_img=transform_img,
                              transforms_label=transform_label,
                              sub=sub_name,
                              path_label=path_label,
                              path_mask=path_mask)

    train_dataloader = DataLoader(
        train_data,
        config.batch_size,
        shuffle=True,  #每一epoch打乱数据
        num_workers=config.num_workers)

    test_data = WaterDataset(train=False,
                             val=True,
                             transforms_img=transform_img,
                             transforms_label=transform_label)

    test_dataloader = DataLoader(
        test_data,
        1,
        shuffle=True,  #每一epoch打乱数据
        num_workers=2)

    print('data loaded')
    '''目标函数和优化器'''
    criterion = torch.nn.BCELoss()
    learning_rate = config.learning_rate
    optimizer = torch.optim.Adam(model.parameters(),
                                 lr=learning_rate,
                                 weight_decay=config.weight_decay)
    '''测试工具'''
    testtools = testTools(model=model, data=test_dataloader)

    print('testtools prepared!')
    '''记录、统计'''
    recording_loss = []
    running_loss = 0  #中间数据
    recording_iou = []
    iou_max_pre = 0  #记录之前最大的iou
    checkpoint = None
    number_unchange = 0

    if config.ifbar:
        bar = Bar(name='train',
                  max_batch=int(50000 / config.batch_size),
                  max_epoch=config.max_epoch)
    if ifboard:
        board = Board(False)
    '''训练'''

    for epoch in range(config.max_epoch):
        t1 = time.time()
        for i, data in enumerate(train_dataloader, 0):
            if path_mask:
                inputs, labels, name, mask = data  #获得输入和标签
                if config.use_gpu:  #使用gpu
                    inputs = inputs.cuda()
                    labels = labels.cuda()
                    mask = mask.cuda()
            else:
                inputs, labels, name = data  #获得输入和标签
                if config.use_gpu:  #使用gpu
                    inputs = inputs.cuda()
                    labels = labels.cuda()

            optimizer.zero_grad()  #积累的导数归零

            if path_mask:
                outputs = model(inputs) * mask  #前向传播
                labels = labels * mask
            else:
                outputs = model(inputs)

            loss = criterion(outputs, labels)  #计算损失

            #记录
            running_loss += loss.item()

            if i % config.number_recording == config.number_recording - 1:
                recording_loss.append(running_loss / config.number_recording)

                iou = testtools.IoU(recaculate=True).max()
                #iou=testtools.PA(recaculate=True).max()
                recording_iou.append(iou)

                number_unchange += 1
                if iou > iou_max_pre:
                    iou_max_pre = iou
                    torch.save(model, config.model_save_path_checkpoints)
                    number_unchange = 0

                running_loss = 0

                if ifboard:
                    board.setData([recording_loss[-1], recording_iou[-1]])
                #print('epoch:'+str(epoch)+',batches:'+str(i-config.number_recording+1)+'--'+str(i)+
                #',loss:'+str(recording_loss[-1])+', iou:'+str(recording_iou[-1])+', max_iou:'+str(iou_max_pre))
                #print('epoch:'+str(epoch)+',batches:'+str(i-config.number_recording+1)+'--'+str(i)+
                #',loss:'+str(recording_loss[-1])+', iou:'+str(recording_iou[-1]))

            loss.backward()  #后向传播
            optimizer.step()  #更新参数

            if config.ifbar:
                if len(recording_loss) == 0:
                    info = None
                else:
                    info = {
                        'loss:': recording_loss[-1],
                        'iou:': recording_iou[-1],
                        'max_iou:': iou_max_pre
                    }
                bar.draw(info=info)

        t2 = time.time()
        print('time: ' + str((t2 - t1) / 60) + ' min')

    if ifboard:
        board.closeClient()

    model_dict = torch.load(config.model_save_path_checkpoints).state_dict()
    # 载入参数
    model.load_state_dict(model_dict)
    '''保存模型'''
    #if config.model_save_path:
    #    model.save(config.model_save_path)

    model.save(model_path)
    '''保存统计数据'''
    #if config.statistic_save_path:
    #    with shelve.open(config.statistic_save_path) as f:
    #        f['loss']=recording_loss
    #        f['iou']=recording_iou
    with shelve.open(statistic_path) as f:
        f['loss'] = recording_loss
        f['iou'] = recording_iou

    print('Finished Training!')
Esempio n. 19
0
class YEET:
    """
    This class specifies the base Game class. To define your own game, subclass
    this class and implement the functions below. This works when the game is
    two-player, adversarial and turn-based.

    Use 1 for player1 and -1 for player2.
    21 possible actions per move, and 8 possible targets per action + 1 if no targets
    is_basic = True initializes game between priest and rogue only
    """
    def __init__(self, is_basic=True):
        self.num_actions = 21
        self.players = ['player1', 'player2']
        self.is_basic = is_basic
        self.b = Board()

    def getInitGame(self):
        """
        Returns:
            startBoard: a representation of the board (ideally this is the form
                        that will be the input to your neural network)
        """
        # self.b.isolateSet()
        self.b.initGame()
        return self.b.game

    def getNextState(self, player, action, game_instance=Board.game):
        """
        Input:
            board: current board (gameUtils)
            player: current player (1 or -1)
            action: action taken by current player

        Returns:
            nextBoard: board after applying action
            nextPlayer: player who plays in the next turn (should be -player)

            all actions executed by copy_player to preserve new game

        """
        if game_instance == None:
            game_instance = Board.game

        try:
            self.b.performAction(action, player, game_instance)
        except GameOver:
            raise GameOver
        next_state = self.b.getState(player, game_instance)
        if action[0] != 19:
            return next_state, player
        else:
            return next_state, -player

    def getValidMoves(self, player, game_instance=Board.game):
        """
        Input:
            board: current board
            player: current player

        Returns:
            validMoves: a binary vector of length self.getActionSize(), 1 for
                        moves that are valid from the current board and player,
                        0 for invalid moves
        """
        # if player == 1:
        #     current_player = self.b.players[0]
        # elif player == -1:
        #     current_player = self.b.players[1]
        if game_instance == None:
            game_instance = Board.game
        return self.b.getValidMoves(game_instance)

    def getGameEnded(self, game_instance=Board.game):
        """
        Input:
            board: current board
            player: current player (1 or -1)

        Returns:
            r: 0 if game has not ended. 1 if player won, -1 if player lost,
               small non-zero value for draw.
        """
        if game_instance == None:
            game_instance = Board.game

        p1 = game_instance.player_to_start

        if p1.playstate == 4:
            return 1
        elif p1.playstate == 5:
            return -1
        elif p1.playstate == 6:
            return 0.0001
        elif game_instance.turn > 180:
            game_instance.ended = True
            return 0.0001
        return 0

    def getState(self, player, game_instance=Board.game):
        """
        Input:
            board: current board
            player: current player (1 or -1)

        Returns:
            state: see gameUtils.getState for info
        """
        # if player == 1:
        #     current_player = self.b.players[0]
        # elif player == -1:
        #     current_player = self.b.players[1]
        if game_instance == None:
            game_instance = Board.game

        return self.b.getState(player, game_instance)
        # return b.game

    def getSymmetries(self, state, pi):
        """
        Input:
            board: current board
            pi: policy vector of size self.getActionSize()

        Returns:
            symmForms: a list of [(board,pi)] where each tuple is a symmetrical
                       form of the board and the corresponding pi vector. This
                       is used when training the neural network from examples.
        """
        # assert(len(pi) == len(state))
        assert (len(pi) == 168)
        pi_board = np.reshape(pi, (21, 9))
        l = []

        for i in range(1, 5):
            for j in [True, False]:
                newS = np.rot90(state, i)
                newPi = np.rot90(pi_board, i)
                if j:
                    newS = np.fliplr(newS)
                    newPi = np.fliplr(newPi)
                l += [(newS, list(newPi.ravel()) + [pi[-1]])]
        return l

    def stringRepresentation(self, state):
        """
        Input:
            state: np array of state

        Returns:
            boardString: a quick conversion of board to a string format.
                         Required by MCTS for hashing.
        """
        return state.tostring()
Esempio n. 20
0
 def __init__(self, is_basic=True):
     self.num_actions = 21
     self.players = ['player1', 'player2']
     self.is_basic = is_basic
     self.b = Board()
Esempio n. 21
0
    def __init__(self, input=0, camera=None, imgpts=None, board=None):
        if not isinstance(camera, Camera):
            camera = Camera(device=input)

        self.camera = camera
        self.frame,reseted  = self.camera.get_image()

        if board is None:
            self.board = Board()
        else:
            self.board = board
        allobj = self.board._get_configs()
        [i.append(0) for i in allobj]
        nobj = np.array(allobj, np.float64)
        if imgpts is None:
            cv2.namedWindow("Calibration Window", cv2.WINDOW_NORMAL)
            cv2.namedWindow("Calibration Hint", cv2.WINDOW_NORMAL)
            cv2.imshow("Calibration Window", self.frame)
            cv2.waitKey(1)
            config_points = nobj
            cv2.setMouseCallback("Calibration Window", self.click)
            pos = 0
            for i in config_points:
                print ("Select field %s please. Accept with any key." % str(i))
                hintim = self.board.get_config_hint(pos)
                cv2.imshow("Calibration Hint", hintim)
                k = cv2.waitKey(-1) & 0xFF
                self.imgpoints.append(self.imgpoint)
                if k == 27:
                    print("Escaped and closing.")
                    break
                else:
                    print("Thank you")
                    pos += 1

        else:
            self.imgpoints = imgpts

        print("Imagepoints %s" % self.imgpoints)
        print("Objp %s" % nobj)

        print(self.camera.config['dist'])
        print(np.array(self.camera.config['mtx']))
        _, rvec, tvec = cv2.solvePnP(nobj,
                                     np.array(self.imgpoints, np.float64), np.array(self.camera.config['mtx']),
                                     np.array(self.camera.config['dist']), None,None, False, cv2.SOLVEPNP_ITERATIVE)
        mean_error = 0
        imgpoints2, _ = cv2.projectPoints(nobj, rvec, tvec, self.camera.cameramatrix, self.camera.config['dist'])
        impoints = np.array([[x] for x in self.imgpoints], np.float64)
        error = cv2.norm(impoints, imgpoints2, cv2.NORM_L2) / len(imgpoints2)
        mean_error += error

        print "total error: ", mean_error
        outers = self.board.get_radius()
        def calcy(x,r):
            return np.sqrt(np.power(r,2)-np.power(x,2))

        points = []
        for outer in outers:
            xs = [i*0.1 for i in range(0,int(outer*10))]
            xs += [i*-0.1 for i in range(0,int(outer*10))]
            for i in xs:
                y = calcy(i,int(outer))
                points.append([[i],[y],[0]])
                points.append([[i], [-y], [0]])
        points = np.array(points)
        # points = np.array([[[0],[0],[0]], [[outer],[0],[0]]])
        imp, jac = cv2.projectPoints(points, rvec,tvec, np.array(self.camera.config['mtx']), np.array(self.camera.config['dist']))
        rot, _ = cv2.Rodrigues(rvec)
        rev = projectReverse(self.imgpoints,rot, tvec, self.camera.config['mtx'])
        self.rot = rot
        self.tvec = tvec
        # b.draw_board_to_frame(frame2)
        print("Imagepoints %s" % self.imgpoints)
        print("Objecpoints %s" % rev)
        cv2.destroyAllWindows()
        self.imp = imp
Esempio n. 22
0
 def run():
     game = Board.Board()
     game.print_board()
Esempio n. 23
0
class Driver:
    def __init__(self, r, c, m):
        self.rows = r
        self.cols = c
        self.mines = m

        self.board_initialization()

    def board_initialization(self):
        # initializes the board, places the mines and pre-evaluate the numbers of neigbouring mines in each cell.
        self.board = Board(r=self.rows, c=self.cols, m=self.mines)

        self.board.init_board()
        self.board.place_mines()
        self.board.eval_nums()
        # self.board.display_board_dbg()

    def get_verify_input(self):
        # Makes sure that input is a valid integer and in the limits.
        while True:
            try:
                r = int(input("Enter row in [1, {}]: ".format(self.rows)))
                c = int(input("Enter column in [1, {}]: ".format(self.cols)))
            except ValueError:
                print("Enter valid input.")
                continue

            if 1 <= r <= self.rows and 1 <= c <= self.cols:
                break
            else:
                print("Enter valid input.")

        # converting inputs to array indices.
        r = r - 1
        c = c - 1

        return r, c

    def main_loop(self):
        print("This Minesweeper has {} rows and {} columns.\n".format(
            self.rows, self.cols))

        # r, c = self.get_verify_input()
        while True:
            self.board.display_board()
            r, c = self.get_verify_input()
            self.board.handle_clicking(r, c)

            status = self.board.get_game_status()

            if status < 0:
                print("\n\n\t\tGame Over! You Lost!")
                self.board.display_board(over=True)
                break
            if status == 1:
                print("\n\n\t\tCongratulations! You won!")
                self.board.display_board(over=True)
                break
Esempio n. 24
0
    def post(self):

        with self.make_session() as db_session:

            response_dict = {}
            received_fen = self.get_argument('position', None)
            cookie_val = self.get_cookie(COOKIE_NAME)

            chess_session_row, new_cookie_val = _resolve_chess_session_from_cookie_session(
                db_session, cookie_val)

            if new_cookie_val:
                self.set_cookie(COOKIE_NAME, new_cookie_val)

            move_is_legal, sanitized_fen, board_is_reset = self._move_is_legal(
                received_fen, chess_session_row.fen)

            if board_is_reset:
                chess_session_row.injected_argument_counter = 0
                chess_session_row.nr_of_player_moves = 0
                db_session.commit()

            if not move_is_legal:
                response_dict["resetBoard"] = True
                response_dict["img"] = get_meme_hint()
                response_dict["msg"] = ILLEGAL_MOVE_MESSAGE
                db_session.commit()
                self.write(response_dict)
                self.finish()
                return

            received_board = Board(sanitized_fen)
            chess_session_row.nr_of_player_moves += 1
            injected_arguments = self._get_injected_arguments()
            if len(injected_arguments.keys()) > 0:
                info_dict = json.dumps(info_handler.info)
                response_dict["info"] = info_dict

            chess_session_row.injected_argument_counter += "searchmoves" in injected_arguments.keys(
            )

            best_move = self.get_best_move(received_board)
            if best_move is not None:
                received_board.push(best_move)
            outbound_board = received_board

            game_state = self._get_game_state(
                outbound_board, chess_session_row.injected_argument_counter,
                chess_session_row.nr_of_player_moves)

            if game_state == GAME_STATE.NOT_FINISHED:
                chess_session_row.fen = outbound_board.fen()
                response_dict["bestMove"] = best_move.uci()
            elif game_state == GAME_STATE.COMPUTER_HAS_WON:
                response_dict["msg"] = COMPUTER_HAS_WON_MESSAGE
                response_dict["bestMove"] = best_move.uci()
                response_dict["img"] = get_meme_hint()
            elif game_state == GAME_STATE.HUMAN_HAS_WON:
                response_dict["msg"] = HUMAN_HAS_WON_MESSAGE
            elif game_state == GAME_STATE.HUMAN_HAS_WON_BUT_CHEATED:
                response_dict["msg"] = HUMAN_HAS_WON_BUT_CHEATED_MESSAGE
                response_dict["img"] = get_meme_hint()

            db_session.commit()
            self.write(response_dict)
            self.finish()
Esempio n. 25
0
class CPU():
    def __init__(self, strategy=BlueprintBase):
        self.board = Board()
        
        self.rack = []
        self.distribution = distribution[:]
        self.drawTiles()
            
        self.checkWord = self.board.checkWord
        self.extraList = self.board.extraList

        self.score = 0

        self.BlueprintCreator = strategy
        
        self.name = "CPU"

    def drawTiles(self):
        while len(self.rack)<7 and len(self.distribution)>0:
            letter = random.choice(self.distribution)
            self.rack.append(letter.upper())
            self.distribution.remove(letter)
    
    def gacc(self, iterable, maxDepth):
        for word in self.gac(iterable, maxDepth):
            if self.checkWord(word):
                yield word
    
    def displayBoard(self, board):
        s="{bar}\n{sep}\n".format(bar="|",sep="-"*66)
        text=s+s.join(''.join('|'+c.center(4 if j == 0 else 3) for j, c in enumerate(r)) for r in board) + s
        text = text[2:-1]
        print(text)
        return text

    def generate(self):
        prevBoard = self.board.clone()
        words = self.board.removeDuplicates(self.gacc(self.rack, len(self.rack)))
        places = self.board.getPlaces(self.board.board)
        neighbors = []

        if places == []:
            for i in range(1, 15):
                places.append((i, 8))
                places.append((8, i))
        for place in places:
            r, c = place
            neighbors.append((r+1,c))
            neighbors.append((r-1,c))
            neighbors.append((r,c+1))
            neighbors.append((r,c-1))
        neighbors = self.board.removeDuplicates(neighbors)
        for word in words:
            for neighbor in neighbors:
                rIndex, cIndex = neighbor
                for direc in ['A', 'D']:
                    newBoard = self.board.clone()
                    if self.playWord(word, rIndex, cIndex, direc, newBoard):
                        play = Move(word, newBoard, rIndex, cIndex, direc, prevBoard, self.rack)
                        yield play
                        continue
                        
                    newBoard = self.board.clone()
                    if self.playWordOpp(word, rIndex, cIndex, direc, newBoard):
                        play = Move(word, newBoard, rIndex, cIndex, direc, prevBoard, self.rack, revWordWhenScoring=False)
                        yield play

        words = self.board.removeDuplicates(self.gac(self.rack, 7))
        for (d, row) in enumerate(self.board.board[1:]):
            yield from self.complete(self.slotify(row[1:]), 'A', d+1, words)
            
        for (d, col) in enumerate([[row[i] for row in self.board.board[1:]] for i in range(len(self.board.board))]):
            yield from self.complete(self.slotify(col), 'D', d, words)

    def proxyBoard(self):
        return Board(copy.deepcopy(self.board.board))

    def playWord(self, word, row, col, direc, board):
        for letter in reversed(word):
            if row>15 or col>15:
                return False
            if board.board[row][col] in string.ascii_uppercase:
                return False
            board.board[row][col] = letter
            if direc=='A':
                col -= 1
            else:
                row -= 1
        if board.checkBoard(board.board):
            return True
        return False

    def playWordOpp(self, word, row, col, direc, board, skip=False):
        for letter in word:
            if row>15 or col>15:
                return False
            if board.board[row][col] in string.ascii_uppercase:
                return False
            board.board[row][col] = letter
            if direc=='A':
                col += 1
            else:
                row += 1
        if board.checkBoard(board.board):
            return True
        return False

    def gac(self, iterable, maxDepth):
        for depth in range(1, maxDepth + 1): 
            for word in itertools.permutations(iterable, depth):
                yield ''.join(word)
    
    def place(self, slot, pos, word, direc, depth):
        slot, reps = slot
        currPos = pos
        slot = list(slot)

        index = wordPos = 0
        while index < len(word):
            newPos = currPos + index
            if newPos>=len(slot):
                return False
            if slot[newPos] != '.':
                currPos += 1
                index -= 1
            else:
                #cc = (depth, currPos) if direc == 'A' else (currPos, depth)
                #if word[index] not in self.board.crosschecks[cc[0]][cc[1]]: return False
                slot[newPos] = word[index]
                if not wordPos:
                    wordPos = currPos+index
            index += 1
        wordPos += 1
        slot = ''.join(slot)

        if not all(map(self.checkWord, slot.strip('.').split('.'))):
            return False

        newBoardSlot = [reps[index] if newLetter == '.' else newLetter for (index, newLetter) in enumerate(slot)]
        newBoard = self.board.clone()
        if direc == 'A':
            newBoard.board[depth][1:] = newBoardSlot[:]
            col = wordPos
            row = depth
        else:
            for (index, row) in enumerate(newBoard.board[1:]):
                row[depth] = newBoardSlot[index]
            col = depth
            row = wordPos
        move = Move(word, newBoard, row, col, direc, self.board.clone(), self.rack, doNotScoreWord=True)
        if move.board.checkBoard(newBoard.board):
            move.getScore()
            move.getEvaluation(move.rack)
            return move
        return False
        
    def complete(self, slot, direc, depth, words):
        if depth==0:
            return []
        slotForLen = slot[0]
        if slotForLen != '...............':
            edgeFinder = [i[0] for i in enumerate(slotForLen) if i[1] !='.']
            for word in words:
                for pos in range(edgeFinder[0], edgeFinder[-1]+len(word)+2):
                    if pos-len(word) in range(len(slotForLen)):
                        if slotForLen[pos-len(word)] == '.':
                            yield self.place(slot, pos-len(word), word, direc, depth)

        #return newSlots

    def slotify(self, slot):
        slotForReps = slot
        slot = ''.join(i for i in slot)
        slot = slot.replace(' ', '.')
        for i in self.extraList:
            slot = slot.replace(i, '.')
        #print(slot)
        return slot, slotForReps


    def exchange(self):
        if len(distribution)<7:
            return []
        exchs = self.gac(self.rack, len(self.rack))
        for i in exchs:
            exch = Move(i, self.board, 0, 0, 0, self.board, self.rack, _type = 'e')
            exch.score = 0
            exch.getEvaluation(self.rack)
            yield exch

    def _run(self, file=sys.stdout):
        if file is not sys.stdout:
            file = open(file, "w")
        strategy = self.BlueprintCreator(self.generate(), self.rack)
        b = strategy.pick()
        t='p'
        
        if b is None:
            strategy.setMoves(self.exchange())
            b = strategy.pick()
            t='e'
            
        if b is None:
            print('I must pass...')
            return False
        
        if t != 'e':
            s = skips_formatted(b)
            print(s, file=file)
            print(b.row, b.col, file=file)
            print(b.score, b.valuation, file=file)
            
            self.board = b.board
            self.score += b.score
        else:
            print('Exchanging: {}\nValuation: {}'.format(b.word, b.valuation), file=file)

        for i in b.word:
            try:
                self.rack.remove(i)
            except:
                pass
        if file is not sys.stdout:
            print(self.displayBoard(self.board.board), file=file)
        else:
            self.displayBoard(self.board.board)
        self.drawTiles()
        #self.board.updateCrosschecks(b)
        return b
Esempio n. 26
0
class MainApplikacation(object):
    detected = []
    detected2 = []
    detected3 = []
    detected4 = []
    detected5 = []
    real = []
    was_covert = []
    frame_no = []
    Calibrated = None
    Substractor = None
    input = None
    camera = None
    board_config_load = True
    date = datetime.now().strftime("%Y-%m-%d-%H-%M")
    fname = "data%s"%date
    imgpoint = None
    boardpoint = None
    def write_data(self):
        print "Writing data to file"
        i = 0
        fname = self.fname
        fname += ".csv"
        while os.path.isfile(fname):
            i += 1
            fname = self.fname + '-' + str(i)+".csv"
        with open(fname, 'wb') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=',',dialect='excel',
                                    quotechar='|', quoting=csv.QUOTE_MINIMAL)
            spamwriter.writerow(['Detected','Detected2','Detected3','Detected4','Detected5', 'Reality', 'Was Covert', 'Frameno', 'Diff', 'Diff2', 'Diff3', 'Diff4', 'Diff5'])
            def calc_diff(a,b):
                i = 0
                diff = []
                for each in a:
                    try:
                        if each == b[i]:
                            diff.append(True)
                        else:
                            diff.append(False)
                    except:
                        print "For some Reasion there was an error in diff calc"
                    i += 1
                percentage = float(len([x for x in diff if x is True])) / float(len(diff))
                return diff, percentage
            diff, percentage = calc_diff(self.detected, self.real)
            print "Tip Version 1 was %s Percent correct."%(percentage * 100)
            diff2, percentage = calc_diff(self.detected2, self.real)
            print "Tip Version 2 was %s Percent correct." % (percentage * 100)
            diff3, percentage = calc_diff(self.detected3, self.real)
            print "Tip Version 3 was %s Percent correct." % (percentage * 100)
            diff4, percentage = calc_diff(self.detected4, self.real)
            print "Tip Version 4 was %s Percent correct." % (percentage * 100)
            diff5, percentage = calc_diff(self.detected5, self.real)
            print "Tip Version 5 was %s Percent correct." % (percentage * 100)
            datas = zip(self.detected, self.detected2, self.detected3, self.detected4, self.detected5, self.real,
                        self.was_covert, self.frame_no, diff,diff2, diff3, diff4, diff5)
            for each in datas:
                entry = list(each)
                # if each[0] == each[1]:
                #     entry.append(True)
                # else:
                #     entry.append(False)
                spamwriter.writerow(entry)

    
    def __init__(self, inp):
        if isinstance(inp,str):
            self.fname = inp.split('.')[0]
        self.camera = Camera(device=inp, output=self.fname)
        self.board = Board()
        camconf = "camera_config.json"
        baord_conf = "boardconfig.json"
        if os.path.isfile(camconf):
            self.camera.load_config(filename=camconf)
        else:
            self.camera.do_calibration(img=True)
            self.camera.save_config(camconf)
        if self.board_config_load and os.path.isfile(baord_conf):
            with open(baord_conf, 'r') as bc:
                imgps = json.loads(bc.readline())

            self.Calibrated = BoardCalibrator(camera=self.camera, imgpts=imgps, board=self.board)
        else:
            self.Calibrated = BoardCalibrator(camera=self.camera)
            with open("boardconfig.json", 'w') as bc:
                imgps = self.Calibrated.imgpoints
                bc.write(json.dumps(imgps))
        self.Substractor = BackgroundSubtractor(c1=inp,camera=self.camera)
        plt.ion()
        self.figure = plt.figure()
        self.plt1 = self.figure.add_subplot(111)
        self.line1, = self.plt1.plot(range(200), [0] * 200, 'r.-')
        self.plt1.axis([0, 200, 0, 10000])
        cv2.namedWindow("Current", cv2.WINDOW_NORMAL)
        cv2.moveWindow("Current", 20,20)
        cv2.namedWindow("Original", cv2.WINDOW_NORMAL)
        cv2.moveWindow("Original", 20, 500)
        cv2.namedWindow("Points", cv2.WINDOW_NORMAL)
        cv2.moveWindow("Current", 1000, 20)
        cv2.namedWindow("Blobimg", cv2.WINDOW_NORMAL)
        cv2.setMouseCallback("Points", self._click)
        mixer.init()
        mixer.music.load('beep.mp3')
        # cv2.namedWindow("FG Substraction", cv2.WINDOW_NORMAL)
        # cv2.createTrackbar("History", "Current", self.history, 1000, self._set_history)
        # cv2.createTrackbar("Shadow Treshold", "Current", int(self.shad_tresh * 100), 100, self._set_shad_tresh)
        # cv2.createTrackbar("VarThreshold", "Current", self.var_tresh, 100, self._set_var_tresh)
        # cv2.createTrackbar("VarMax", "Current", self.var_max, 100, self._set_var_max)
        # cv2.createTrackbar("VarMin", "Current", self.var_min, 100, self._set_var_min)

        self.Substractor.start()

        realboard = np.zeros((self.camera.height, self.camera.width, 3), np.uint8)
        # self.frame = self.camera.undistort_image(img)
        for i in self.Calibrated.imp:
            try:
                realboard[i[0][1], i[0][0]] = [0,0,255]
            except IndexError:
                pass

        added = 0
        while True:
            img = self.Substractor.get_image()
            if img is not None:

                img = cv2.add(realboard,img)
                cv2.imshow("Original", img)
                cv2.imshow("Points", self.board.draw_board())
                if self.Substractor.stopped:
                    self.write_data()
                    exit()
                cv2.imshow("Current", self.Substractor.get_substracted())
                storage, unaltered = self.Substractor.get_storage()
                y = [x[2] for x in storage]
                y = unaltered
                self.line1.set_xdata(range(len(y)))
                self.line1.set_ydata(y)
                k = cv2.waitKey(1)
                if k == ord('a'):
                    self.add_dart(frame_no=self.camera.read_frame_no)
                if k == ord('s'):
                    self.write_data()
                if k == ord('w'):
                    pass
                    self.figure.savefig(r"thesisimages/plot.jpg")
                if k == ord('f'):
                    added = 0
                    self.Substractor.clear_arrows()
                if k == 27:
                    self.Substractor.stopped = True
                    break
                if k == 119:
                    print "Pressed w Key so Waiting"
                    cv2.waitKey(-1)
            arrows = self.Substractor.get_arrows()
            i = 1
            for each in arrows:
                tip = each.tip
                frame_no = each.frame_no
                points = self.Calibrated.calculate_points(tip)
                if i > added:
                    self.add_dart(arrow=each, detected=points, frame_no=frame_no)
                    added += 1
                i += 1
            if added >= 3:
                added = 0
                self.Substractor.clear_arrows()
        self.write_data()

    def _click(self, event, x, y, flags, param):

        if event == cv2.EVENT_LBUTTONDOWN:
            nx = x - self.board.size / 2
            ny = self.board.size / 2 - y
            print("Clicked %s " % self.board.calculate_field([[nx],[ny]]))
            self.imgpoint = [x, y]
            self.boardpoint = [[nx],[ny]]
            # self.imgpoints.append([x, y])

    def add_dart(self, arrow=None, detected="N/D", frame_no=0):
        self.Substractor.paused = True
        # mixer.music.play()
        if arrow is not None:
            print "Ratio is %s"%arrow.ratio
            print [cv2.contourArea(x) for x in arrow.contours]
            points = self.Calibrated.calculate_points(arrow.tip)
            pimg = self.board.draw_field(points)
            cv2.imshow("Points", pimg)
            cv2.imshow("Blobimg", arrow.img)
            k = -1
            while k not in [13, 32]or self.boardpoint is None:
                k = cv2.waitKey(-1)
            if k == 13:
                print "Enter"
                print len(self.detected)
                self.was_covert.append(False)
            if k == 32:
                self.was_covert.append(True)
            self.real.append(self.board.calculate_field(self.boardpoint))
            self.boardpoint = None
Esempio n. 27
0
    def __init__(self, inp):
        if isinstance(inp,str):
            self.fname = inp.split('.')[0]
        self.camera = Camera(device=inp, output=self.fname)
        self.board = Board()
        camconf = "camera_config.json"
        baord_conf = "boardconfig.json"
        if os.path.isfile(camconf):
            self.camera.load_config(filename=camconf)
        else:
            self.camera.do_calibration(img=True)
            self.camera.save_config(camconf)
        if self.board_config_load and os.path.isfile(baord_conf):
            with open(baord_conf, 'r') as bc:
                imgps = json.loads(bc.readline())

            self.Calibrated = BoardCalibrator(camera=self.camera, imgpts=imgps, board=self.board)
        else:
            self.Calibrated = BoardCalibrator(camera=self.camera)
            with open("boardconfig.json", 'w') as bc:
                imgps = self.Calibrated.imgpoints
                bc.write(json.dumps(imgps))
        self.Substractor = BackgroundSubtractor(c1=inp,camera=self.camera)
        plt.ion()
        self.figure = plt.figure()
        self.plt1 = self.figure.add_subplot(111)
        self.line1, = self.plt1.plot(range(200), [0] * 200, 'r.-')
        self.plt1.axis([0, 200, 0, 10000])
        cv2.namedWindow("Current", cv2.WINDOW_NORMAL)
        cv2.moveWindow("Current", 20,20)
        cv2.namedWindow("Original", cv2.WINDOW_NORMAL)
        cv2.moveWindow("Original", 20, 500)
        cv2.namedWindow("Points", cv2.WINDOW_NORMAL)
        cv2.moveWindow("Current", 1000, 20)
        cv2.namedWindow("Blobimg", cv2.WINDOW_NORMAL)
        cv2.setMouseCallback("Points", self._click)
        mixer.init()
        mixer.music.load('beep.mp3')
        # cv2.namedWindow("FG Substraction", cv2.WINDOW_NORMAL)
        # cv2.createTrackbar("History", "Current", self.history, 1000, self._set_history)
        # cv2.createTrackbar("Shadow Treshold", "Current", int(self.shad_tresh * 100), 100, self._set_shad_tresh)
        # cv2.createTrackbar("VarThreshold", "Current", self.var_tresh, 100, self._set_var_tresh)
        # cv2.createTrackbar("VarMax", "Current", self.var_max, 100, self._set_var_max)
        # cv2.createTrackbar("VarMin", "Current", self.var_min, 100, self._set_var_min)

        self.Substractor.start()

        realboard = np.zeros((self.camera.height, self.camera.width, 3), np.uint8)
        # self.frame = self.camera.undistort_image(img)
        for i in self.Calibrated.imp:
            try:
                realboard[i[0][1], i[0][0]] = [0,0,255]
            except IndexError:
                pass

        added = 0
        while True:
            img = self.Substractor.get_image()
            if img is not None:

                img = cv2.add(realboard,img)
                cv2.imshow("Original", img)
                cv2.imshow("Points", self.board.draw_board())
                if self.Substractor.stopped:
                    self.write_data()
                    exit()
                cv2.imshow("Current", self.Substractor.get_substracted())
                storage, unaltered = self.Substractor.get_storage()
                y = [x[2] for x in storage]
                y = unaltered
                self.line1.set_xdata(range(len(y)))
                self.line1.set_ydata(y)
                k = cv2.waitKey(1)
                if k == ord('a'):
                    self.add_dart(frame_no=self.camera.read_frame_no)
                if k == ord('s'):
                    self.write_data()
                if k == ord('w'):
                    pass
                    self.figure.savefig(r"thesisimages/plot.jpg")
                if k == ord('f'):
                    added = 0
                    self.Substractor.clear_arrows()
                if k == 27:
                    self.Substractor.stopped = True
                    break
                if k == 119:
                    print "Pressed w Key so Waiting"
                    cv2.waitKey(-1)
            arrows = self.Substractor.get_arrows()
            i = 1
            for each in arrows:
                tip = each.tip
                frame_no = each.frame_no
                points = self.Calibrated.calculate_points(tip)
                if i > added:
                    self.add_dart(arrow=each, detected=points, frame_no=frame_no)
                    added += 1
                i += 1
            if added >= 3:
                added = 0
                self.Substractor.clear_arrows()
        self.write_data()
Esempio n. 28
0
from utils import checkBoardStatus, Board

initState = ("0 1 2 " "0 1 2 " "0 1 0")

b = Board(initState, 1)
print(checkBoardStatus(b, 1))
Esempio n. 29
0
 def setUp(self):
     self.board = Board()
     self.strat = rl.RLStrat(0.01)
     self.strat.start_game(CellState.PLAYER_X)
Esempio n. 30
0
class BoardCalibrator(object):
    imgpoints = []

    def __init__(self, input=0, camera=None, imgpts=None, board=None):
        if not isinstance(camera, Camera):
            camera = Camera(device=input)

        self.camera = camera
        self.frame,reseted  = self.camera.get_image()

        if board is None:
            self.board = Board()
        else:
            self.board = board
        allobj = self.board._get_configs()
        [i.append(0) for i in allobj]
        nobj = np.array(allobj, np.float64)
        if imgpts is None:
            cv2.namedWindow("Calibration Window", cv2.WINDOW_NORMAL)
            cv2.namedWindow("Calibration Hint", cv2.WINDOW_NORMAL)
            cv2.imshow("Calibration Window", self.frame)
            cv2.waitKey(1)
            config_points = nobj
            cv2.setMouseCallback("Calibration Window", self.click)
            pos = 0
            for i in config_points:
                print ("Select field %s please. Accept with any key." % str(i))
                hintim = self.board.get_config_hint(pos)
                cv2.imshow("Calibration Hint", hintim)
                k = cv2.waitKey(-1) & 0xFF
                self.imgpoints.append(self.imgpoint)
                if k == 27:
                    print("Escaped and closing.")
                    break
                else:
                    print("Thank you")
                    pos += 1

        else:
            self.imgpoints = imgpts

        print("Imagepoints %s" % self.imgpoints)
        print("Objp %s" % nobj)

        print(self.camera.config['dist'])
        print(np.array(self.camera.config['mtx']))
        _, rvec, tvec = cv2.solvePnP(nobj,
                                     np.array(self.imgpoints, np.float64), np.array(self.camera.config['mtx']),
                                     np.array(self.camera.config['dist']), None,None, False, cv2.SOLVEPNP_ITERATIVE)
        mean_error = 0
        imgpoints2, _ = cv2.projectPoints(nobj, rvec, tvec, self.camera.cameramatrix, self.camera.config['dist'])
        impoints = np.array([[x] for x in self.imgpoints], np.float64)
        error = cv2.norm(impoints, imgpoints2, cv2.NORM_L2) / len(imgpoints2)
        mean_error += error

        print "total error: ", mean_error
        outers = self.board.get_radius()
        def calcy(x,r):
            return np.sqrt(np.power(r,2)-np.power(x,2))

        points = []
        for outer in outers:
            xs = [i*0.1 for i in range(0,int(outer*10))]
            xs += [i*-0.1 for i in range(0,int(outer*10))]
            for i in xs:
                y = calcy(i,int(outer))
                points.append([[i],[y],[0]])
                points.append([[i], [-y], [0]])
        points = np.array(points)
        # points = np.array([[[0],[0],[0]], [[outer],[0],[0]]])
        imp, jac = cv2.projectPoints(points, rvec,tvec, np.array(self.camera.config['mtx']), np.array(self.camera.config['dist']))
        rot, _ = cv2.Rodrigues(rvec)
        rev = projectReverse(self.imgpoints,rot, tvec, self.camera.config['mtx'])
        self.rot = rot
        self.tvec = tvec
        # b.draw_board_to_frame(frame2)
        print("Imagepoints %s" % self.imgpoints)
        print("Objecpoints %s" % rev)
        cv2.destroyAllWindows()
        self.imp = imp
        # cv2.setMouseCallback("Calibration Window", self._calcObj)
        # while True:
        #     self.frame,reseted  = self.camera.get_image()
        #     self.frame = self.camera.undistort_image(self.frame)
        #     for i in imp:
        #         try:
        #             self.frame[i[0][1], i[0][0]] = [0,0,255]
        #         except IndexError:
        #             pass
        #     # self.frame = cv2.circle(self.frame,(int(np.round(imp[0][0][0])), int(np.round(imp[0][0][1]))),int(np.round(dist)),[0,0,255],1)
        #     cv2.imshow("Calibration Window", self.frame)
        #     k = cv2.waitKey(1) & 0xFF
        #     if k == 27:
        #         break
        #
        # k = cv2.waitKey(-1) & 0xFF
    def calculate_points(self, point):
        x,y = point
        objp = projectReverse(np.array([[[x],[y]]]), self.rot, self.tvec,self.camera.config['mtx'])
        return self.board.calculate_field(objp[0][:2])

    def _calcObj(self, event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            print("Clicked %s: %s" % (x, y))

            objp = projectReverse(np.array([[[x],[y]]]), self.rot, self.tvec, self.camera.config['mtx'])
            print "Object Point %s"%objp
            print "Field: %s" %self.board.calculate_field(objp[0][:2])


    def click(self, event, x, y, flags, param):

        if event == cv2.EVENT_LBUTTONDOWN:
            print("Clicked %s: %s" % (x, y))
            self.imgpoint = [x,y]
            # self.imgpoints.append([x, y])

    def _get_line_in_pic(self, points):
        x_coords, y_coords = zip(*points)
        # print (x_coords)
        # print (y_coords)
        A = vstack([x_coords, ones(len(x_coords))]).T
        m, c = lstsq(A, y_coords)[0]
        x1 = (0 - c) / m
        # print ("x: %s , y: %s" % (x1, 0))
        x2 = (height - c) / m
        # print("x: %s , y: %s" % (x2, height))
        return x1, x2

    def _make_rotation_transformation(self, angle, origin=(0, 0)):
        cos_theta, sin_theta = math.cos(angle), math.sin(angle)
        x0, y0 = origin

        def xform(point):
            x, y = point[0] - x0, point[1] - y0
            return (x * cos_theta - y * sin_theta + x0,
                    x * sin_theta + y * cos_theta + y0)

        return xform

    def _rotate_point(self, point, rangle):
        b = point[1]  # hieght
        # print("a: %s" % b)
        a = point[0]  #
        # print("b %s" % a)
        angle = math.atan(a / b)
        # print("angle %s" % math.degrees(angle))
        dangle = math.degrees(angle)
        c = b / math.cos(angle)
        # print ("c %s" % c)
        ndangle = dangle + rangle
        nangle = math.radians(ndangle)
        na = math.sin(nangle) * c
        # print("New a %s" % na)
        nb = math.cos(nangle) * c
        # print("New b %s" % nb)
        return na, nb
Esempio n. 31
0
 def setUp(self):
     self.board = Board()
     self.board.board[0][0] = CellState.PLAYER_X
     self.board.board[0][1] = CellState.PLAYER_X
Esempio n. 32
0
 def setUp(self):
     self.board = Board()
Esempio n. 33
0
                    move_stats[depth] = (child[1].pos, evaluation)

            beta = min(beta, evaluation)
            if beta <= alpha:
                break
        return minEval


if __name__ == "__main__":

    move_stats = dict()

    time_taken = []

    t1 = time.time()
    game = Board()
    move = None
    move_str = None
    best_move = None
    start_time = None
    with open('move_count_vsHuman.txt', 'w') as file:
        file.write(str(0))

    difficulty = None
    try:
        difficulty = int(input("Enter difficulty level (1-5): "))
        if difficulty > 5:
            raise ValueError()
    except ValueError:
        print("Please specify an integer in the range 1-5.")
        exit(0)
Esempio n. 34
0
 def proxyBoard(self):
     return Board(copy.deepcopy(self.board.board))