Esempio n. 1
0
    def print_visits(self, childern):
        print('**************************************************')

        print('    '.join(self._column_indicator))

        for row in range(1, self._board_size + 1):
            pieces = []
            for col in range(1, self._board_size + 1):
                pieces.append('{:4d}'.format(
                    childern.get(Point(row, col)).num_visits if childern.
                    get(Point(row, col)) is not None else 0))
            print('%02d %s' % (row, ' | '.join(pieces)))
Esempio n. 2
0
def select_move(bot_name):

    bot_agent = AlphaZeroAgent(Connect5Game.ASSIGNED_PLAYER_ID_2,
                               "Agent_New",
                               encoder,
                               model_new,
                               az_mcts_round_per_moves,
                               c_puct,
                               az_mcts_temperature,
                               device=device)
    human_agent = HumanPlayer(Connect5Game.ASSIGNED_PLAYER_ID_1,
                              "HumanPlayerX")

    board = Board(board_size)
    players = {}
    players[bot_agent.id] = bot_agent
    players[human_agent.id] = human_agent

    start_game_state = GameState(board, human_agent.id, None)

    game = Connect5Game(start_game_state, [bot_agent.id, human_agent.id],
                        number_of_planes, False)

    historic_jboard_positions = [
        point_from_coords([move][0]) for move in (request.json)['moves']
    ]
    historic_moves = [
        Move(Point(historic_jboard_position.row, historic_jboard_position.col))
        for historic_jboard_position in historic_jboard_positions
    ]
    over = False
    bot_move_str = ''

    for move in historic_moves:
        game.apply_move(move)

    if game.is_over():
        over = True
    else:
        bot_move = bot_agent.select_move(game)
        game.apply_move(bot_move)
        game.working_game_state.board.print_board()
        jboard_postion = Point(bot_move.point.row, bot_move.point.col)
        bot_move_str = coords_from_point(jboard_postion)
        over = True if game.is_over() else False

    return jsonify({
        'bot_move': bot_move_str,
        'over': over,
        'diagnostics': None
    })
Esempio n. 3
0
 def _check_right_diagonal_win(board, player):
     for row in range(1, board.board_size + 1 - 4):
         for col in range(1, board.board_size + 1 - 4):
             if board.get_piece_at_point(Point(
                     row,
                     col)).owner_id == player and board.get_piece_at_point(
                         Point(row + 1, col + 1)
                     ).owner_id == player and board.get_piece_at_point(
                         Point(row + 2, col + 2)
                     ).owner_id == player and board.get_piece_at_point(
                         Point(row + 3, col + 3)
                     ).owner_id == player and board.get_piece_at_point(
                         Point(row + 4, col + 4)).owner_id == player:
                 return True
     return False
Esempio n. 4
0
 def _check_horizontal_win(board, player):
     for col in range(1, board.board_size + 1 - 4):
         for row in range(1, board.board_size + 1):
             if board.get_piece_at_point(Point(
                     row,
                     col)).owner_id == player and board.get_piece_at_point(
                         Point(row, col + 1)
                     ).owner_id == player and board.get_piece_at_point(
                         Point(row, col + 2)
                     ).owner_id == player and board.get_piece_at_point(
                         Point(row, col + 3)
                     ).owner_id == player and board.get_piece_at_point(
                         Point(row, col + 4)).owner_id == player:
                 return True
     return False
