def _selection(self, root_id): node_id = root_id while self.tree[node_id]['n'] > 0: board = utils.get_board(node_id, self.board_size) win_index = utils.check_win(board, self.win_mark) if win_index != 0: return node_id, win_index qu = {} ids = [] total_n = 0 for action_idx in self.tree[node_id]['child']: edge_id = node_id + (action_idx, ) n = self.tree[edge_id]['n'] total_n += n for i, action_index in enumerate(self.tree[node_id]['child']): child_id = node_id + (action_index, ) n = self.tree[child_id]['n'] q = self.tree[child_id]['q'] p = self.tree[child_id]['p'] u = self.c_puct * p * np.sqrt(total_n) / (n + 1) qu[child_id] = q + u max_value = max(qu.values()) ids = [key for key, value in qu.items() if value == max_value] node_id = ids[np.random.choice(len(ids))] board = utils.get_board(node_id, self.board_size) win_index = utils.check_win(board, self.win_mark) return node_id, win_index
def browse(self): threads = utils.get_board(self.board, self.page)["threads"] for t in threads: post = t["posts"][0] if int(post["images"]) <= 0: continue if "sub" in post: title = "%s | images: %s" % (post["sub"], post["images"] + 1) elif "com" in post: title = "%s | images: %s" % (post["com"], post["images"] + 1) else: title = "%s | images: %s" % (post["filename"], post["images"] + 1) icon = utils.get_thumb_url(self.board, post["tim"]) utils.add_directory(title, icon, icon, "%s?action=thread&board=%s&id=%s" % (sys.argv[0], urllib.quote_plus(self.board), post["no"])) if self.page < self.totalPages: next_page = self.page + 1 utils.add_next_page("%s?action=%s&page=%s&total_pages=%s&board=%s" % (sys.argv[0], self.action, next_page, self.totalPages, self.board), next_page) control.directory_end() return
def initialize_game(): clock = pygame.time.Clock() board = utils.get_board() snake = Snake() board[0][0] = 1 food = utils.generate_food(board) return clock, board, snake, food
def _expansion_simulation(self, leaf_id, win_index): leaf_board = self.tree[leaf_id]['board'] current_player = self.tree[leaf_id]['player'] if win_index == 0: # expansion actions = utils.valid_actions(leaf_board) for action in actions: action_index = action[1] child_id = leaf_id + (action_index, ) child_board = utils.get_board(child_id, self.board_size) next_turn = utils.get_turn(child_id) self.tree[child_id] = { 'board': child_board, 'player': next_turn, 'parent': leaf_id, 'child': [], 'n': 0., 'w': 0., 'q': 0. } self.tree[leaf_id]['child'].append(action_index) if self.tree[leaf_id]['parent']: # simulation board_sim = leaf_board.copy() turn_sim = current_player while True: actions_sim = utils.valid_actions(board_sim) action_sim = actions_sim[np.random.choice( len(actions_sim))] coord_sim = action_sim[0] if turn_sim == 0: board_sim[coord_sim] = 1 else: board_sim[coord_sim] = -1 win_idx_sim = utils.check_win(board_sim, self.win_mark) if win_idx_sim == 0: turn_sim = abs(turn_sim - 1) else: reward = utils.get_reward(win_idx_sim, leaf_id) return reward else: # root node don't simulation reward = 0. return reward else: # terminal node don't expansion reward = 1. return reward
def _selection(self, root_id): node_id = root_id # 한 번이라도 시뮬레이션이 이루어진 노드에서만 선택 while self.tree[node_id]['n'] > 0: # node_id로부터 보드의 현 상태를 생성하고 승패를 판단함 board = utils.get_board(node_id, self.board_size) win_index = utils.check_win(board, self.win_mark) if win_index != 0: return node_id, win_index # 해당 노드에서 승패가 결정나면 node_id 와 win_index(승패결과) 반환 qu = {} # q + u ids = [] # key에 child_id와 value에 qu가 입력될 dict total_n = 0 # 해당 부모노드에 포함된 자식노드들 시뮬레이션 수의 합 # 모든 자식노드들의 n값을 더해 total_n을 구함 for action_idx in self.tree[node_id]['child']: edge_id = node_id + (action_idx, ) n = self.tree[edge_id]['n'] total_n += n # 모든 자식노드들의 q+u 값을 구함 for i, action_index in enumerate(self.tree[node_id]['child']): child_id = node_id + (action_index, ) n = self.tree[child_id]['n'] q = self.tree[child_id]['q'] p = self.tree[child_id]['p'] u = self.c_puct * p * np.sqrt(total_n) / (n + 1) qu[child_id] = q + u max_value = max(qu.values()) # qu중 최대값을 구함 ids = [key for key, value in qu.items() if value == max_value ] # qu최대값에 해당하는 child_id와 value를 dict에 입력 node_id = ids[np.random.choice(len(ids))] # 최대값 중 하나에 해당하는 노드를 선택 # node_id로부터 보드의 현 상태를 생성하고 승패를 판단함 board = utils.get_board(node_id, self.board_size) win_index = utils.check_win(board, self.win_mark) return node_id, win_index
def _selection(self, root_id): node_id = root_id while self.tree[node_id]['n'] > 0: # if it is leaf node board = utils.get_board(node_id, self.board_size, self.win_mark) win_index = utils.check_win(board, self.win_mark) if win_index != 0: # if the game is over and the current node is not leaf return node_id, win_index qu = {} ids = [] total_n = 0 for action_idx in self.tree[node_id]['child']: edge_id = node_id + (action_idx, ) n = self.tree[edge_id]['n'] total_n += n # the total number of visit of child nodes # PUCT calculation for i, action_index in enumerate(self.tree[node_id]['child']): child_id = node_id + (action_index, ) # history + action visited previously n = self.tree[child_id]['n'] q = self.tree[child_id]['q'] p = self.tree[child_id]['p'] u = self.c_puct * p * np.sqrt(total_n) / (n + 1 ) # 2nd term of PUCT qu[child_id] = q + u max_value = max(qu.values()) ids = [key for key, value in qu.items() if value == max_value] # argmax indices node_id = ids[np.random.choice( len(ids))] # key & value of seleted index among argmax indices board = utils.get_board(node_id, self.board_size, self.win_mark) win_index = utils.check_win(board, self.win_mark) return node_id, win_index
def play_solo(no_of_plays=1): random_moves = [] hunt_moves = [] prob_moves = [] deep_moves = [] for i in range(no_of_plays): board = utils.get_board('random_ships') random_moves.append(random_algo.play(copy.deepcopy(board))) hunt_moves.append(hunt_algo.play(copy.deepcopy(board))) prob_moves.append(probability_density.play(copy.deepcopy(board))) rl_moves = rl.play(no_of_plays) print('average moves for each algo to win: ') print('random: ', statistics.mean(random_moves), '---', random_moves) print('hunt: ', statistics.mean(hunt_moves), '---', hunt_moves) print('prob: ', statistics.mean(prob_moves), '---', prob_moves) print('RL: ', statistics.mean(rl_moves), '---', rl_moves) plot_results(random_moves, hunt_moves, prob_moves, rl_moves)
def play_tournament(no_of_plays=1): # 6 DIFFERENT GAME COMPETITIONS # random vs. hunt random_vs_hunt = {'random': 0, 'hunt': 0} for i in range(no_of_plays): rh_random_moves = random_algo.play(utils.get_board('random_ships')) rh_hunt_moves = hunt_algo.play(utils.get_board('random_ships')) if rh_random_moves < rh_hunt_moves: random_vs_hunt['random'] += 1 elif rh_hunt_moves < rh_random_moves: random_vs_hunt['hunt'] += 1 # random vs. prob random_vs_prob = {'random': 0, 'prob': 0} for i in range(no_of_plays): rp_random_moves = random_algo.play(utils.get_board('random_ships')) rp_prob_moves = probability_density.play( utils.get_board('random_ships')) if rp_random_moves < rp_prob_moves: random_vs_prob['random'] += 1 elif rp_prob_moves < rp_random_moves: random_vs_prob['prob'] += 1 # hunt vs. prob hunt_vs_prob = {'hunt': 0, 'prob': 0} for i in range(no_of_plays): hp_hunt_moves = hunt_algo.play(utils.get_board('random_ships')) hp_prob_moves = probability_density.play( utils.get_board('random_ships')) if hp_hunt_moves < hp_prob_moves: hunt_vs_prob['hunt'] += 1 elif hp_prob_moves < hp_hunt_moves: hunt_vs_prob['prob'] += 1 # random vs. RL random_vs_rl = {'random': 0, 'rl': 0} rrl_random_moves = [] for i in range(no_of_plays): rrl_random_moves.append( random_algo.play(utils.get_board('random_ships'))) rrl_rl_moves = rl.play(no_of_plays) for i in range(no_of_plays): if rrl_random_moves[i] < rrl_rl_moves[i]: random_vs_rl['random'] += 1 elif rrl_rl_moves[i] < rrl_random_moves[i]: random_vs_rl['rl'] += 1 # hunt vs. RL hunt_vs_rl = {'hunt': 0, 'rl': 0} hrl_hunt_moves = [] for i in range(no_of_plays): hrl_hunt_moves.append(hunt_algo.play(utils.get_board('random_ships'))) hrl_rl_moves = rl.play(no_of_plays) for i in range(no_of_plays): if hrl_hunt_moves[i] < hrl_rl_moves[i]: hunt_vs_rl['hunt'] += 1 elif hrl_rl_moves[i] < hrl_hunt_moves[i]: hunt_vs_rl['rl'] += 1 # prob vs. RL prob_vs_rl = {'prob': 0, 'rl': 0} prl_prob_moves = [] for i in range(no_of_plays): prl_prob_moves.append( probability_density.play(utils.get_board('random_ships'))) prl_rl_moves = rl.play(no_of_plays) for i in range(no_of_plays): if prl_prob_moves[i] < prl_rl_moves[i]: prob_vs_rl['prob'] += 1 elif prl_rl_moves[i] < prl_prob_moves[i]: prob_vs_rl['rl'] += 1 print('TOURNAMENT GAME BETWEEN ALGORITHMS') print('\t Random vs. Hunt') print('\t\t random: ', random_vs_hunt['random'], 'wins') print('\t\t hunt: ', random_vs_hunt['hunt'], 'wins') print('\t Random vs. Probability Density') print('\t\t random: ', random_vs_prob['random'], 'wins') print('\t\t probability: ', random_vs_prob['prob'], 'wins') print('\t Hunt vs. Probability Density') print('\t\t hunt: ', hunt_vs_prob['hunt'], 'wins') print('\t\t probability: ', hunt_vs_prob['prob'], 'wins') print('\t Random vs. Reinforcement Learning') print('\t\t random: ', random_vs_rl['random'], 'wins') print('\t\t learning: ', random_vs_rl['rl'], 'wins') print('\t Hunt vs. Reinforcement Learning') print('\t\t hunt: ', hunt_vs_rl['hunt'], 'wins') print('\t\t learning: ', hunt_vs_rl['rl'], 'wins') print('\t Probability Density vs. Reinforcement Learning') print('\t\t probability: ', prob_vs_rl['prob'], 'wins') print('\t\t learning: ', prob_vs_rl['rl'], 'wins')
async def round_socket_handler(request): users = request.app["users"] sockets = request.app["websockets"] seeks = request.app["seeks"] games = request.app["games"] ws = MyWebSocketResponse() ws_ready = ws.can_prepare(request) if not ws_ready.ok: raise web.HTTPFound("/") await ws.prepare(request) session = await aiohttp_session.get_session(request) session_user = session.get("user_name") user = users[session_user] if session_user else None game_ping_task = None game = None opp_ws = None async def game_pinger(): """ Prevent Heroku to close inactive ws """ # TODO: use this to detect disconnected games? while not ws.closed: await ws.send_json({}) await asyncio.sleep(5) log.debug("-------------------------- NEW round WEBSOCKET by %s" % user) async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if type(msg.data) == str: if msg.data == "close": log.debug("Got 'close' msg.") break else: data = json.loads(msg.data) log.debug("Websocket (%s) message: %s" % (id(ws), msg)) if data["type"] == "move": log.info("Got USER move %s %s %s" % (user.username, data["gameId"], data["move"])) move_is_ok = await play_move(games, data) if not move_is_ok: message = "Something went wrong! Server can't accept move %s. Try another one, please!" % data[ "move"] chat_response = { "type": "roundchat", "user": "******", "message": message, "room": "player" } await ws.send_json(chat_response) board_response = get_board(games, data, full=False) log.info(" Server send to %s: %s" % (user.username, board_response["fen"])) await ws.send_json(board_response) game = games[data["gameId"]] if game.status > STARTED and user.bot: await user.game_queues[data["gameId"] ].put(game.game_end) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if opp_player.bot: await opp_player.game_queues[data["gameId"] ].put(game.game_state) if game.status > STARTED: await opp_player.game_queues[ data["gameId"]].put(game.game_end) else: try: opp_ws = users[opp_name].game_sockets[ data["gameId"]] log.info(" Server send to %s: %s" % (opp_name, board_response["fen"])) await opp_ws.send_json(board_response) except KeyError: log.error( "Failed to send move %s to %s in game %s" % (data["move"], opp_name, data["gameId"])) await round_broadcast(game, users, board_response, channels=request.app["channels"]) elif data["type"] == "ready": game = games[data["gameId"]] opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if opp_player.bot: await opp_player.event_queue.put(game.game_start) response = start(games, data) await ws.send_json(response) else: opp_ok = data["gameId"] in users[ opp_name].game_sockets # waiting for opp to be ready also if not opp_ok: loop = asyncio.get_event_loop() end_time = loop.time() + 20.0 while True: if (loop.time() + 1.0) >= end_time: log.debug( "Game %s aborted because user %s is not ready." % (data["gameId"], opp_name)) response = await game.abort() await ws.send_json(response) break await asyncio.sleep(1) opp_ok = data["gameId"] in users[ opp_name].game_sockets if opp_ok: break if opp_ok: opp_ws = users[opp_name].game_sockets[ data["gameId"]] response = start(games, data) await opp_ws.send_json(response) await ws.send_json(response) response = { "type": "user_present", "username": opp_name } await ws.send_json(response) elif data["type"] == "board": board_response = get_board(games, data, full=True) log.info("User %s asked board. Server sent: %s" % (user.username, board_response["fen"])) await ws.send_json(board_response) elif data["type"] == "analysis": game = await load_game(request.app, data["gameId"]) # If there is any fishnet client, use it. if len(request.app["workers"]) > 0: work_id = "".join( random.choice(string.ascii_letters + string.digits) for x in range(6)) work = { "work": { "type": "analysis", "id": work_id, }, # or: # "work": { # "type": "move", # "id": "work_id", # "level": 5 // 1 to 8 # }, "username": data["username"], "game_id": data["gameId"], # optional "position": game.board. initial_fen, # start position (X-FEN) "variant": game.variant, "chess960": game.chess960, "moves": " ".join(game.board.move_stack ), # moves of the game (UCI) "nodes": 500000, # optional limit # "skipPositions": [1, 4, 5] # 0 is the first position } request.app["works"][work_id] = work request.app["fishnet"].put_nowait( (ANALYSIS, work_id)) else: engine = users.get("Fairy-Stockfish") if (engine is not None) and engine.online: engine.game_queues[ data["gameId"]] = asyncio.Queue() await engine.event_queue.put( game.analysis_start(data["username"])) response = { "type": "roundchat", "user": "", "room": "spectator", "message": "Analysis request sent..." } await ws.send_json(response) elif data["type"] == "rematch": game = await load_game(request.app, data["gameId"]) if game is None: log.debug("Requseted game %s not found!") response = { "type": "game_not_found", "username": user.username, "gameId": data["gameId"] } await ws.send_json(response) continue opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if opp_player.bot: if opp_player.username == "Random-Mover": engine = users.get("Random-Mover") else: engine = users.get("Fairy-Stockfish") if engine is None or not engine.online: # TODO: message that engine is offline, but capture BOT will play instead engine = users.get("Random-Mover") color = "w" if game.wplayer.username == opp_name else "b" seek = Seek(user, game.variant, game.initial_fen, color, game.base, game.inc, game.level, game.rated, game.chess960) seeks[seek.id] = seek response = await new_game(request.app, engine, seek.id) await ws.send_json(response) await engine.event_queue.put( challenge(seek, response)) gameId = response["gameId"] engine.game_queues[gameId] = asyncio.Queue() else: opp_ws = users[opp_name].game_sockets[ data["gameId"]] if opp_name in game.rematch_offers: color = "w" if game.wplayer.username == opp_name else "b" seek = Seek(user, game.variant, game.initial_fen, color, game.base, game.inc, game.level, game.rated, game.chess960) seeks[seek.id] = seek response = await new_game( request.app, opp_player, seek.id) await ws.send_json(response) await opp_ws.send_json(response) else: game.rematch_offers.add(user.username) response = { "type": "offer", "message": "Rematch offer sent", "room": "player", "user": "" } game.messages.append(response) await ws.send_json(response) await opp_ws.send_json(response) elif data["type"] == "draw": game = games[data["gameId"]] opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] response = await draw(games, data, agreement=opp_name in game.draw_offers) await ws.send_json(response) if opp_player.bot: if game.status == DRAW: await opp_player.game_queues[ data["gameId"]].put(game.game_end) else: opp_ws = users[opp_name].game_sockets[ data["gameId"]] await opp_ws.send_json(response) if opp_name not in game.draw_offers: game.draw_offers.add(user.username) await round_broadcast(game, users, response) elif data["type"] in ("abort", "resign", "abandone", "flag"): game = games[data["gameId"]] response = await game_ended(games, user, data, data["type"]) await ws.send_json(response) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if opp_player.bot: await opp_player.game_queues[data["gameId"] ].put(game.game_end) else: opp_ws = users[opp_name].game_sockets[ data["gameId"]] await opp_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "game_user_connected": game = await load_game(request.app, data["gameId"]) if session_user is not None: if data["username"] and data[ "username"] != session_user: log.info( "+++ Existing game_user %s socket connected as %s." % (session_user, data["username"])) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( db=request.app["db"], username=data["username"], anon=data["username"].startswith( "Anonymous")) users[user.username] = user # Update logged in users as spactators if user.username != game.wplayer.username and user.username != game.bplayer.username and game is not None: game.spectators.add(user) else: user = users[session_user] else: log.info( "+++ Existing game_user %s socket reconnected." % data["username"]) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User(db=request.app["db"], username=data["username"], anon=data["username"].startswith( "Anonymous")) users[user.username] = user user.ping_counter = 0 # update websocket user.game_sockets[data["gameId"]] = ws # remove user seeks await user.clear_seeks(sockets, seeks) if game is None: log.debug("Requseted game %s not found!") response = { "type": "game_not_found", "username": user.username, "gameId": data["gameId"] } await ws.send_json(response) continue else: games[data["gameId"]] = game if user.username != game.wplayer.username and user.username != game.bplayer.username: game.spectators.add(user) response = { "type": "spectators", "spectators": ", ".join( (spectator.username for spectator in game.spectators)), "gameId": data["gameId"] } await round_broadcast(game, users, response, full=True) response = { "type": "game_user_connected", "username": user.username, "gameId": data["gameId"], "ply": game.ply } await ws.send_json(response) response = { "type": "fullchat", "lines": list(game.messages) } await ws.send_json(response, dumps=partial( json.dumps, default=datetime.isoformat)) loop = asyncio.get_event_loop() game_ping_task = loop.create_task(game_pinger()) request.app["tasks"].add(game_ping_task) elif data["type"] == "is_user_present": player_name = data["username"] player = users.get(player_name) if player is not None and data["gameId"] in ( player.game_queues if player.bot else player.game_sockets): response = { "type": "user_present", "username": player_name } else: response = { "type": "user_disconnected", "username": player_name } await ws.send_json(response) elif data["type"] == "moretime": # TODO: stop and update game stopwatch time with updated secs game = games[data["gameId"]] opp_color = WHITE if user.username == game.bplayer.username else BLACK if opp_color == game.stopwatch.color: opp_time = game.stopwatch.stop() game.stopwatch.restart(opp_time + MORE_TIME) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if not opp_player.bot: opp_ws = users[opp_name].game_sockets[ data["gameId"]] response = {"type": "moretime"} await opp_ws.send_json(response) elif data["type"] == "roundchat": response = { "type": "roundchat", "user": user.username, "message": data["message"], "room": data["room"] } gameId = data["gameId"] game = await load_game(request.app, gameId) game.messages.append(response) for name in (game.wplayer.username, game.bplayer.username): player = users[name] if player.bot: if gameId in player.game_queues: await player.game_queues[gameId].put( '{"type": "chatLine", "username": "******", "room": "spectator", "text": "%s"}\n' % (user.username, data["message"])) else: if gameId in player.game_sockets: player_ws = player.game_sockets[gameId] await player_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "leave": response = { "type": "roundchat", "user": "", "message": "%s left the game" % user.username, "room": "player" } gameId = data["gameId"] game = await load_game(request.app, gameId) game.messages.append(response) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if not opp_player.bot and gameId in opp_player.game_sockets: opp_player_ws = opp_player.game_sockets[gameId] await opp_player_ws.send_json(response) response = { "type": "user_disconnected", "username": user.username } await opp_player_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "updateTV": db = request.app["db"] query_filter = { "us": data["profileId"] } if "profileId" in data and data[ "profileId"] != "" else {} doc = await db.game.find_one(query_filter, sort=[('$natural', -1)]) gameId = None if doc is not None: gameId = doc["_id"] if gameId != data["gameId"] and gameId is not None: response = {"type": "updateTV", "gameId": gameId} await ws.send_json(response) else: log.debug("type(msg.data) != str %s" % msg) elif msg.type == aiohttp.WSMsgType.ERROR: log.debug("!!! Round ws connection closed with exception %s" % ws.exception()) else: log.debug("other msg.type %s %s" % (msg.type, msg)) log.info("--- Round Websocket %s closed" % id(ws)) if game is not None and opp_ws is not None: response = {"type": "user_disconnected", "username": user.username} await opp_ws.send_json(response) await round_broadcast(game, users, response) if game is not None and not user.bot: del user.game_sockets[game.id] if user.username != game.wplayer.username and user.username != game.bplayer.username: game.spectators.discard(user) response = { "type": "spectators", "spectators": ", ".join( (spectator.username for spectator in game.spectators)), "gameId": game.id } await round_broadcast(game, users, response, full=True) if game_ping_task is not None: game_ping_task.cancel() return ws
def test_prob(): board = utils.get_board('random_ships') m = probability_density.play(board) print('total moves: ', m)
return False # same function in all the algorithms def play(board): global remaining_ships moves = 0 while True: prepare_to_make_move(board) moves += 1 print('moves: ', moves) # utils.display_board(board) # resetting remaining ships remaining_ships = [] floating_ships = utils.get_floating_ships(board) for ship_number in floating_ships: remaining_ships.append(utils.ships[ship_number - 1][2]) if utils.check_if_won(board): break # print('hunt play done') utils.display_board(board) return moves if __name__ == '__main__': m = play(utils.get_board('random_ships')) print('moves: ', m)
'''Main Function''' # get the path of the labels text file path = os.path.join(os.path.join(utils.home(), 'labels'), 'labels.txt') for ind in range(0, 100): imgname = utils.readlabels(path, ind)[0] imgname = os.path.basename(imgname) imgname = os.path.splitext(imgname)[0] txtfile = imgname + '.txt' txtfile = os.path.join(utils.home(), 'labels', txtfile) f = open(txtfile, "a+") if (not os.stat(txtfile).st_size == 0): continue # get the image of the board test2 = utils.get_board(path, ind) w, h = test2.shape[0], test2.shape[1] # pre-process the image img = preprocess(test2) utils.imshow(img) cv2.destroyAllWindows() w, h = img.shape[0], img.shape[1] # convert img to be ocr'd img_2 = Image.fromarray(img) # config string for tesseract tessdata_dir_config = '--psm 11 -l eng' # get ocr label label = pytesseract.image_to_data(img_2, config=tessdata_dir_config) data = np.genfromtxt(io.BytesIO(label.encode()), delimiter="\t", skip_header=1, filling_values=1, usecols=(6, 7, 8, 9, 10, 11), dtype=np.str) # delete all the rows where tesseract did not find a letter
import sys import appex from sudoku import Sudoku from utils import get_board if not appex.is_running_extension(): print("Must use share sheet to pass in image!") sys.exit(1) image = appex.get_image() orig, grid = get_board(image) print("Original".center(45)) orig.show() sudoku = Sudoku(grid) print("\n", "Interpreted".center(45), sudoku) sudoku.solve() print("Solved".center(45), sudoku)
def main(): # Create object with players players = utils.get_players(config.N_PLAYERS) # Create board with properties board = utils.get_board(config.BOARD_FILENAME) # Continue playing as long as more than one player remains in game while len(players) > 1: # Take turns for turn in range(config.N_PLAYERS): # Define current player curr_player = players[turn] # Double roll counter n_double_roll = 0 # Continue turn until player rolls no doubles or goes to jail while True: # Roll dice roll, rolled_double = utils.roll_dice() # Update double roll counter n_double_roll += int(rolled_double) # If player is in jail if players[turn].jail_turns > 0: # Select jail strategy curr_player.choose_jail_strategy(rolled_double) # If player is still in jail if curr_player.jail_turns > 0: break # If player rolled less than 3 doubles if n_double_roll < 3: # Move player curr_player.move(roll) # Define current board space curr_space = board[curr_player.position] for case in classes.Switch(type(curr_space).__name__): if case('Street'): curr_player.evaluate_buy(curr_space, players) # If no double rolled, end turn if not rolled_double: break # Otherwise, send player to jail and end turn elif n_double_roll == 3: curr_player.go_to_jail() break
async def fishnet_move(request): work_id = request.match_info.get("workId") data = await request.json() fm = request.app["fishnet_monitor"] key = data["fishnet"]["apikey"] worker = FISHNET_KEYS[key] # print(json.dumps(data, sort_keys=True, indent=4)) if key not in FISHNET_KEYS: return web.Response(status=404) fm[worker].append("%s %s %s" % (datetime.utcnow(), work_id, "move")) if work_id not in request.app["works"]: response = await get_work(request, data) return response work = request.app["works"][work_id] gameId = work["game_id"] # remove work from works del request.app["works"][work_id] game = await load_game(request.app, gameId) users = request.app["users"] games = request.app["games"] username = "******" move = data["move"]["bestmove"] invalid_move = False log.info("BOT move %s %s %s %s - %s" % (username, gameId, move, game.wplayer.username, game.bplayer.username)) if game.status <= STARTED: try: await game.play_move(move) except SystemError: invalid_move = True log.error("Game %s aborted because invalid move %s by %s !!!" % (gameId, move, username)) game.status = INVALIDMOVE game.result = "0-1" if username == game.wplayer.username else "1-0" opp_name = game.wplayer.username if username == game.bplayer.username else game.bplayer.username if not invalid_move: board_response = get_board(games, {"gameId": gameId}, full=False) if users[opp_name].bot: if game.status > STARTED: await users[opp_name].game_queues[gameId].put(game.game_end) else: await users[opp_name].game_queues[gameId].put(game.game_state) else: try: opp_ws = users[opp_name].game_sockets[gameId] if not invalid_move: await opp_ws.send_json(board_response) if game.status > STARTED: await opp_ws.send_json(game.game_end) except KeyError: log.error("Move %s can't send to %s. Game %s was removed from game_sockets !!!" % (move, username, gameId)) if not invalid_move: await round_broadcast(game, users, board_response, channels=request.app["channels"]) response = await get_work(request, data) return response
return False def play(board): moves = 0 while True: make_move(board) moves += 1 print('moves: ',moves) # utils.display_board(board) if utils.check_if_won(board): break # print('hunt play done') utils.display_board(board) return moves if __name__ == '__main__': moves = [] for i in range(30): board = utils.get_board('random_ships') moves.append( play(board) ) print(moves)
def __init__(self, config): logging.info("Setting up the Simulated World") self.board = get_board(config["Board"]) # Game board self.player = Player(self.board, config["Player"]) # Peq Solitaire Player self.visualizer = BoardVisualizer(self.board, config["Training"]) # Class for visualizing board using networkx
async def bot_move(request): auth = request.headers.get("Authorization") if auth is None: return web.HTTPForbidden() token = auth[auth.find("Bearer") + 7:] if token not in BOT_TOKENS: log.error("BOT account auth with token %s failed" % token) return web.HTTPForbidden() user_agent = request.headers.get("User-Agent") username = user_agent[user_agent.find("user:"******"gameId"] move = request.match_info["move"] users = request.app["users"] games = request.app["games"] bot_player = users[username] game = games[gameId] invalid_move = False # log.info("BOT move %s %s %s %s - %s" % (username, gameId, move, game.wplayer.username, game.bplayer.username)) if game.status <= STARTED: try: await game.play_move(move) except SystemError: invalid_move = True log.error("Game %s aborted because invalid move %s by %s !!!" % (gameId, move, username)) game.status = INVALIDMOVE game.result = "0-1" if username == game.wplayer.username else "1-0" bot_player.bot_online = False await bot_player.game_queues[gameId].put(game.game_state) if game.status > STARTED: await bot_player.game_queues[gameId].put(game.game_end) opp_name = game.wplayer.username if username == game.bplayer.username else game.bplayer.username if not invalid_move: board_response = get_board(games, {"gameId": gameId}, full=False) if users[opp_name].bot: if game.status > STARTED: await users[opp_name].game_queues[gameId].put(game.game_end) else: await users[opp_name].game_queues[gameId].put(game.game_state) else: opp_ws = users[opp_name].game_sockets[gameId] if not invalid_move: await opp_ws.send_json(board_response) if game.status > STARTED: await opp_ws.send_json(game.game_end) if not invalid_move: await round_broadcast(game, users, board_response, channels=request.app["channels"]) return web.json_response({"ok": True})
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) # Implement the default Matplotlib key bindings. from matplotlib.backend_bases import key_press_handler from matplotlib.figure import Figure import utils import numpy as np import pytesseract from PIL import Image import pdb import cv2 root = tkinter.Tk() root.wm_title("Embedding in Tk") img = utils.get_board('/Users/Alex/Desktop/Summer-2019/scrabble/labels.txt', 12) im = Image.fromarray(img) im = pytesseract.image_to_boxes(im) fig = Figure(figsize=(5, 5), dpi=100) t = np.arange(0, 3, .01) fig.figimage(img, 0) canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea. canvas.draw() canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) toolbar = NavigationToolbar2Tk(canvas, root) toolbar.update() canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) def on_key_press(event):
help="nearest multiple of 32 for resized width") ap.add_argument("-e", "--height", type=int, default=320, help="nearest multiple of 32 for resized height") ap.add_argument("-p", "--padding", type=float, default=0.0, help="amount of padding to add to each border of ROI") args = vars(ap.parse_args()) # load the input image and grab the image dimensions image = cv2.imread(args["image"]) image = utils.get_board(os.path.join(os.getcwd(), 'labels.txt'), 0) orig = image.copy() (origH, origW) = image.shape[:2] # set the new width and height and then determine the ratio in change # for both the width and height (newW, newH) = (args["width"], args["height"]) rW = origW / float(newW) rH = origH / float(newH) # resize the image and grab the new image dimensions image = cv2.resize(image, (newW, newH)) (H, W) = image.shape[:2] # define the two output layer names for the EAST detector model that
# USAGE # python ocr.py --image images/example_01.png # python ocr.py --image images/example_02.png --preprocess blur # import the necessary packages from PIL import Image import pytesseract import argparse import cv2 import utils import os import pdb import matplotlib.pyplot as plt path = os.path.join(os.getcwd(),'labels.txt') num_boards = 2 board = utils.get_board(path, 1) plt.imshow(board) plt.show()