Ejemplo n.º 1
0
def play_game(li, game_id, engine_factory, user_profile, config):
    response = li.get_game_stream(game_id)
    lines = response.iter_lines()
    #Initial response of stream will be the full game info. Store it
    initial_state = json.loads(next(lines).decode('utf-8'))
    game = model.Game(initial_state, user_profile["username"], li.baseUrl,
                      config.get("abort_time", 20))
    board = setup_board(game)

    engineeng = engine_factory(board)

    logger.info("+++ {}".format(game))

    if is_engine_move(game, board.move_stack) and not is_game_over(game):
        move = engineeng.search(board, 5000, 5000, 1, 1)
        finalmove = switchusiuci(move)
        board.push(shogi.Move.from_usi(move))
        li.make_move(game.id, finalmove)
    while not terminated:
        try:
            binary_chunk = next(lines)
        except (StopIteration):
            break
        upd = json.loads(
            binary_chunk.decode('utf-8')) if binary_chunk else None
        u_type = upd["type"] if upd else "ping"
        if not board.is_game_over():
            if u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                board = update_board(board, moves[-1])
                if not is_game_over(game) and is_engine_move(game, moves):
                    move = engineeng.search(board, upd['wtime'], upd['btime'],
                                            upd['winc'], upd['binc'])
                    finalmove = switchusiuci(move)
                    board.push(shogi.Move.from_usi(move))
                    li.make_move(game.id, finalmove)
                if board.turn == shogi.BLACK:
                    game.ping(config.get("abort_time", 20),
                              (upd["btime"] + upd["binc"]) / 1000 + 60)
                else:
                    game.ping(config.get("abort_time", 20),
                              (upd["wtime"] + upd["winc"]) / 1000 + 60)
            elif u_type == "ping":
                if game.should_abort_now():
                    logger.info("    Aborting {} by lack of activity".format(
                        game.url()))
                    li.abort(game.id)
                    break
                elif game.should_terminate_now():
                    logger.info(
                        "    Terminating {} by lack of activity".format(
                            game.url()))
                    if game.is_abortable():
                        li.abort(game.id)
                    break
        else:
            logger.info("game over")
            engineeng.quit()
            break
Ejemplo n.º 2
0
def analyze_game(li, game_id, control_queue, engine_factory, user_profile,
                 config, skill_level, chess960, username):
    response = li.get_game_stream(game_id)
    lines = response.iter_lines()
    line0 = next(lines)
    print("line0 =", line0)
    while len(line0) == 0:
        line0 = next(lines)
    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(line0.decode('utf-8')),
                      user_profile["username"], li.baseUrl,
                      config.get("abort_time", 20))
    board = setup_board(game, chess960)
    engine = engine_factory(board)

    logger.info("+++ {}".format(game))

    engine.go_commands = {"movetime": 500, "depth": 13}

    while board.move_stack:
        best_move = engine.search(board, 0, 0, 0, 0)
        stats = engine.get_info()
        li.analysis(username, game_id, len(board.move_stack),
                    "w" if board.color else "b", stats)
        board.pop()
Ejemplo n.º 3
0
def main():
    pygame.mixer.init()
    pygame.mixer.music.\
        load('music/Game of Thrones - Main Theme (Extended) HD.mp3')
    pygame.mixer.music.play(-1)
    ev_manager = controller.EventManager()
    game_view = view.GameView(ev_manager)
    game = model.Game(ev_manager)

    mouse_controller = controller.MouseController(ev_manager, game_view, game)
    mouse_controller.notify(events.TickEvent())
    cpu_spinner = controller.CPUSpinnerController(ev_manager)

    human_player = model.Player(game)
    human_player.set_name("Human")

    game.players.append(human_player)
    game.set_active_player(human_player)

    cpu_player = model.AIPlayer(game)
    cpu_player.set_name("AI Player")
    game.players.append(cpu_player)
    game.main_player = game.players[0]

    ev_manager.post(events.MenuBuildEvent())
    cpu_spinner.run()
Ejemplo n.º 4
0
def prepare_game_start(players, view_mod):
    '''
    Create the overall game object
    '''

    n_players = len(players)

    all_tiles = create_all_objects_of_type(get_number_of_plantation_tiles(),
                                           create_tile)

    all_buildings = create_all_objects_of_type(get_number_of_buildings(),
                                               create_building)

    all_goods = create_all_objects_of_type(get_number_of_goods(), create_good)
    all_colonists = (y for y in create_colonists(n_players))
    all_vp = (y for y in create_victory_points(n_players))
    all_roles = create_all_objects_of_type(get_number_of_role_cards(n_players),
                                           create_role)

    start_doubloons = n_players - 1
    # Give out money
    for player in players:
        player.doubloons = start_doubloons

    # Take indigo and give to first and second player
    players[0].recieve_island_tile(next(all_tiles['indigo']))
    players[1].recieve_island_tile(next(all_tiles['indigo']))
    if n_players == 5:
        # Third player gets indigo
        players[2].recieve_island_tile(next(all_tiles['indigo']))

    if n_players == 3:
        players[2].recieve_island_tile(next(all_tiles['corn']))
    elif n_players == 4:
        players[2].recieve_island_tile(next(all_tiles['corn']))
        players[3].recieve_island_tile(next(all_tiles['corn']))
    else:
        # five players
        players[3].recieve_island_tile(next(all_tiles['corn']))
        players[4].recieve_island_tile(next(all_tiles['corn']))

    # Fill up tiles portal
    tiles_portal = create_tiles_portal(all_tiles, n_players)
    tiles_portal.fill_display()

    colonist_portal = create_colonist_portal(n_players, all_colonists,
                                             n_players)

    cargo_ships = create_cargo_ships(n_players)
    remaining_buildings = list(it.chain.from_iterable(all_buildings.values()))
    remaining_goods = {k: list(v) for (k, v) in all_goods.items()}
    remaining_roles = list(it.chain.from_iterable(all_roles.values()))

    trading_house = mod.TradingHouse()

    game = mod.Game(players, remaining_roles, cargo_ships, colonist_portal,
                    tiles_portal, list(all_vp), remaining_buildings,
                    remaining_goods, trading_house, view_mod.Game())

    return game