Esempio n. 5
0
    def encode(self, boards, player_in_action, previous_move=None):
        '''
        The input to the neural network is a 19 × 19 × 17 image stack comprising num_plane*2+1 binary feature planes.
        num_plane feature planes Xt consist of binary values indicating the presence of the current player’s stones
        (Xt(i)= 1 if intersection i contains a stone of the player’s colour at time-step t; 0 if the intersection is
        empty, contains an opponent stone, or if t < 0). A further 8 feature planes, Yt, represent the corresponding 
        features for the opponent’s stones. The final feature plane, C, represents the colour to play, and has a constant
        value of either 1 if black is to play or 0 if white is to play.  These planes are concatenated together to give 
        input features st = [Xt,Yt, Xt−1, Yt−1, ..., Xt−7, Yt−7, C].  

        Refer to: Mastering the Game of Go without Human Knowledge
        '''

        board_matrix = np.zeros(self.shape(), dtype=int)
        for plane in range(len(boards)):
            for row in range(self._board_height):
                for col in range(self._board_width):
                    point = Point(row + 1, col + 1)
                    piece = boards[plane].get_piece_at_point(point)
                    if piece.owner_id != -1:
                        if piece.owner_id == player_in_action:
                            board_matrix[plane * 2 + 1, row, col] = 1
                        else:
                            board_matrix[plane * 2, row, col] = 1

        for row in range(self._board_height):
            for col in range(self._board_width):
                board_matrix[self._num_plane * 2, row, col] = player_in_action

        return board_matrix
Esempio n. 6
0
def main():
    root = Tk()
    myframe = Frame(root)
    myframe.pack(fill=BOTH, expand=YES)
    mycanvas = ResizingCanvas(myframe,
                              width=850,
                              height=400,
                              bg="white",
                              highlightthickness=0)
    mycanvas.pack(fill=BOTH, expand=YES)

    start_point = Point(50, 0)
    kline = KLineElem(100, 300, 400, 5)
    mycanvas.CreateOneKLine(start_point, kline)

    start_point.x += 12
    kline = KLineElem(300, 100, 400, 5)
    mycanvas.CreateOneKLine(start_point, kline)

    # to do here
    kline_elem_list = KLineAPI.GetKLineData("15min", 10, "btcusdt")

    # tag all of the drawn widgets
    mycanvas.addtag_all("all")
    root.mainloop()
Esempio n. 7
0
 def moove_user(self, user):
     for mouvement in constante.POSSIBLE_MOUVEMENT:
         X = user.X + mouvement.X
         Y = user.Y + mouvement.Y
         case = self.cases[X][Y]
         case.lock()
         if self.can_moove(X, Y):
             current_case = self.cases[user.X][user.Y]
             current_case.lock()
             current_case.value = constante.EMPTY
             if not case.value == constante.EXIT:
                 case.value = constante.PEOPLE
             case.unlock()
             current_case.unlock()
             self.cases[user.X][user.Y].unlock()
             if not case.value == constante.EXIT:
                 self.update_graphique(user, X, Y)
                 user.X = X
                 user.Y = Y
             else:
                 self.users.remove(user)
                 if len(self.users) <= 0:
                     self.events[0].clear()
                 self.cpt -= 1
                 if self.draw_is_enable:
                     self.drawer.remove_user(Point(user.X, user.Y))
             return
Esempio n. 8
0
 def get_valid_position(self):
     while True:
         random_point = Point(random.randint(0, 511),
                              random.randint(0, 127))
         if self.map.cases[random_point.X][
                 random_point.Y].value == constante.EMPTY:
             return random_point
Esempio n. 9
0
    def encode(self, boards, player_in_action, previous_move=None):
        board_matrix = np.zeros(self.shape(), dtype=int)

        # The previous number of planes
        for plane in range(len(boards)):
            for row in range(self._board_height):
                for col in range(self._board_width):
                    point = Point(row + 1, col + 1)
                    piece = boards[plane].get_piece_at_point(point)
                    if piece.owner_id != -1:
                        if piece.owner_id == player_in_action:
                            board_matrix[plane * 2 + 1, row, col] = 1
                        else:
                            board_matrix[plane * 2, row, col] = 1

        #  the  last move
        for row in range(self._board_height):
            for col in range(self._board_width):
                flag = 0
                if previous_move is not None and row == previous_move.point.row - 1 and col == previous_move.point.col - 1:
                    flag = 1

                board_matrix[self._num_plane * 2, row, col] = flag

        #  the  player who will play in the next move
        for row in range(self._board_height):
            for col in range(self._board_width):
                board_matrix[self._num_plane * 2 + 1, row,
                             col] = player_in_action

        return board_matrix
