示例#1
0
def children_generator(node):
    if node.turn:
        moves = list_moves(node.view)
        for move in moves:
            yield update_node_1(node, move), move
    else:
        for position in node.possible:
            view = create_view(position)
            new_possible = update_possible(node.possible, False, view)
            moves = list_moves(position, False)
            for move in moves:
                yield update_node_2(node, create_view(update_position(position, move, False)), new_possible), move
示例#2
0
def update_possible(possible, after_move, view):
    new_possible = set()
    if after_move:
        for position in possible:
            moves = list_moves(position, False)
            for move in moves:
                new_position = update_position(position, move, False)
                new_view = create_view(new_position)
                if view == new_view:
                    new_possible.add(new_position)
    else:
        for position in possible:
            new_view = create_view(position)
            if view == new_view:
                new_possible.add(position)
    return frozenset(new_possible)
示例#3
0
def flag(game_id, x, y):
    """
    Place a flag in a cell in a game.
    ---
    tags:
      - game
    parameters:
      - in: path
        name: game_id
        description: Id of the game to check a cell in.
        required: true
        type: string
      - in: path
        name: x
        description: X coordinate of the cell to place the flag.
        required: true
        type: integer
      - in: path
        name: y
        description: Y coordinate of the cell to place the flag.
        required: true
        type: integer
    responses:
      200:
        description: Game
        schema:
          $ref: '#/definitions/Game'
    """
    game = games_col.find_one({'_id': ObjectId(game_id)})
    if not game:
        abort(404)
    flag_cell(game, int(x), int(y))
    games_col.replace_one({'_id': ObjectId(game_id)}, game)
    return dumps(create_view(game))
示例#4
0
def lookup_technologies(data_dir, fname):
    subdir = os.path.split(fname)[0]
    pos_file = os.path.join(data_dir, 'pos', subdir, "%s.pos.lif" % subdir)
    tex_file = os.path.join(data_dir, 'tex', subdir, "%s.lup.lif" % subdir)
    ensure_directory(tex_file)
    lif = Container(pos_file).payload
    lif_tex = LIF(json_object=lif.as_json())
    pos_view = lif.get_view('v2')
    tex_view = create_view('tex', 'Technology', 'dtriac-pipeline:lookup.py')
    lif_tex.views = [tex_view]
    tokens = [a for a in pos_view.annotations if a.type.endswith('Token')]
    _lookup_technologies_in_tokens(lif, tokens, tex_view)
    lif_tex.write(fname=tex_file, pretty=True)
示例#5
0
def static_evaluation(node):
    position = next(iter(node.possible))
    if len(find_piece(position, "K")) == 0:
        win_lose_score = -2000
    elif len(find_piece(position, "k")) == 0:
        win_lose_score = 2000
    else:
        win_lose_score = 0

    my_knights = len(find_piece(position, "N"))
    opponent_knights = len(find_piece(position, "n"))
    material_score = my_knights - opponent_knights

    # visibility score
    if node.turn:
        my_visibility_score = -len(find_piece(node.view, "#"))
        opponent_visibility_scores = []
        for position in node.possible:
            opponent_view = create_view(position, False)
            opponent_visibility_scores.append(-len(find_piece(node.view, "#")))
        opponent_visibility_score = sum(opponent_visibility_scores)/len(opponent_visibility_scores)
    else:
        my_visibility_scores = []
        opponent_visibility_scores = []
        for position in node.possible:
            my_view = create_view(position, True)
            my_visibility_scores.append(-len(find_piece(my_view, "#")))

            opponent_view = create_view(position, False)
            opponent_visibility_scores.append(-len(find_piece(opponent_view, "#")))

        my_visibility_score = sum(my_visibility_scores)/len(my_visibility_scores)
        opponent_visibility_score = sum(opponent_visibility_scores)/len(opponent_visibility_scores)

    visibility_score = my_visibility_score - opponent_visibility_score

    return additivetuple((win_lose_score, material_score, visibility_score))
示例#6
0
def get_game(game_id):
    """
    Fetch a Game
    ---
    tags:
      - game
    parameters:
      - in: path
        name: game_id
        description: Id of the game to fetch.
        required: true
        type: string
    responses:
      200:
        description: Game
        schema:
          $ref: '#/definitions/Game'
    """
    game = games_col.find_one({'_id': ObjectId(game_id)})
    if not game:
        abort(404)
    return dumps(create_view(game))
