def main(): with open(sys.argv[1]) as file: data = json.load(file) # BEGIN # # Setup colour = data.get(COLOUR_KEY) board.setup(data) print("# Colour is {}, coords at {}".format( colour, board.get_col_coord_tuple(colour))) print("# Initial board:") print_board(board.get_board(), debug=True) move_counter = 0 while len(board.get_col_coord_dict(colour)) > 0: ###print("board by piece") ###print(board.get_col_coord_tuple("red")) temp_path = pathfinder.get_next_move(board.get_pieces(True), board.get_col_coord_tuple(colour), (colour, 3)) ###print("path found! : {}".format(temp_path)) coords = output.determine_move(board.get_col_coord_tuple(colour), Formatting.string_to_tuple(temp_path)) board.update_piece(coords) print_board(board.get_board(), debug=True) move_counter += 1 ###print(board.get_pieces(True)) print("# Number of moves: {}".format(move_counter))
def main(): filename = 'boggle-dictionary.txt' dictionary = Dictionary(filename) boggle_board = get_board() print("Boggle board after shuffle:") for row in boggle_board: print(row) print("\nWords found in board:") word_list = find_words(boggle_board, dictionary) for word in word_list: print(word) #benchmarking print('\nAverage time taken to find words in standard 4x4 boggle board =') print(benchmarking(dictionary), 'seconds') #Create result object result = dict() result['score'] = calculate_score(word_list) result['words'] = sorted(word_list) print('\nResult object:') print(result) return result
def on_incoming_data(data: str) -> str: global board try: action = get_player_action(data) except ValueError: return "{}" #Reset the game board if action == "reset": board.reset() return "{}" #Send the current board to the client elif action == "getstate": array = board.get_board() return json.JSONEncoder().encode({"moves": array}) #Allow the player to move elif action == "move": try: move = get_player_move(data) return board.player_move(move) except ValueError: return "{}" else: return "{}"
def predict_policy(self, board): """ Takes in a Board object and returns p """ board_ = board.get_board() board_ = board_.reshape((1, 9)) policy, _ = self.nn.predict(board_) policy = policy[0].tolist() return policy
def test_valid_black_move_bishop(self): board_string_sample_black_bishop = " QQQ QbQ QQQ " valid_black_bishops_moves_sample = [[3, 1, 4, 2, 10], [3, 1, 2, 2, 10], [3, 1, 4, 0, 10], [3, 1, 2, 0, 10]] get_board_sample_9 = get_board(board_string_sample_black_bishop) result = valid_black_move(get_board_sample_9) self.assertEqual(result, valid_black_bishops_moves_sample)
def test_get_board(self): expected_result_black_rook = self.starting_board[0][0] expected_result_white_rook = self.starting_board[15][15] result = get_board(self.starting_board_string) result_black_rook = result[0][0] result_white_rook = result[15][15] self.assertEqual(expected_result_black_rook, result_black_rook) self.assertEqual(expected_result_white_rook, result_white_rook)
def move(): data = bottle.request.json board = get_board(data) return { 'move': get_move(board), 'taunt': 'learning...', }
def test_valid_black_move_rook(self): board_string_sample_black_rook = " QQQ QrQ QQQ r " valid_black_rooks_moves_sample = [[2, 0, 3, 1, 5], [2, 1, 3, 1, 5], [2, 2, 3, 1, 5], [3, 0, 3, 1, 5], [3, 2, 3, 1, 5], [4, 0, 3, 1, 5], [4, 1, 3, 1, 5], [4, 2, 3, 1, 5]] get_board_sample_8 = get_board(board_string_sample_black_rook) result = valid_white_move(get_board_sample_8) self.assertEqual(result, valid_black_rooks_moves_sample)
def test_valid_black_move_queen(self): board_string_sample_black_queen = " QQQ QqQ QQQ " valid_black_queen_moves_sample = [[3, 1, 4, 1, 5], [3, 1, 3, 0, 5], [3, 1, 3, 2, 5], [3, 1, 2, 1, 5], [3, 1, 4, 2, 5], [3, 1, 2, 2, 5], [3, 1, 4, 0, 5], [3, 1, 2, 0, 5]] get_board_sample_7 = get_board(board_string_sample_black_queen) result = valid_black_move(get_board_sample_7) self.assertEqual(result, valid_black_queen_moves_sample)
def test_valid_black_move_pawn(self): board_string_sample_black_pawns = " p Q Q p p " valid_black_pawns_moves_sample = [[6, 6, 7, 6, 4], [6, 6, 7, 6, 1], [4, 7, 5, 7, 4], [4, 7, 5, 7, 1], [3, 1, 4, 2, 10], [3, 1, 4, 0, 10], [3, 1, 5, 1, 3], [3, 1, 4, 1, 1]] get_board_sample_6 = get_board(board_string_sample_black_pawns) result = valid_black_move(get_board_sample_6) self.assertEqual(result, valid_black_pawns_moves_sample)
def test_valid_white_move_bishop(self): board_string_sample_bishop = " qqq qBq qqq " valid_white_bishops_moves_sample = [[12, 1, 11, 0, 10], [12, 1, 13, 0, 10], [12, 1, 11, 2, 10], [12, 1, 13, 2, 10]] get_board_sample_4 = get_board(board_string_sample_bishop) result = valid_white_move(get_board_sample_4) self.assertEqual(result, valid_white_bishops_moves_sample)
def test_valid_white_move_pawn(self): board_string_sample_pawns = " P q q P P " valid_white_pawns_moves_sample = [[7, 7, 6, 7, 4], [7, 7, 6, 7, 1], [12, 1, 11, 0, 10], [12, 1, 11, 2, 10], [12, 1, 10, 1, 3], [12, 1, 11, 1, 1], [13, 6, 11, 6, 3], [13, 6, 12, 6, 1]] get_board_sample_1 = get_board(board_string_sample_pawns) result = valid_white_move(get_board_sample_1) self.assertEqual(result, valid_white_pawns_moves_sample)
def solution2(game_id): initial_state = _api.get_game(game_id) if (initial_state["success"] == True): state = initial_state["gameState"] tiles = state["tileInfo"] current_player = state["yourPlayer"] current_y_pos = current_player["yPos"] current_x_pos = current_player["xPos"] path_index = 0 map_to_board_first(tiles) # TODO: DETECT THESE AUTOMATICALLY IN THE FUTURE goal_point = get_goal(tiles) # for row in get_board(): # for tile in row: # print(str(tile)[:1], end='') # print("") path = astar(get_board(), (current_x_pos, current_y_pos), goal_point) draw_map(state, path) while not state["gameStatus"] == "done": current_player = state["yourPlayer"] current_y_pos = current_player["yPos"] current_x_pos = current_player["xPos"] turn = state["turn"] tiles = state["tileInfo"] direction = get_dir((current_x_pos, current_y_pos), path[path_index]) path_index += 1 if direction == None: path_index = 0 path = astar(get_board(), (current_x_pos, current_y_pos), goal_point) direction = get_dir((current_x_pos, current_y_pos), path[path_index]) response = _api.step(game_id, direction) state = response["gameState"] else: print(initial_state["message"])
def test_valid_white_move_rook(self): board_string_sample_rook = " R q qRq q " valid_white_rooks_moves_sample = [[8, 2, 7, 2, 1], [8, 2, 8, 3, 1], [8, 2, 8, 1, 1], [8, 2, 9, 2, 2], [12, 1, 11, 1, 10], [12, 1, 12, 2, 10], [12, 1, 12, 0, 10], [12, 1, 13, 1, 10]] get_board_sample_3 = get_board(board_string_sample_rook) result = valid_white_move(get_board_sample_3) self.assertEqual(result, valid_white_rooks_moves_sample)
def move_piece(piece, board): """ This function is for moving knights """ if (piece.get_name() == "knight"): moves = [(2, 1), (-2, 1), (2, -1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)] elif (piece.get_name() == "king"): moves = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, -1), (-1, 1)] current_position = piece.get_position() new_positions = [] current_board = board.get_board() for index in range(len(moves)): move = moves[index] new_row = current_position[0] + move[0] new_col = current_position[1] + move[1] if (new_row < 0) or (new_row > 7) or (new_col < 0) or (new_col > 7): continue else: if (current_board[new_row][new_col] == '-'): new_positions.append((new_row, new_col)) else: other_piece = current_board[new_row][new_col] if (piece.get_color() != other_piece.get_color()): new_positions.append((new_row, new_col)) else: continue if (len(new_positions) == 0): return False else: new_position = input( "Enter the position to move your knight to Ex.(2 3): ") if (new_position == "back"): return None new_position = new_position.split(' ') new_row = int(new_position[1]) new_col = int(new_position[0]) while ((new_row, new_col) not in new_positions): new_position = input( "You can\'t move to that position. Try again Ex.(2 3): ") new_position = new_position.split(' ') new_row = int(new_position[1]) new_col = int(new_position[0]) return (new_row, new_col)
def test_valid_black_move_king(self): board_string_sample_black_kings = " QQQ QkQ QQQ k " valid_black_kings_moves_sample = [[8, 9, 9, 9, 1], [8, 9, 8, 8, 1], [8, 9, 8, 10, 1], [8, 9, 7, 9, 2], [8, 9, 9, 10, 1], [8, 9, 7, 10, 1], [8, 9, 9, 8, 1], [8, 9, 7, 8, 1], [3, 1, 4, 1, 10], [3, 1, 3, 0, 10], [3, 1, 3, 2, 10], [3, 1, 2, 1, 10], [3, 1, 4, 2, 10], [3, 1, 2, 2, 10], [3, 1, 4, 0, 10], [3, 1, 2, 0, 10]] get_board_sample_10 = get_board(board_string_sample_black_kings) result = valid_black_move(get_board_sample_10) self.assertEqual(result, valid_black_kings_moves_sample)
def test_valid_white_move_queen(self): board_string_sample_queens = " Q qqq qQq qqq " valid_white_queens_moves_sample = [[12, 1, 11, 1, 5], [12, 1, 12, 2, 5], [12, 1, 12, 0, 5], [12, 1, 13, 1, 5], [12, 1, 11, 0, 5], [12, 1, 13, 0, 5], [12, 1, 11, 2, 5], [12, 1, 13, 2, 5]] get_board_sample_2 = get_board(board_string_sample_queens) result = valid_white_move(get_board_sample_2) self.assertEqual(result, valid_white_queens_moves_sample)
def __init__(self, slctboard): """ 提供校准过程实现的方法 :param tested_board: instance of board :return: """ self.board = get_board(slctboard) # 选择被测板类型后即决定该class下所有函数是否被执行、参数是什么 self.busyflag = None self.ispassed = None self.steptime = 0.1 self.check_value = 0 self.cali_parameter = 0 self.varify_value = 0
def move_rook(rook, board): """ This function is for moving the rook """ current_board = board.get_board() current_position = rook.get_position() current_row = current_position[0] current_col = current_position[1] color = rook.get_color() if (can_move(rook, current_board, current_position) == False): return False else: pass while (True): new_position = input( "Enter the position that you want to move the rook to Ex.(1 4): ") if (new_position == "back"): return None new_position = new_position.split(' ') new_row = int(new_position[1]) new_col = int(new_position[0]) new_position = (new_row, new_col) change_in_row = new_row - current_row change_in_col = new_col - current_col if (new_row < 0) or (new_row > 7) or (new_col < 0) or (new_col > 7): print("That is not a valid move") continue else: if (change_in_row != 0) and (change_in_col == 0): is_valid = check_vertical(current_board, current_position, new_position, color, change_in_row) if (is_valid == True): return (new_row, new_col) else: print("That is not a valid move") elif (change_in_col != 0) and (change_in_row == 0): is_valid = check_horezontal(current_board, current_position, new_position, color, change_in_col) if (is_valid == True): return (new_row, new_col) else: print("That is not a valid move") else: print("That is not a valid move") continue
def point_benefit(board, color, position): benefit = 0 field = board.get_board() if field[OTHER[color]][25 - position] >= 2: benefit -= 30 if field[OTHER[color]][25 - position] == 1: benefit += 5 if field[color][position] == 1: benefit += 4 if field[color][position] >= 2: benefit += 3 if field[OTHER[color]][25 - position] == 0 and field[color][position] == 0: benefit += 2 return benefit
def value(board, color): field = board.get_board() value = 0 for position in range(1, 25): if field[OTHER[color]][25 - position] >= 2: value -= 5 - field[OTHER[color]][25 - position] if field[OTHER[color]][25 - position] == 1: value += 3 if field[color][position] == 1: value += 0.9 - (position / 12) if field[color][position] >= 2: value += 4 - field[color][position] if field[OTHER[color]][25 - position] == field[color][position] == 0: value += 0 return value
def test_valid_white_move_king(self): board_string_sample_kings = " K qqq qKq qqq " valid_white_kings_moves_sample = [[8, 2, 7, 2, 1], [8, 2, 8, 3, 1], [8, 2, 8, 1, 1], [8, 2, 9, 2, 2], [8, 2, 7, 1, 1], [8, 2, 9, 1, 1], [8, 2, 7, 3, 1], [8, 2, 9, 3, 1], [12, 1, 11, 1, 10], [12, 1, 12, 2, 10], [12, 1, 12, 0, 10], [12, 1, 13, 1, 10], [12, 1, 11, 0, 10], [12, 1, 13, 0, 10], [12, 1, 11, 2, 10], [12, 1, 13, 2, 10]] get_board_sample_5 = get_board(board_string_sample_kings) result = valid_white_move(get_board_sample_5) self.assertEqual(result, valid_white_kings_moves_sample)
def move(): data = bottle.request.json board = get_board(data) # return HTTPResponse( # status=200, # headers={ # "Content-Type": "application/json" # }, # body=json.dumps({ # "move": get_move(data, board) # }) # ) return { 'move': get_move(data, board) }
def move_bishop(bishop, board): """ This function is for moving the bishop """ current_board = board.get_board() current_position = bishop.get_position() current_row = current_position[0] current_col = current_position[1] color = bishop.get_color() if (can_move(bishop, current_board, current_position) == False): return False else: pass while (True): new_position = input( "Enter the position that you want to move the bishop to Ex.(1 4): " ) if (new_position == "back"): return None new_position = new_position.split(' ') new_row = int(new_position[1]) new_col = int(new_position[0]) new_position = (new_row, new_col) change_in_row = new_row - current_row change_in_col = new_col - current_col if (new_row < 0) or (new_row > 7) or (new_col < 0) or (new_col > 7): print("That is not a valid move") continue else: if (abs(change_in_row) == abs(change_in_col)): is_valid = check_diagnol(current_board, current_position, new_position, color, change_in_row, change_in_col) if (is_valid == True): return (new_row, new_col) else: print("That is a not a valid move") else: print("That is not a valid move")
def decideMoveGood(data): graph = board.get_board(data) currX = data['you']["body"]["data"][0]['x'] currY = data['you']["body"]["data"][0]['y'] startP = (currX, currY) checkX = None checkY = None for i in data['food']['data']: smallestX = abs(i['x'] - currX) if checkX == None or smallestX > checkX: smallestX = i['x'] smallestY = abs(i['y'] - currY) if checkY == None or smallestY > checkY: smallestY = i['y'] goalF = (checkX, checkY) path = bfs.breadth_first_search(graph, startP, goalF) return directionToGo(path, startP)
def make_move(board, color, roll): print("Called with: ", color, roll) field = board.get_board() max_eval, move = -100000000, 0 if field[color][0] > 0: # print("Hit Case") if field[OTHER[color]][25 - roll] <= 1: board.move_checker(color, 0, roll) return board elif board.takeout[color]: # print("Takeout Case") if field[color][25 - roll] > 0: board.move_checker(color, 25 - roll, roll) return board else: for i in range(19, 25 - roll): if field[color][i] > 0: board.move_checker(color, i, roll) return board for i in range(25 - roll, 25): if field[color][i] > 0: board.move_checker(color, i, roll) return board else: # print("Default Case") new_board = copy.deepcopy(board) for i in range(24, 0, -1): if 0 < i - roll < 25 and field[color][i - roll] > 0: if new_board.move_checker(color, i - roll, roll): # new_board.print_board() if value(new_board, color) >= max_eval: max_eval = value(new_board, color) move = i # print(i) # board.print_board() # print(value(board, color), max_eval) new_board = copy.deepcopy(board) # board.print_board() # print("Got to here") # print(move) # board.print_board() board.move_checker(color, move - roll, roll) return board
def find_positions(pawn, board, vertical_moves, diagonal_moves): """ decides the moves available for the pawn """ new_positions = [] current_position = pawn.get_position() chess_board = board.get_board() has_moved = pawn.get_has_moved() if (has_moved == False): if (pawn.get_color() == "black"): vertical_moves.append((2, 0)) else: vertical_moves.append((-2, 0)) pawn.set_has_moved() for move in vertical_moves: new_row = current_position[0] + move[0] new_col = current_position[1] + move[1] if (new_row < 0) or (new_row > 7) or (new_col < 0) or (new_col > 7): pass else: if (chess_board[new_row][new_col] == '-'): new_positions.append((new_row, new_col)) else: break for move in diagonal_moves: new_row = current_position[0] + move[0] new_col = current_position[1] + move[1] if (new_row < 0) or (new_row > 7) or (new_col < 0) or (new_col > 7): continue else: if (chess_board[new_row][new_col] != '-'): other_piece = chess_board[new_row][new_col] if (pawn.get_color() != other_piece.get_color()): new_positions.append((new_row, new_col)) else: pass return new_positions
def benchmarking(dictionary): """ Find average time taken to find all valid (given by dictionary) in a standard boggle board of size 4x4 Arguments: dictionary -- object of Dictionary class; API for methods is_path and is_word """ sum = 0 for i in range(100): boggle_board = get_board() time_before = time.time() for j in range(10): find_words(boggle_board, dictionary) time_after = time.time() time_diff = time_after - time_before sum = sum + (time_diff / 10) avg = sum / 100 return avg
def can_form_heap(board, color, position, rolls): benefit = 0 field = board.get_board() if field[OTHER[color]][25 - position] >= 2: benefit -= 30 if field[OTHER[color]][25 - position] == 1: benefit += 7 if field[color][position - rolls[0]] > 2: if field[color][position - rolls[1]] >= 2: benefit += 2 elif field[color][position - rolls[1]] == 1: benefit += 3 elif field[color][position - rolls[0]] == 1: if field[color][position - rolls[1]] > 2: benefit += 3 elif field[color][position - rolls[1]] == 1: benefit += 4 if field[color][position] == 1: benefit += 4 if field[color][position] >= 2: benefit += 3 - field[color][position] if field[OTHER[color]][25 - position] == 0 and field[color][position] == 0: benefit += 2
for i in range(len(PLAYERS)): PLAYERS[i].add_position( (len(PLAYERS) * round + (i - (round - 1))) % len(PLAYERS)) return DECK, BOARD, POT, PLAYERS players = init_players(6, 100) game = init_game(players, 9) deck = game[0] board = game[1] pot = game[2] players = game[3] for card in board.get_board(): print(card.show_card()) print(pot.show_pot()) players[0].show_player_hand().best_five(board) for player in players: print(player.general_name()) print( player.general_name(), player.show_player_hand().show_hand()[0].show_card(), player.show_player_hand().show_hand()[1].show_card(),
def get_state(blacks, whites, turn, strict_stone_count): """Return State object.""" return State(get_board(blacks, whites), turn, strict_stone_count)
import tiles, validator, board, scoring import string plr_tiles = {0: [],1: []} current_player = 0 d = board.get_board() def get_tiles(player): '''refills player rack with new tiles from the bag''' global plr_tiles new_tiles = tiles.dist_tiles(plr_tiles[player]) plr_tiles[player].extend(new_tiles) print plr_tiles[player] return new_tiles def update_tiles(player, rem_tiles, exchange=False): '''removes used tiles from player rack''' global plr_tiles print 'update tiles' print plr_tiles[player] print rem_tiles for i in rem_tiles : if i.islower(): i = '?' if i in plr_tiles[player]: plr_tiles[player].remove(i) if exchange: tiles.exchange_tiles(rem_tiles) print 'Result' print plr_tiles[player] def player_turn(move):
async def run(self): async with aiohttp.ClientSession() as session: async with session.ws_connect( url=self.__url, heartbeat=10.0, headers=self.__generate_headers()) as ws: await ws.send_str(self.__get_enter_room_message()) opponent_uid = '' is_gaming = False async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: decrypt_message = self.aes_decrypt( bytes.fromhex(msg.data[32:])) text_message = json.loads(decrypt_message) logger.debug('[Recv][<-]: %s' % text_message) if 'url' in text_message: if not is_gaming: current_game_started_time = 0 current_game_finished_time = 0 current_game_bv = 0 current_game_bvs = 0 current_game_opponent_solved_bv = 1 # This should avoid bugs in calcuation current_game_difficulty = '' if text_message['url'] == 'pvp/enter': await ws.send_str( self.__get_create_room_message()) elif text_message[ 'url'] == 'pvp/room/enter/event' and self.__uid != text_message[ 'user']['pvp']['uid']: opponent_uid = text_message['user']['pvp'][ 'uid'] logger.info( 'An opponent entered the room ...') await ws.send_str( self.__get_hello_message()) self.__RESUMED = False self.__level = self.__get_default_level( text_message['user']['user'] ['timingLevel']) if opponent_uid not in self.__USER_LIST: self.__USER_LIST[opponent_uid] = {} if text_message['user']['user']['vip']: self.__USER_LIST[opponent_uid][ 'original'] = self.__VIP_COUNTS self.__USER_LIST[opponent_uid][ 'left'] = self.__VIP_COUNTS else: self.__USER_LIST[opponent_uid][ 'original'] = self.__NORMAL_COUNTS self.__USER_LIST[opponent_uid][ 'left'] = self.__NORMAL_COUNTS if opponent_uid in ban_list or self.__USER_LIST[ opponent_uid]['left'] <= 0: logger.info( 'The opponent is in the ban list ...' ) await ws.send_str( self.__get_room_kick_out_message( uid=opponent_uid)) elif text_message[ 'url'] == 'pvp/room/exit/event' and opponent_uid == text_message[ 'user']['pvp']['uid']: if opponent_uid in ban_list: logger.info( 'The opponent is kicked out of the room ...' ) else: logger.info( 'The opponent exited the room ...') elif text_message[ 'url'] == 'pvp/user/online' and opponent_uid == text_message[ 'uid'] and text_message['offline']: logger.info( 'The opponent is offline now, refreshing the room ...' ) await ws.send_str( self.__get_exit_room_message()) elif text_message[ 'url'] == 'pvp/room/ready' and opponent_uid == text_message[ 'uid'] and text_message['ready']: logger.info('The opponent got ready ...') await ws.send_str( self.__get_start_battle_message()) elif text_message[ 'url'] == 'pvp/room/update' and self.__uid in text_message[ 'room']['userIdList']: if text_message['room']['expired']: logger.info('The room has expired ...') if text_message['room']['gaming']: is_gaming = True await ws.send_str( self.__get_battle_board_message()) self.__USER_LIST[opponent_uid][ 'left'] -= 1 else: logger.info( 'The room status has been updated ...' ) if not self.__RESUMED: await ws.send_str( self. __get_level_status_message()) if opponent_uid and self.__USER_LIST[ opponent_uid]['left'] <= 3: await ws.send_str( self.__get_left_games_message( uid=opponent_uid)) if opponent_uid and self.__USER_LIST[ opponent_uid]['left'] <= 0: await ws.send_str( self.__get_exit_room_message()) if opponent_uid == text_message[ 'room']['users'][0]['pvp'][ 'uid']: if text_message['room']['coin'] == 0 and len( text_message['room'] ['password'] ) == 0 and text_message['room'][ 'minesweeperAutoOpen'] and not text_message[ 'room']['minesweeperFlagForbidden'] and text_message[ 'room']['round'] == 1 and text_message[ 'room'][ 'maxNumber'] == 2: await ws.send_str( self. __get_ready_status_message( )) else: await ws.send_str( self. __get_room_edit_warning_message( )) if len(opponent_uid) != 0 and ( len(text_message['room'] ['userIdList']) != 2 or opponent_uid not in text_message['room'] ['userIdList'] ) and opponent_uid not in ban_list and not self.__RESUMED: await ws.send_str( self.__get_edit_room_message()) self.__RESUMED = True elif text_message['url'] == 'pvp/room/exit': # keep alive self.__level_hold_on = False self.__INC_FACTOR = 0.24 self.__DEC_FACTOR = 0.08 opponent_uid = '' logger.info('The bot left the room ...') logger.info('Re-creating the room ...') await ws.send_str( self.__get_create_room_message()) elif text_message[ 'url'] == 'pvp/room/message' and opponent_uid == text_message[ 'msg']['user']['uid']: message = text_message['msg'][ 'message'].strip().split() if message: result = self.__user_message_parser( message) await ws.send_str(result) else: if text_message[ 'url'] == 'pvp/minesweeper/info': tmp_level = self.__level board = get_board(text_message['cells'] [0].split('-')[0:-1]) board_result = get_board_result(board) current_game_bv = board_result['bv'] current_game_difficulty = board_result[ 'difficulty'] current_game_bvs = self.__get_est_bvs( tmp_level, current_game_difficulty, current_game_bv) await ws.send_str( self.__get_battle_progress_message(1)) logger.info( 'The battle is ready to start, wait for 6 seconds ...' ) time.sleep( 6) # first preparation cold time current_game_started_time = time.time() logger.info('The battle is started ...') elif text_message[ 'url'] == 'pvp/minesweeper/progress': if text_message['uid'] == self.__uid: if text_message[ 'bv'] == current_game_bv: current_game_finished_time = time.time( ) await ws.send_str( self.__get_bot_success_message( current_game_bv, current_game_finished_time - current_game_started_time)) else: await ws.send_str( self. __get_battle_progress_message( text_message['bv'] + 1)) time.sleep(1 / current_game_bvs ) # cold time by bvs elif text_message['uid'] == opponent_uid: current_game_opponent_solved_bv = text_message[ 'bv'] logger.info( 'The opponent is solving %d bv ...' % (current_game_opponent_solved_bv)) else: logger.debug( 'This is another game out of the room ...' ) elif text_message[ 'url'] == 'pvp/minesweeper/win': is_gaming = False winner_uid = text_message['users'][0][ 'pvp']['uid'] if winner_uid == self.__uid: logger.info( 'The bot won the battle ...') if not self.__level_hold_on: est_level = self.__get_est_level( current_game_difficulty, current_game_finished_time - current_game_started_time, current_game_opponent_solved_bv, current_game_bv) prev_level = self.__level self.__level = self.__level - ( self.__level - est_level) * self.__DEC_FACTOR if self.__level < self.__MIN_LEVEL: self.__level = self.__MIN_LEVEL logger.info( 'Level changes a bit [%.3f -> %.3f] ...' % (prev_level, self.__level)) self.__INC_FACTOR = self.__INC_FACTOR / 2.0 if self.__INC_FACTOR > 0.07 else 0.06 self.__DEC_FACTOR = self.__DEC_FACTOR * 2.0 if self.__DEC_FACTOR < 0.31 else 0.32 logger.info( 'The increasing factor is set to: %.3f' % (self.__INC_FACTOR)) logger.info( 'The decreasing factor is set to: %.3f' % (self.__DEC_FACTOR)) elif winner_uid == opponent_uid: logger.info( 'The opponent won the battle ...') if not self.__level_hold_on: current_game_finished_time = time.time( ) est_level = self.__get_est_level( current_game_difficulty, current_game_finished_time - current_game_started_time, current_game_opponent_solved_bv, current_game_bv) prev_level = self.__level self.__level = self.__level + ( est_level - self.__level ) * self.__INC_FACTOR if self.__level > self.__MAX_LEVEL: self.__level = self.__MAX_LEVEL logger.info( 'Level changes a bit [%.3f -> %.3f] ...' % (prev_level, self.__level)) self.__INC_FACTOR = self.__INC_FACTOR * 2.0 if self.__INC_FACTOR < 0.47 else 0.48 self.__DEC_FACTOR = self.__DEC_FACTOR / 2.0 if self.__DEC_FACTOR > 0.05 else 0.04 logger.info( 'The increasing factor is set to: %.3f' % (self.__INC_FACTOR)) logger.info( 'The decreasing factor is set to: %.3f' % (self.__DEC_FACTOR)) elif text_message[ 'url'] == 'pvp/room/user/exit' and opponent_uid == text_message[ 'user']['pvp']['uid']: logger.info('The opponent ran away ...') else: code = text_message['code'] logger.warning( 'Something weird is happening, HTTP code: %d' % code) if code == 10100: logger.error( 'Incompatible version type, please update your version number.' ) break elif msg.type == aiohttp.WSMsgType.ERROR: logger.warning( 'The websocket connection encounters an error: %s' % msg.data) break
global board r, c = get_empty() if r is None: return True for i in range(1, 10): if is_valid(r, c, i): board[r][c] = i if solve_cell(): return True board[r][c] = 0 return False def solve_board(): global board solve_cell() return board if __name__ == '__main__': board = get_board() row = len(board) col = len(board[0]) if row != 9 or col != 9: raise Exception('Invalid rows and columns') print_board(board) solution = solve_board() print('Solution:') print_board(solution) write_board(solution)
board_roi = frame[0:1, 0:1] # Opens the game board html webbrowser.open("file://" + path + '/game.html') # Game Loop while True: # Gets the Key Press keyp = cv2.waitKey(1) & 0xFF # Gets the current frame sta, img = images.read() img2 = img.copy() # Scans the curent image for a board if keyp == ord('s'): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) board, retever = get_board(gray) # Get the board ROI if board: corners_board = get_corners(board, img) board_roi = corners_board[0] # Rotates the board if keyp == ord('r'): board = rotate_board(board) # Flips the board if keyp == ord('f'): flipped = not flipped # Undoes last move if keyp == ord('u'): if(chess.undo()):