Esempio n. 10
0
 def get_w(self):
     w = Point(0, 0)
     lam, x = self.alpha, self.train_data
     for i in range(len(x)):
         y = 1 if x[i].class_id == 1 else -1
         w += x[i].mul_scalar(lam[i] * y)
     return w
Esempio n. 11
0
def read_points(file_name):
    points = []
    with open(file_name, encoding="mbcs") as csv_file:
        rows = csv.reader(csv_file, delimiter=';')
        for row in rows:
            if len(row) != 0:
                points.append(Point(row[0], row[1]))
    return points
Esempio n. 12
0
 def encode(self, boards, player_in_action, previous_move=None):
     board_matrix = np.zeros(self.shape(), dtype=int)
     for plane in range(len(boards)):
         for row in range(self._board_height):
             for col in range(self._board_width):
                 point = Point(row+1, col+1)
                 piece = boards[plane].get_piece_at_point(point)
                 if piece.owner_id != -1:
                     board_matrix[plane, row, col] = piece.owner_id
     return board_matrix
Esempio n. 13
0
 def init_users(self):
     users = []
     for i in range(self.nb_personne):
         point = self.get_valid_position()
         users.append(
             User(point.X, point.Y,
                  User.POSSIBLE_COLOR[random.randint(0, 3)]))
         if self.draw_is_enable:
             self.drawer.add_user(Point(users[i].X, users[i].Y),
                                  users[i].color)
     return users
Esempio n. 14
0
    def print_board(self):
        print('**************************************************')

        print(' '.join(self._column_indicator))

        for row in range(1, self._board_size + 1):
            pieces = []
            for col in range(1, self._board_size + 1):
                piece = self.get_piece_at_point(Point(row, col))
                pieces.append(str(piece.owner_id)
                              ) if piece.owner_id != -1 else pieces.append(' ')
            print('%02d %s' % (row, ' | '.join(pieces)))
Esempio n. 15
0
def _get_tree_count(input_file, slopes):
    slope_tree_count = []
    grid = _create_grid_with_values(input_file)
    for slope in slopes:
        position = Point(x=0, y=0)
        tree_count = 0
        while position.y < len(grid):
            if _get_value_at_point(grid, position.x, position.y) == '#':
                tree_count += 1
            position.x += slope[0]
            position.y += slope[1]
        slope_tree_count.append(tree_count)
    print(slope_tree_count)
    return math.prod(slope_tree_count)
Esempio n. 16
0
def point_from_coords(coords):
    col_name = coords[0]
    row = int(coords[1:])
    point = Point(row + 1, Board.get_column_indicator_index(col_name) + 1)
    return point
Esempio n. 17
0
from common.point import Point

WIDTH = 512
HEIGHT = 128
EMPTY = 0
PEOPLE = 1
OBSTACLE = 2
EXIT = 3

# MOUVEMENT
NORTH = Point(0, -1)
EAST = Point(-1, 0)
NORTH_EAST = Point(-1, -1)
SOUTH_EAST = Point(-1, 1)
POSSIBLE_MOUVEMENT = [NORTH_EAST, NORTH, EAST, SOUTH_EAST]
Esempio n. 18
0
from common.point import Point
from svm_classifier import SVMClassifier
from common.score import *
from common.utils import *
from random import *

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.preprocessing import StandardScaler

with open('LinearDataset', 'r') as f:
    data = [Point(*(line.split(' '))) for line in f.readlines()]
    #data = [Point(-1, -2), Point(-1, 2), Point(1, 3, 1), Point(1, -1, 1)]
    shuffle(data)
    y = []
    for p in data:
        y.append(p.class_id)
    ratio = 0.8
    train_data, test_data = train_test_split(data, ratio)
    train_y, test_y = train_test_split(y, ratio)
    classifier = SVMClassifier()
    classifier.learn(train_data)
    result = calc_score(classifier, test_data)
    print('measure = {}'.format(result.measure()))

    figure = plt.figure(figsize=(14, 14))

    x_min, x_max = -10, 10
    y_min, y_max = -10, 10