Ejemplo n.º 5
0
 def __init__(self, seed=None):
     wx.Frame.__init__(self, None, -1, 'Ricochet Robot!')
     game = model.Game(seed)
     #game = model.Game.hardest()
     self.view = View(self, game)
     self.view.SetSize((800, 800))
     self.Fit()
Ejemplo n.º 6
0
    def __init__(self):

        self.game = model.Game("SQUOIDS")
        self.view = view.MainFrame(self.game, 1250, 800)
        self.audio = audio.AudioManager()

        self.initialise()
Ejemplo n.º 7
0
 def on_key_down(self, event):
     code = event.GetKeyCode()
     if code == wx.WXK_ESCAPE:
         self.GetParent().Close()
     elif code >= 32 and code < 128:
         value = chr(code)
         if value in model.COLORS:
             self.color = value
         elif value == 'S':
             self.solve()
         elif value == 'U' and self.undo:
             self.undo_move()
             self.Refresh()
         elif value == 'N':
             self.path = None
             self.undo = []
             self.lines = []
             self.game = model.Game()
             self.Refresh()
     elif self.color:
         lookup = {
             wx.WXK_UP: model.NORTH,
             wx.WXK_RIGHT: model.EAST,
             wx.WXK_DOWN: model.SOUTH,
             wx.WXK_LEFT: model.WEST,
         }
         if code in lookup:
             color = self.color
             direction = lookup[code]
             try:
                 self.do_move(color, direction)
             except Exception:
                 pass
             self.Refresh()
Ejemplo n.º 8
0
def play_game(li, game_id, weights, threads, challenge_queue):
    username = li.get_profile()["username"]
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')), username,
                      li.baseUrl)
    board = setup_board(game.state)
    engine, info_handler = setup_engine(engine_path, board, weights, threads)

    print("+++ {}".format(game.show()))

    board = play_first_move(game, engine, board, li)

    for update in updates:
        if update:
            upd = json.loads(update.decode('utf-8'))
            moves = upd.get("moves").split()
            board = update_board(board, moves[-1])

            if is_engine_move(game.is_white, moves):
                engine.position(board)
                best_move, ponder = engine.go(wtime=upd.get("wtime"),
                                              btime=upd.get("btime"),
                                              winc=upd.get("winc"),
                                              binc=upd.get("binc"))
                li.make_move(game.id, best_move)

                # print(">>> {} {}".format(game.url(), best_move))
                # get_engine_stats(info_handler)

    print("--- {} Game over".format(game.url()))
    accept_next_challenge(challenge_queue)
Ejemplo n.º 9
0
def run(mode):
    evManager = eventmanager.EventManager()
    gamemodel = model.Game(evManager)
    graphics = views.GraphicalView(evManager, gamemodel)
    keyboard = controller.Controller(evManager, gamemodel)

    gamemodel.run(mode)
Ejemplo n.º 10
0
def play_game(li, game_id, control_queue, engine_factory, user_profile,
              config):
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')),
                      user_profile["username"], li.baseUrl)
    board = setup_board(game)
    engine = engine_factory(board)
    conversation = Conversation(game, engine, li, __version__)

    print("+++ {}".format(game))

    engine.pre_game(game)

    engine_cfg = config["engine"]

    if (engine_cfg["polyglot"] == True):
        board = play_first_book_move(game, engine, board, li, engine_cfg)
    else:
        board = play_first_move(game, engine, board, li)

    try:
        for binary_chunk in updates:
            upd = json.loads(
                binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd), game)
            elif u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                board = update_board(board, moves[-1])
                if is_engine_move(game, moves):
                    best_move = None
                    if (engine_cfg["polyglot"] == True and len(moves) <=
                        (engine_cfg["polyglot_max_depth"] * 2) - 1):
                        best_move = get_book_move(board, engine_cfg)
                    if best_move == None:
                        best_move = engine.search(board, upd["wtime"],
                                                  upd["btime"], upd["winc"],
                                                  upd["binc"])
                    li.make_move(game.id, best_move)
                    game.abort_in(20)
            elif u_type == "ping":
                if game.should_abort_now() and len(game.state["moves"]) < 6:
                    print("    Aborting {} by lack of activity".format(
                        game.url()))
                    li.abort(game.id)
    except (RemoteDisconnected, ConnectionError, ProtocolError,
            HTTPError) as exception:
        print("Abandoning game due to connection error")
        traceback.print_exception(type(exception), exception,
                                  exception.__traceback__)
    finally:
        print("--- {} Game over".format(game.url()))
        engine.quit()
        # This can raise queue.NoFull, but that should only happen if we're not processing
        # events fast enough and in this case I believe the exception should be raised
        control_queue.put_nowait({"type": "local_game_done"})