示例#7
0
def check(game_id, x, y):
    """
    Try to reveal a cell in a game.
    If the cell is flagged this operation is ignored.
    If it has a mine the cell will explode.
    ---
    tags:
      - game
    parameters:
      - in: path
        name: game_id
        description: Id of the game to check a cell in.
        required: true
        type: string
      - in: path
        name: x
        description: X coordinate of the cell to check.
        required: true
        type: integer
      - in: path
        name: y
        description: Y coordinate of the cell to check.
        required: true
        type: integer
    responses:
      200:
        description: Game
        schema:
          $ref: '#/definitions/Game'
    """
    game = games_col.find_one({'_id': ObjectId(game_id)})
    if not game:
        abort(404)
    check_cell(game, int(x), int(y))
    games_col.replace_one({'_id': ObjectId(game_id)}, game)
    return dumps(create_view(game))
示例#8
0
from utils import (start_position, update_position, create_view,
                   print_position)
import engine
from tqdm import tqdm
from time_limit import time_limit

ended = False
current_position = start_position
possible = frozenset({start_position})

while not ended:

    # show the current view
    view = create_view(current_position, False)
    print_position(view)

    # take user input
    inp = input("select piece\n")
    begin = tuple(int(i) for i in inp.split(","))
    inp = input("select target\n")
    end = tuple(int(i) for i in inp.split(","))
    user_move = [begin, end]

    # play the user move
    current_position = update_position(current_position, user_move, False)

    # show the current view
    view = create_view(current_position, False)
    print_position(view)

    # update the information of the computer
示例#9
0
    elif value >= beta:
        new_entry = TableEntry(value=value,
                               principal_variation=principal_variation,
                               depth=depth,
                               flag=-1)
    else:
        new_entry = TableEntry(value=value,
                               principal_variation=principal_variation,
                               depth=depth,
                               flag=0)
    lookup_table[node] = new_entry

    return value, principal_variation


def iterative_deepening(node, max_depth=float("inf")):
    depth = 0
    t0 = time()
    while depth <= max_depth:
        score, principal_variation = minimax(node, depth)
        print("score", score, "at depth", depth, "in", time()-t0, "seconds")
        depth += 1


if __name__ == "__main__":

    # simple test
    node = Node(possible=frozenset({start}),
                view=create_view(start),
                turn=True)
    iterative_deepening(node, 5)
示例#10
0
def post_game():
    """
    Create a new game
    ---
    tags:
      - game
    definitions:
      - schema:
          id: Game
          properties:
            id:
             type: string
             description: Unique identifier of the game
            status:
             type: string
             description: Any of playing, win or lost.
            board:
             type: array
             items:
              type: object
              properties:
                has_mine:
                  type: boolean
                  description: Indicates if there is a mine in this cell
                exploded:
                  type: boolean
                  description: Indicates if there is this cell has exploded.
                revealed:
                  type: boolean
                  description: Indicates if there is this cell has revealed.
                flagged:
                  type: boolean
                  description: Indicates if there is this cell has been flagged.
                value:
                  type: integer
                  description: After its revealed, it indicates the number of adjacent mines.
             description: 2D array of the game cells
    parameters:
      - in: body
        name: body
        schema:
          id: GameRequest
          properties:
            rows:
              type: integer
              description: Number of rows
            cols:
              type: integer
              description: Number of cols
            mines:
              type: integer
              description: Number of mines (not to exceed 50% ratio)
    responses:
      200:
        description: Game created
        schema:
          $ref: '#/definitions/Game'
    """
    params = request.json
    check_create_params(params)
    new_game = {
        'rows': params.get('rows', DEFAULT_ROWS) if params else DEFAULT_ROWS,
        'cols': params.get('cols', DEFAULT_COLS) if params else DEFAULT_COLS,
        'mines':
        params.get('mines', DEFAULT_MINES) if params else DEFAULT_MINES,
        'status': 'playing'
    }
    validate_game(new_game)
    generate_board(new_game)
    add_mines(new_game)
    calculate_value(new_game)
    games_col.insert_one(new_game)
    return dumps(create_view(new_game))