Esempio n. 19
0
 def point_from_coords(cls, text):
     col_name = text[0]
     row = int(text[1])
     return Point(row, Board.get_column_indicator_index(col_name)+1)
Esempio n. 20
0
 def update_graphique(self, user, X, Y):
     if self.draw_is_enable:
         old_point = Point(user.X, user.Y)
         new_point = Point(X, Y)
         self.drawer.draw_user(old_point, new_point, user.color)
Esempio n. 21
0
    def CreateOneKLine(self,
                       start_point=Point(0, 0),
                       kline_elem=KLineElem(0, 0, 0, 0)):
        """
        CreateOneKLine
        :param Point: start position
        :param KLineElem: KLine data
        """
        kline_width = self._kline_width
        kline_color = None
        p1 = Point(start_point.x, start_point.y)
        p2 = Point(p1.x, 0)
        if (kline_elem.open < kline_elem.close):
            p2.y = p1.y + (kline_elem.high - kline_elem.close)
            kline_color = "red"
        else:
            p2.y = p1.y + (kline_elem.high - kline_elem.open)
            kline_color = "green"
        p3 = Point(p1.x, p2.y + abs(kline_elem.open - kline_elem.close))
        p4 = Point(p1.x, p1.y + (kline_elem.high - kline_elem.low))

        p1.Print()
        p2.Print()
        p3.Print()
        p4.Print()

        self.create_line(p1.x, p1.y, p4.x, p4.y, fill=kline_color)
        self.create_rectangle(p2.x - kline_width,
                              p2.y,
                              p3.x + kline_width,
                              p3.y,
                              fill=kline_color)
Esempio n. 22
0
 def decode_point_index(self, index):
     row = index // self._board_width
     col = index % self._board_width
     return Point(row=row+1, col=col+1)
Esempio n. 23
0
        dem.scale(args.cols, args.rows, args.csize)
        dname = os.path.split(inp_)[-1].split('.')[0]
        for r in radi:
            for i in range(args.count):
                fname = '%s%s_r%d_%d.in' % (args.prefix, dname, r, i + 1)
                fpath = os.path.join(args.output, fname)
                if os.path.exists(fpath):
                    continue
                logger.info('Generating %s' % fpath)

                # generate random bs
                center_x, center_y = np.random.uniform(
                    args.W / 5, args.W - args.W / 5), np.random.uniform(
                        args.W / 5, args.W - args.W / 5)
                center_z = estimate(center_x, center_y, dem)
                bs = Point(center_x, center_y, center_z)

                # Generate random relays
                relays = []

                for j in range(args.nr):
                    rn = None
                    while True:
                        rn = point(dem, (0, args.W), (0, args.H),
                                   z_off=args.height,
                                   cls=RelayNode,
                                   distribution=args.distribution)
                        if distance(rn, bs) <= 2 * r:
                            break
                    if distance(rn, bs) > 2 * r:
                        logger.warning(f'{r} {distance(rn, bs)}')
Esempio n. 24
0
 def _init_grid(self):
     for row in self._rows:
         for col in self._cols:
             free_point = Point(row, col)
             self._grid[free_point] = Piece(-1, free_point)
Esempio n. 25
0
from common.utils import normalize
from common.point import Point
from KNN.knn_classifier import *
from common.cross_validator import *


def optimal_k(chips):
    result = 0
    result_k = 1
    for k in range(1, min(20, len(chips))):
        cur = cross_validate(KnnClassifier(k), chips)
        print('with k = {} : result = {}'.format(k, cur.measure()))
        if cur.measure() > result:
            result = cur.measure()
            result_k = k
    return result_k


with open('chips.txt', 'r') as f:
    chips = [Point(*line.split(',')) for line in f.readlines()]
    chips = normalize(normalize(chips, 0), 1)
    shuffle(chips)
    count_to_test = len(chips) // 5
    test = chips[:count_to_test]
    chips = chips[count_to_test:]
    k = optimal_k(chips)
    classifier = KnnClassifier(k)
    classifier.learn(chips)
    result = calc_score(classifier, test)
    print('optimal k = {}, measure = {}'.format(k, result.measure()))