Ejemplo n.º 11
0
 def __init__(self, seed=None, nrobots=5):
     wx.Frame.__init__(self, None, -1, 'Ricochet Robots!')
     assert 0 < nrobots <= 5, 'Invalid number of robots'
     game = model.Game(seed, ncolors=nrobots)
     # game = model.Game.hardest() # TODO
     self.view = View(self, game)
     self.view.SetSize((800, 800))
     self.Fit()
Ejemplo n.º 12
0
def main():
    width = 300
    height = 300

    mygame = model.Game("Rabbit Quest", width, height)
    os.environ["SDL_VIDEO_CENTERED"] = "1"
    pygame.init()
    pygame.display.set_caption("Honey's adbenture")
    FPSCLOCK = pygame.time.Clock()

    PLAYERMOVEX = 4
    PLAYERMOVEY = 10

    surface = pygame.display.set_mode((width, height))
    x = 100
    y = 100
    dx = 0
    dy = 0
    data = [x, y, 30, 30]

    loop = True

    while loop is True:

        dx = 0

        for event in pygame.event.get():

            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                    loop = False

            elif event.type == QUIT:
                loop = False

            elif event.type == KEYDOWN:
                if event.key in [K_w, K_UP]:
                    mygame.dy -= 10

        keys = pygame.key.get_pressed()

        if keys[K_d] or keys[K_RIGHT]:
            dx = PLAYERMOVEX

        elif keys[K_a] or keys[K_LEFT]:
            dx = 0 - PLAYERMOVEX

        mygame.dx += dx
        mygame.update()

        surface.fill((30, 30, 30))
        mygame.blocks.draw(surface)
        mygame.sprites.draw(surface)
        pygame.display.update()

        FPSCLOCK.tick(30)

    pygame.quit()
Ejemplo n.º 13
0
def main():
    """This is the entry point to the application."""

    # This is for text mode.

    if len(sys.argv) == 2 and sys.argv[1] == '-t':
        model.main()
        sys.exit(0)

    # Do initialization.

    pygame.init()
    screen = pygame.display.set_mode(DISPLAY_MODE)
    pygame.display.set_caption(TITLE)
    clock = pygame.time.Clock()
    background = pygame.Surface(screen.get_size()).convert()
    background.fill(BACKGROUND)
    pygame.display.flip()

    game_model = model.Game()
    board_view = view.Board(game_model)
    score_board = view.ScoreBoard(game_model)
    rendering_groups = [board_view, score_board]

    while True:

        clock.tick(FRAMES_PER_SEC)
        scheduler.tick()

        # Handle user input.

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key in (K_ESCAPE, K_q) or event.type == QUIT:
                    sys.exit(0)
                elif event.key == K_h:
                    url = "file://" + os.path.abspath(data.find("help.html"))
                    webbrowser.open(url, new=True)
                elif event.key == K_r:
                    game_model.reset()
            elif event.type == MOUSEBUTTONDOWN:
                for square_view in board_view:
                    if square_view.rect.collidepoint(*pygame.mouse.get_pos()):
                        xyz = square_view.square_model.xyz
                        try:
                            game_model.move(xyz)
                        except ValueError:
                            pass
                        break

        # Provide the simulation and render it.

        for i in rendering_groups:
            i.update()
            i.clear(screen, background)
            pygame.display.update(i.draw(screen))
Ejemplo n.º 14
0
def play_game(li, game_id, control_queue, engine_factory, user_profile, config):
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')), user_profile["username"], li.baseUrl, config.get("abort_time", 20))
    board = setup_board(game)
    engine = engine_factory(board)
    conversation = Conversation(game, engine, li, __version__)

    print("+++ {}".format(game))

    engine_cfg = config["engine"]
    polyglot_cfg = engine_cfg.get("polyglot", {})
    book_cfg = polyglot_cfg.get("book", {})

    if not polyglot_cfg.get("enabled") or not play_first_book_move(game, engine, board, li, book_cfg):
        play_first_move(game, engine, board, li)

    engine.set_time_control(game)

    try:
        for binary_chunk in updates:
            upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd), game)
            elif u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                board = update_board(board, moves[-1])
                if is_engine_move(game, moves):
                    if config.get("fake_think_time") and len(moves) > 9:
                        delay = min(game.clock_initial, game.my_remaining_seconds()) * 0.015
                        accel = 1 - max(0, min(100, len(moves) - 20)) / 150
                        sleep = min(5, delay * accel)
                        time.sleep(sleep)
                    best_move = None
                    if polyglot_cfg.get("enabled") and len(moves) <= polyglot_cfg.get("max_depth", 8) * 2 - 1:
                        best_move = get_book_move(board, book_cfg)
                    if best_move == None:
                        best_move = engine.search(board, upd["wtime"], upd["btime"], upd["winc"], upd["binc"])
                    li.make_move(game.id, best_move)
                    game.abort_in(config.get("abort_time", 20))
            elif u_type == "ping":
                if game.should_abort_now():
                    print("    Aborting {} by lack of activity".format(game.url()))
                    li.abort(game.id)
    except (RemoteDisconnected, ChunkedEncodingError, ConnectionError, ProtocolError, HTTPError) as exception:
        print("Abandoning game due to connection error")
        traceback.print_exception(type(exception), exception, exception.__traceback__)
    finally:
        print("--- {} Game over".format(game.url()))
        engine.quit()
        # This can raise queue.NoFull, but that should only happen if we're not processing
        # events fast enough and in this case I believe the exception should be raised
        control_queue.put_nowait({"type": "local_game_done"})
Ejemplo n.º 15
0
def index():
    hash = _generate_hash()
    events = []
    events.append((0, time.time(), 'Game {} started.'.format(hash)))
    events.append(ev_level(1))
    g = model.Game(hash=hash, level=1, events=json.dumps(events), shots=6)
    db.session.add(g)
    db.session.commit()
    encache(g)
    return flask.redirect('/i/' + hash)
Ejemplo n.º 16
0
    def create_game(self, host_name, sid):
        game = model.Game()
        player = model.Player(name=host_name, sid=sid, game=game)
        player.games.append(game)
        game.host = player

        db.session.add(game)
        db.session.add(player)

        return game
Ejemplo n.º 17
0
	def __init__(self, root):

		super().__init__()

		self.root = root
		self.game = model.Game(NBR_ROWS, NBR_COLS)
		self.game_board = self.game.get_board()

		self.root.geometry("600x600")
		self._reversi = reversi.Reversi(self.game, self.root, HEIGHT, WIDTH)
		self.window = self._reversi.get_board()
		self.initUI()
		self.initGame()
Ejemplo n.º 18
0
    def new_game(self, game_, **kwargs):
        if game_.host.sid != kwargs['sid']:
            raise errors.ForbiddenAction()

        game = model.Game()
        db.session.add(game)

        for p in game_.players:
            p.game = game
            p.games.append(game)
        game.players = game_.players
        game.host_id = game_.host.id

        return game
def solve(username):
    boardData = getCanvasData()
    walls = getWalls(boardData)
    data = getConfig()
    config = data['config']
    oldconfig = config
    challengeID = data['challengeId']
    goals = data['goals']
    robots = data['robots']
    # sort
    for x in range(4):
        if "green" in robots[x][2]:
            green = robots[x]
        elif "yellow" in robots[x][2]:
            yellow = robots[x]
        elif "blue" in robots[x][2]:
            blue = robots[x]
        elif "red" in robots[x][2]:
            red = robots[x]
    robots[0] = green
    robots[1] = blue
    robots[2] = red
    robots[3] = yellow
    print(walls)
    print(robots)
    print(goals)
    grid = []
    for wall in walls:
        grid += wall
    robits = getRobots(robots)
    listTokens = placeGoals(grid, goals)
    colorz = ['' for n in range(4)]
    for x, robot in enumerate(robots):
        if "green" in robot[2]:
            colorz[x] = 'G'
        elif "red" in robot[2]:
            colorz[x] = 'R'
        elif "yellow" in robot[2]:
            colorz[x] = 'Y'
        elif "blue" in robot[2]:
            colorz[x] = 'B'
    paths = [[] for n in range(5)]
    for x, tokenz in enumerate(listTokens):
        paths[x] = ricochet.search(model.Game(grid=grid, robots=robits, col=colorz, token=tokenz))
    solutions = getSolution(paths)
    if username is not '':
        print('will do something')
    return formatmessage(solutions)
Ejemplo n.º 20
0
def generate_game(**kwargs):
    default_params = {
        "machine_name": "foo",
        "human_name": "bar",
        "full_price": model.Price(**{
            "price": 12.00,
            "currency": "GBP"
        }),
        "current_price": model.Price(**{
            "price": 12.00,
            "currency": "GBP"
        }),
        "os": ["linux", "windows"],
        "platform": ["download"]
    }
    default_params.update(kwargs)
    return model.Game(**default_params)
Ejemplo n.º 21
0
    def do_start(self, args):
        """Start the game"""

        self.model = model.Game()
        self.model.initialise()

        loop = True

        while loop is True:
            island_names = self.model.get_island_names()

            chosen_island = utils.pick("Island", island_names)
            self.model.create_island(chosen_island)

            self.model.current_island.print_layout()

            if utils.confirm("Ok with this island?") is True:
                loop = False
Ejemplo n.º 22
0
def play_game(li, game_id, control_queue, engine_factory):
    username = li.get_profile()["username"]
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')), username,
                      li.baseUrl)
    board = setup_board(game)
    engine = engine_factory(board)
    conversation = Conversation(game, engine, li)

    print("+++ {}".format(game.show()))

    engine.pre_game(game)

    board = play_first_move(game, engine, board, li)

    try:
        for binary_chunk in updates:
            upd = json.loads(
                binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd))
            elif u_type == "gameState":
                moves = upd.get("moves").split()
                board = update_board(board, moves[-1])

                if is_engine_move(game.is_white, moves):
                    best_move = engine.search(board, upd.get("wtime"),
                                              upd.get("btime"),
                                              upd.get("winc"), upd.get("binc"))
                    li.make_move(game.id, best_move)
    except (RemoteDisconnected, ConnectionError, ProtocolError,
            HTTPError) as exception:
        print("Abandoning game due to connection error")
        traceback.print_exception(type(exception), exception,
                                  exception.__traceback__)
    finally:
        print("--- {} Game over".format(game.url()))
        engine.quit()
        # This can raise queue.NoFull, but that should only happen if we're not processing
        # events fast enough and in this case I believe the exception should be raised
        control_queue.put_nowait({"type": "local_game_done"})
Ejemplo n.º 23
0
def create_game():
    player = current_user.id
    deck = range(1, 107)
    random.shuffle(deck)
    dealt_cards = deck[100:]
    deck[100:] = []
    string_deck = str(deck)
    draw_deck = string_deck.strip('[]')
    game = model.Game(id=None, draw_pile=draw_deck)
    model.session.add(game)
    model.session.commit()
    string_hand = str(dealt_cards)
    player_hand = string_hand.strip('[]')
    usergame = model.Usergame(id=None, game_id=game.id, user_id=player,
                              position=2, hand=player_hand, miles=0, immunities=2222,
                              can_be_stopped=0, can_have_flat=0, can_have_low_gas=0,
                              can_have_speed_limit=0, can_be_in_accident=0, speed_limit=0,
                              can_go=0, has_flat=0, has_accident=0, gas_empty=0, game_status=0)
    model.session.add(usergame)
    model.session.commit()
    return render_template("await_players.html")
Ejemplo n.º 24
0
def play_game(li, game_id, engine_path, weights, threads, control_queue):
    username = li.get_profile()["username"]
    updates = li.get_game_stream(game_id).iter_lines()

    #Initial response of stream will be the full game info. Store it
    game = model.Game(json.loads(next(updates).decode('utf-8')), username,
                      li.baseUrl)
    board = setup_board(game.state)
    engine = setup_engine(engine_path, board, weights, threads)
    conversation = Conversation(game, engine, li)

    print("+++ {}".format(game.show()))

    engine.pre_game(game)

    board = play_first_move(game, engine, board, li)

    for binary_chunk in updates:
        upd = json.loads(
            binary_chunk.decode('utf-8')) if binary_chunk else None
        u_type = upd["type"] if upd else "ping"
        if u_type == "chatLine":
            conversation.react(ChatLine(upd))
        elif u_type == "gameState":
            moves = upd.get("moves").split()
            board = update_board(board, moves[-1])

            if is_engine_move(game.is_white, moves):
                best_move = engine.search(board, upd.get("wtime"),
                                          upd.get("btime"), upd.get("winc"),
                                          upd.get("binc"))
                li.make_move(game.id, best_move)
                if CONFIG.get("print_engine_stats"):
                    engine.print_stats()

    print("--- {} Game over".format(game.url()))
    engine.quit()
    # This can raise queue.NoFull, but that should only happen if we're not processing
    # events fast enough and in this case I believe the exception should be raised
    control_queue.put_nowait({"type": "local_game_done"})
Ejemplo n.º 25
0
def load_games(session):
#populate games table

    game_1 = ["Taboo", "static/img/taboo1.jpg"]    
    game_2 = ["Taboo", "static/img/taboo2.jpg"]
    game_3 = ["Taboo", "static/img/taboo3.jpg"]
    game_4 = ["Taboo", "static/img/taboo4.jpg"]
    game_5 = ["Taboo", "static/img/taboo5.jpg"]

    game_6 = ["Catchplace", "static/img/place1.jpg"]    
    game_7 = ["Catchplace", "static/img/place2.jpg"]
    game_8 = ["Catchplace", "static/img/place3.jpg"]
    game_9 = ["Catchplace", "static/img/place4.jpg"]    
    game_10 = ["Catchplace", "static/img/place5.jpg"]

    game_cards = [game_1, game_2, game_3, game_4, game_5, game_6, game_7, game_8, game_9, game_10]

    for game_row in game_cards:
        game = model.Game(
                        game_type=game_row[0],
                        filename=game_row[1])
        session.add(game)
    session.commit()
Ejemplo n.º 26
0
def play_game(li, game_id, user_profile, config):
    response = li.get_game_stream(game_id)
    lines = response.iter_lines()
    #Initial response of stream will be the full game info. Store it
    initial_state = json.loads(next(lines).decode('utf-8'))
    game = model.Game(initial_state, user_profile["username"], li.baseUrl, config.get("abort_time", 20))
    timelim=game.state["btime"]/1000
    timelim=timelim/60
    timep=round(timelim/85*60,1)
    if timep>10:
        timep=10
    elif timep<0.3:
        timep=0.3
    board = setup_board(game)
    cfg = config["engine"]

    if type(board).uci_variant=="chess":
        engine_path = os.path.join(cfg["dir"], cfg["name"])
        bookname="book.bin"
    elif type(board).uci_variant=="atomic":
        engine_path = os.path.join(cfg["dir"], cfg["lcname"])
        bookname="bookchen.bin"
    else:
        engine_path = os.path.join(cfg["dir"], cfg["fairyname"])
        bookname="bookchen.bin"
    engineeng = engine.SimpleEngine.popen_uci(engine_path)
    engineeng.configure({'Threads':5})
    engineeng.configure({'Hash':120})
    engineeng.configure({'EvalFile':'nn-0e698aa9eb8b.nnue'})
    engineeng.configure({'Use NNUE':True})

    logger.info("Game Details: {}".format(game))

    delay_seconds = config.get("rate_limiting_delay", 0)/1000

    if is_engine_move(game, board.move_stack) and not is_game_over(game):
        with chess.polyglot.open_reader(bookname) as reader:
            movesob=[]
            weight=[]
            for entry in reader.find_all(board):
                movesob.append(entry.move)
                weight.append(entry.weight)
        if len(weight)==0 or max(weight)<9:
            move=engineeng.play(board,engine.Limit(time=timep))
            board.push(move.move)
            li.make_move(game.id, move.move)
            time.sleep(delay_seconds)
        else:
            move=movesob[weight.index(max(weight))]
            board.push(move)
            li.make_move(game.id, move)

    with chess.polyglot.open_reader(bookname) as reader:
        while not terminated:
            try:
                binary_chunk = next(lines)
            except(StopIteration):
                break
            upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if not board.is_game_over():
                if u_type == "gameState":
                    game.state=upd
                    moves = upd["moves"].split()
                    board = update_board(board, moves[-1])
                    if not is_game_over(game) and is_engine_move(game, moves):
                        moves=[]
                        weight=[]
                        for entry in reader.find_all(board):
                            moves.append(entry.move)
                            weight.append(entry.weight)
                        if len(weight)==0 or max(weight)<9:
                            if game.is_white:
                                timelim=game.state["wtime"]/1000
                            else:
                                timelim=game.state["btime"]/1000
                            divtime=85-int(len(board.move_stack)/2)
                            if divtime<1:
                                timep=1
                            else:
                                timep=round(timelim/divtime,1)
                                if timep>10:
                                    timep=10
                                elif timep<0.3:
                                    timep=0.3
                            move=engineeng.play(board,engine.Limit(time=timep))
                            board.push(move.move)
                            li.make_move(game.id, move.move)
                            time.sleep(delay_seconds)
                        else:
                            move=moves[weight.index(max(weight))]
                            board.push(move)
                            li.make_move(game.id, move)
                            
                    if board.turn == chess.WHITE:
                        game.ping(config.get("abort_time", 20), (upd["wtime"] + upd["winc"]) / 1000 + 60)
                    else:
                        game.ping(config.get("abort_time", 20), (upd["btime"] + upd["binc"]) / 1000 + 60)
            
                elif u_type == "ping":
                    if game.should_abort_now():
                        logger.info("    Aborting {} by lack of activity".format(game.url()))
                        li.abort(game.id)
                        break
                    elif game.should_terminate_now():
                        logger.info("    Terminating {} by lack of activity".format(game.url()))
                        if game.is_abortable():
                            li.abort(game.id)
                        break
            else:
                break
    logger.info("game over")
    engineeng.quit()              
Ejemplo n.º 27
0
    def __init__(self):

        super(GameCLI, self).__init__()

        self.model = model.Game("Kingdom")
        self.view = view.TextView(self.model)
Ejemplo n.º 28
0
def play_game(li, game_id, user_profile, config):
    seventydone=False
    eightydone=False
    ninetydone=False
    global gamessss
    gamessss+=1
    response = li.get_game_stream(game_id)
    lines = response.iter_lines()
    bullet=False
    #Initial response of stream will be the full game info. Store it
    initial_state = json.loads(next(lines).decode('utf-8'))
    game = model.Game(initial_state, user_profile["username"], li.baseUrl, config.get("abort_time", 20))
    timelim=game.state["btime"]/1000
    timelim=timelim/60
    if timelim>=0.5 and timelim<=2:
        bullet=True
    time=round(timelim/100*60,1)
    if time>6:
        time=6
    elif time<0.3:
        time=0.3
    if bullet:
        time=0.3
    board = setup_board(game)
    cfg = config["engine"]

    if type(board).uci_variant=="chess":
        engine_path = os.path.join(cfg["dir"], cfg["name"])
        bookname="book.bin"
    elif type(board).uci_variant=="atomic":
        engine_path = os.path.join(cfg["dir"], cfg["lcname"])
        bookname="bookchen.bin"
    else:
        engine_path = os.path.join(cfg["dir"], cfg["fairyname"])
        bookname="bookchen.bin"
    engineeng = engine.SimpleEngine.popen_uci(engine_path)
    engineeng.configure({'Threads':5})
    engineeng.configure({'Hash':120})

    logger.info("+++ {}".format(game))

    if is_engine_move(game, board.move_stack) and not is_game_over(game):
        with chess.polyglot.open_reader(bookname) as reader:
            movesob=[]
            weight=[]
            for entry in reader.find_all(board):
                movesob.append(entry.move)
                weight.append(entry.weight)
        if len(weight)==0 or max(weight)<9:
            move=engineeng.play(board,engine.Limit(time=time))
            board.push(move.move)
            li.make_move(game.id, move.move)
        else:
            move=movesob[weight.index(max(weight))]
            board.push(move)
            li.make_move(game.id, move)

    with chess.polyglot.open_reader(bookname) as reader:
        while not terminated:
            try:
                binary_chunk = next(lines)
            except(StopIteration):
                break
            upd = json.loads(binary_chunk.decode('utf-8')) if binary_chunk else None
            u_type = upd["type"] if upd else "ping"
            if not board.is_game_over():
                if u_type == "gameState":
                    game.state=upd
                    moves = upd["moves"].split()
                    board = update_board(board, moves[-1])
                    if not is_game_over(game) and is_engine_move(game, moves):
                        moves=[]
                        weight=[]
                        for entry in reader.find_all(board):
                            moves.append(entry.move)
                            weight.append(entry.weight)
                        if len(weight)==0 or max(weight)<9:
                            move=engineeng.play(board,engine.Limit(time=time))
                            board.push(move.move)
                            li.make_move(game.id, move.move)
                        else:
                            move=moves[weight.index(max(weight))]
                            board.push(move)
                            li.make_move(game.id, move)
                            
                    if board.turn == chess.WHITE:
                        game.ping(config.get("abort_time", 20), (upd["wtime"] + upd["winc"]) / 1000 + 60)
                    else:
                        game.ping(config.get("abort_time", 20), (upd["btime"] + upd["binc"]) / 1000 + 60)
                    if len(board.move_stack)>70 and time>1.7 and not seventydone:
                        time-=1
                        seventydone=True
                    if len(board.move_stack)>80 and time>1.7 and not eightydone:
                        time-=1
                        eightydone=True
                    if len(board.move_stack)>90 and time>1.7 and not ninetydone:
                        time-=1
                        ninetydone=True
            
                elif u_type == "ping":
                    if game.should_abort_now():
                        logger.info("    Aborting {} by lack of activity".format(game.url()))
                        li.abort(game.id)
                        break
                    elif game.should_terminate_now():
                        logger.info("    Terminating {} by lack of activity".format(game.url()))
                        if game.is_abortable():
                            li.abort(game.id)
                        break
            else:
                logger.info("game over")
                gamessss-=1
                engineeng.quit()
                break
Ejemplo n.º 29
0
    import model
    import time
    import random
    import collections
    count = 0
    best = (0, 0)
    hist = collections.defaultdict(int)

    def callback(depth, nodes, inner, hits):
        print('Depth: %d, Nodes: %d (%d inner, %d hits)' %
              (depth, nodes, inner, hits))

    seed = 0
    while True:
        count += 1
        #seed = random.randint(0, 0x7fffffff)
        seed += 1
        start = time.clock()
        path = search(model.Game(seed))  #, callback)
        moves = len(path)
        hist[moves] += 1
        key = (moves, seed)
        if key > best:
            best = key
        path = [''.join(move) for move in path]
        path = ','.join(path)
        duration = time.clock() - start
        #print '%d. %2d (%.3f) %s [%s]'% (count, moves, duration, best, path)
        #print dict(hist)
        print('%d %d [%s]' % (seed, moves, path))
Ejemplo n.º 30
0
def play_game(li, game_id, control_queue, engine_factory, user_profile, config,
              challenge_queue, correspondence_queue, logging_queue,
              logging_configurer, logging_level):
    logging_configurer(logging_queue, logging_level)
    logger = logging.getLogger(__name__)

    response = li.get_game_stream(game_id)
    lines = response.iter_lines()

    # Initial response of stream will be the full game info. Store it
    initial_state = json.loads(next(lines).decode('utf-8'))
    game = model.Game(initial_state, user_profile["username"], li.baseUrl,
                      config.get("abort_time", 20))
    board = setup_board(game)
    engine = engine_factory(board)
    engine.get_opponent_info(game)
    conversation = Conversation(game, engine, li, __version__, challenge_queue)

    logger.info("+++ {}".format(game))

    is_correspondence = game.perf_name == "Correspondence"
    correspondence_cfg = config.get("correspondence", {}) or {}
    correspondence_move_time = correspondence_cfg.get("move_time", 60) * 1000

    engine_cfg = config["engine"]
    is_usi = engine_cfg["protocol"] == "usi"
    is_usi_ponder = is_usi and engine_cfg.get("ponder", False)
    move_overhead = config.get("move_overhead", 1000)
    delay_seconds = config.get("rate_limiting_delay", 0) / 1000
    polyglot_cfg = engine_cfg.get("polyglot", {})
    book_cfg = polyglot_cfg.get("book", {})

    ponder_thread = None
    deferredFirstMove = False

    ponder_usi = None

    def ponder_thread_func(game, engine, board, btime, wtime, binc, winc, byo):
        global ponder_results
        best_move, ponder_move = engine.search_with_ponder(
            game, board, btime, wtime, binc, winc, byo, True)
        ponder_results[game.id] = (best_move, ponder_move)

    logger.debug("Game state: {}".format(game.state))

    if len(board.move_stack) < 2:
        while not terminated:
            try:
                if not play_first_move(game, engine, board, li):
                    deferredFirstMove = True
                break
            except (HTTPError) as exception:
                if exception.response.status_code == 400:  # fallthrough
                    break
    else:
        moves = game.state["moves"].split()
        if not is_game_over(game) and is_engine_move(game, moves):
            best_move = None
            ponder_move = None
            btime = game.state["btime"]
            wtime = game.state["wtime"]
            start_time = time.perf_counter_ns()

            if board.turn == shogi.BLACK:
                btime = max(
                    0, btime - move_overhead - int(
                        (time.perf_counter_ns() - start_time) / 1000000))
            else:
                wtime = max(
                    0, wtime - move_overhead - int(
                        (time.perf_counter_ns() - start_time) / 1000000))
            logger.info("Searching for btime {} wtime {}".format(btime, wtime))
            best_move, ponder_move = engine.search_with_ponder(
                game, board, btime, wtime, game.state["binc"],
                game.state["winc"], game.state["byo"])
            engine.print_stats()

            if is_usi_ponder and not (ponder_move is None):
                ponder_board = copy.deepcopy(board)
                ponder_board.push(shogi.Move.from_usi(best_move))
                ponder_board.push(shogi.Move.from_usi(ponder_move))
                ponder_usi = ponder_move

                if board.turn == shogi.BLACK:
                    btime = max(
                        0, btime - move_overhead - int(
                            (time.perf_counter_ns() - start_time) / 1000000) +
                        game.state["binc"])
                else:
                    wtime = max(
                        0, wtime - move_overhead - int(
                            (time.perf_counter_ns() - start_time) / 1000000) +
                        game.state["winc"])
                logger.info("Pondering for btime {} wtime {}".format(
                    btime, wtime))
                ponder_thread = threading.Thread(
                    target=ponder_thread_func,
                    args=(game, engine, ponder_board, btime, wtime,
                          game.state["binc"], game.state["winc"],
                          game.state["byo"]))
                ponder_thread.start()
            li.make_move(game.id, best_move)
            time.sleep(delay_seconds)
        elif is_game_over(game):
            engine.report_game_result(game, board)
        elif len(board.move_stack) == 0:
            correspondence_disconnect_time = correspondence_cfg.get(
                "disconnect_time", 300)

    correspondence_disconnect_time = 0
    while not terminated:
        try:
            binary_chunk = next(lines)

            upd = json.loads(
                binary_chunk.decode('utf-8')) if binary_chunk else None
            logger.debug("Update: {}".format(upd))
            u_type = upd["type"] if upd else "ping"
            if u_type == "chatLine":
                conversation.react(ChatLine(upd), game)
            elif u_type == "gameState":
                game.state = upd
                moves = upd["moves"].split()
                if len(moves) > 0 and len(moves) != len(board.move_stack):
                    board = update_board(board, moves[-1])
                if not is_game_over(game) and is_engine_move(game, moves):
                    start_time = time.perf_counter_ns()
                    fake_thinking(config, board, game)
                    print_move_number(board)
                    correspondence_disconnect_time = correspondence_cfg.get(
                        "disconnect_time", 300)

                    best_move = None
                    ponder_move = None

                    btime = upd["btime"]
                    wtime = upd["wtime"]
                    start_time = time.perf_counter_ns()

                    if not deferredFirstMove:
                        if best_move == None:
                            if board.turn == shogi.BLACK:
                                btime = max(
                                    0, btime - move_overhead - int(
                                        (time.perf_counter_ns() - start_time) /
                                        1000000))
                            else:
                                wtime = max(
                                    0, wtime - move_overhead - int(
                                        (time.perf_counter_ns() - start_time) /
                                        1000000))
                            logger.info(
                                "Searching for btime {} wtime {}".format(
                                    btime, wtime))
                            best_move, ponder_move = engine.search_with_ponder(
                                game, board, btime, wtime, upd["binc"],
                                upd["winc"], upd["byo"])
                            engine.print_stats()

                        if is_usi_ponder and not (ponder_move is None):
                            ponder_board = copy.deepcopy(board)
                            ponder_board.push(shogi.Move.from_usi(best_move))
                            ponder_board.push(shogi.Move.from_usi(ponder_move))
                            ponder_usi = ponder_move
                            if board.turn == shogi.BLACK:
                                btime = max(
                                    0, btime - move_overhead - int(
                                        (time.perf_counter_ns() - start_time) /
                                        1000000) + upd["binc"])
                            else:
                                wtime = max(
                                    0, wtime - move_overhead - int(
                                        (time.perf_counter_ns() - start_time) /
                                        1000000) + upd["winc"])
                            logger.info(
                                "Pondering for btime {} wtime {}".format(
                                    btime, wtime))
                            ponder_thread = threading.Thread(
                                target=ponder_thread_func,
                                args=(game, engine, ponder_board, btime, wtime,
                                      upd["binc"], upd["winc"], upd["byo"]))
                            ponder_thread.start()
                        li.make_move(game.id, best_move)
                    else:
                        play_first_move(game, engine, board, li)
                        deferredFirstMove = False
                wb = 'w' if board.turn == shogi.BLACK else 'b'
                game.ping(config.get("abort_time", 30),
                          (upd[f"{wb}time"] + upd[f"{wb}inc"]) / 1000 + 60,
                          correspondence_disconnect_time)
            elif u_type == "ping":
                if is_correspondence and not is_engine_move(
                        game, board) and game.should_disconnect_now():
                    break
                elif game.should_abort_now():
                    logger.info("Aborting {} by lack of activity".format(
                        game.url()))
                    li.abort(game.id)
                    break
                elif game.should_terminate_now():
                    logger.info("Terminating {} by lack of activity".format(
                        game.url()))
                    if game.is_abortable():
                        li.abort(game.id)
                    break
        except (HTTPError, ReadTimeout, RemoteDisconnected,
                ChunkedEncodingError, ConnectionError, ProtocolError):
            if game.id not in (ongoing_game["gameId"]
                               for ongoing_game in li.get_ongoing_games()):
                break
        except StopIteration:
            break

    engine.stop()
    if not (ponder_thread is None):
        ponder_thread.join()

    if is_correspondence and not is_game_over(game):
        logger.info("--- Disconnecting from {}".format(game.url()))
        correspondence_queue.put(game_id)
    else:
        logger.info("--- {} Game over".format(game.url()))

    control_queue.put_nowait({"type": "local_game_done"})