示例#1
0
def main():
    # initialize the init state and goal state as 2d array
    init_tile = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
    goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

    # 123046758

    init = State(init_tile, 0, 0)
    goal = State(goal_tile, 0, 0)

    uninformed_solver = UninformedSearchSolver(init, goal)
    informed_solver = InformedSearchSolver(init, goal)

    try:

        print(f"Initial State:\n{init_tile}")
        print(f"Goal State:\n{goal_tile}")
        uninformed_runs = uninformed_solver.run()
        informed_runs = informed_solver.run()
        print(
            f"\nUninformed search took {uninformed_runs} iterations and {uninformed_solver.depth} to solve the puzzle"
        )
        print(
            f"\nInformed search took {informed_runs} iterations and {informed_solver.depth} depth to solve the puzzle"
        )
    except RuntimeError:
        print("Puzzle has no solution.")
示例#2
0
def mass_test(iterations: int):
    for i in range(iterations):
        arr = np.arange(9).reshape((3, 3))
        np.random.shuffle(arr)
        init_state = State(arr)

        arr1 = np.arange(9).reshape((3, 3))
        np.random.shuffle(arr1)
        goal_state = State(arr1)
        try:
            informed_solver = InformedSearchSolver(init_state, goal_state)
            uninformed_solver = UninformedSearchSolver(init_state, goal_state)

            sys.stdout = open(os.devnull, 'w')
            informed_path = informed_solver.run()
            uninformed_path = uninformed_solver.run()
            sys.stdout = sys.__stdout__

            if informed_path > uninformed_path:
                print("Iteration", i,
                      "- Informed path was longer than the uninformed")
                print(init_state.tile_seq)
                print("----------")
                print(goal_state.tile_seq)
        except RuntimeError:
            pass
    def test_misplaced_tiles(self):
        init_tile = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.misplaced_tiles(goal), 4)
def compare_time():
    init_tile = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
    goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

    init = State(init_tile)
    goal = State(goal_tile)

    print('Informed search took {:.4f} milliseconds'.format(
        time_informed(init, goal) * 1000))
    print('Uninformed search took {:.4f} milliseconds'.format(
        time_uninformed(init, goal) * 1000))
示例#5
0
 def get_next_state(self, player_id: int, state: State, action: int):
     next_state = State.from_state(state)
     angle = self.calculate_new_angle(state.get_angle(player_id), action)
     next_state.set_angle(player_id, angle)
     position = self.calculate_new_position(state.get_position(player_id),
                                            angle)
     next_state.set_position(player_id, position)
     self.draw_circle(next_state.get_board(), self.head_colors[player_id],
                      self.get_head_position(position, angle),
                      self.head_radius)
     self.draw_circle(next_state.get_board(), state.colors[player_id],
                      position, self.player_radius)
     # TODO: Look into saving in designated memory space by specifying destination of copy.
     return next_state
示例#6
0
 def create(self, state_configuration=None):
     state_defaults = {"board_size": 3, "player_count": 2, "player_turn": 1}
     if state_configuration == None:
         state_configuration = {}
     state_configuration = dict(state_defaults, **state_configuration)
     configured_board = self.board_config(
         state_configuration.get("board_size", 3),
         state_configuration.get("board_status"))
     configured_game_id = self.game_id_config(
         state_configuration.get("game_id"))
     configured_player_ids = self.player_ids_config(
         player_count=state_configuration.get("player_count", 2))
     configured_player_turn = state_configuration.get("player_turn", 1)
     configured_game_completion = state_configuration.get(
         "game_complete", False)
     configured_history = state_configuration.get("history", [])
     new_state = State(
         dict(
             {
                 "game_id": configured_game_id,
                 "player_ids": configured_player_ids,
                 "player_turn": configured_player_turn,
                 "game_complete": configured_game_completion,
                 "history": configured_history
             }, **configured_board))
     self.state_repo.write_state(new_state)
     return new_state
示例#7
0
 def update(self, state, changes, update_turn=True):
     unchanged_state = copy.deepcopy(state)
     if changes.get("coordinates") != None:
         updated_board = self.update_board(state,
                                           changes.get("coordinates"))
     else:
         updated_board = {}
     if update_turn == True:
         if state.player_turn == (state.player_count):
             state.player_turn = 1
         else:
             state.player_turn += 1
         state.history.append(unchanged_state)
     updated_completion = self.is_game_complete(state)
     updated_state = State(
         dict(
             {
                 "game_id": state.game_id,
                 "player_ids": state.player_ids,
                 "player_turn": state.player_turn,
                 "game_complete": updated_completion,
                 "history": state.history
             }, **updated_board))
     self.state_repo.write_state(updated_state)
     return updated_state
示例#8
0
 def initialize_states(self, positions, angles):
     n = len(self.players)
     states = []
     for i in range(n):
         states.append(
             State((Arena.ARENA_HEIGHT, Arena.ARENA_WIDTH, 3), positions,
                   angles, self.colors[-i:] + self.colors[:-i]))
     return states
示例#9
0
def run_cli_mode():
    state = State()

    state.reset()
    while not state.gameover:
        state.load_new_item()
        while True:
            print(f'Score: {state.score}')
            state.item.log_state()

            if state.is_end_game:
                break

            c = input('Enter char:').strip()
            response = state.submit_char(c)

            if response == SubmitStatus.SUCCESS:
                state.increment_score()
            print('=================')
    def test_next_state(self):
        init_tile = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        informed_solver = InformedSearchSolver(init, goal)

        self.assertEqual(len(informed_solver.opened), 1)
        self.assertEqual(len(informed_solver.closed), 0)
        informed_solver.next_state()

        self.assertEqual(len(informed_solver.opened), 3)
        self.assertEqual(len(informed_solver.closed), 1)
        informed_solver.next_state()

        self.assertEqual(len(informed_solver.opened), 5)
        self.assertEqual(len(informed_solver.closed), 2)
        informed_solver.next_state()

        with self.assertRaises(StopIteration):
            informed_solver.next_state()
示例#11
0
class Bot(object):
    """
    Bot for http://theaigames.com/competitions/ai-block-battle
    """
    def __init__(self):
        self._settings = Settings()
        self._state = State()

    def run(self):
        """
        Handle the game logic
        """
        while not sys.stdin.closed:

            try:
                raw_line = sys.stdin.readline()

                if len(raw_line) == 0:
                    continue

                line = raw_line.strip()

                parts = line.split()
                command = parts[0]

                if command == "settings":
                    self._settings.update(setting=parts[1], value=parts[2])

                elif command == "update":
                    self._state.update(obj=parts[1], state=parts[2], value=parts[3])

                elif command == "action":
                    # Take action
                    Output.write("drop")

            except EOFError:
                return
示例#12
0
    def test_move_right(self):
        initial_state = np.array([[1, 2, 3], [4, 0, 6], [7, 5, 8]])
        expected_state = np.array([[1, 2, 3], [4, 6, 0], [7, 5, 8]])
        old_state = State(initial_state, 0, 0)
        new_state = old_state.move("right")

        self.assertTrue(np.all(new_state.tile_seq == expected_state))

        initial_state = np.array([[1, 2, 3], [4, 5, 0], [6, 7, 8]])
        state = State(initial_state, 0, 0)

        with self.assertRaises(IndexError):
            state.move("right")
示例#13
0
    def __init__(self):
        super(MainWindow, self).__init__(1280, 720)

        self.state = State()

        self.game_view = GameView(self.state, self.width, self.height)
        self.score_view = ScoreView(self.state, self.width, self.height)
        self.leaderboard_view = LeaderBoardView(self.state, self.width,
                                                self.height)

        self.state.router.add_mapping(Screen.GAME, self.game_view)
        self.state.router.add_mapping(Screen.SCORE, self.score_view)
        self.state.router.add_mapping(Screen.LEADERBOARD,
                                      self.leaderboard_view)

        self.state.router.push(Screen.GAME)
示例#14
0
    def test_move_up(self):
        initial_state = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
        expected_state = np.array([[0, 2, 3], [1, 4, 6], [7, 5, 8]])

        old_state = State(initial_state, 0, 0)
        new_state = old_state.move("up")

        self.assertTrue(np.all(new_state.tile_seq == expected_state))
        self.assertTrue(np.all(old_state.tile_seq == initial_state))

        initial_state = np.array([[0, 2, 3], [1, 4, 6], [7, 5, 8]])
        state = State(initial_state, 0, 0)

        with self.assertRaises(IndexError):
            state.move("up")
示例#15
0
 def test_neighbors(self):
     initial_state = State(np.array([[1, 2, 3], [4, 0, 6], [7, 5, 8]]))
     up_state = State(np.array([[1, 0, 3], [4, 2, 6], [7, 5, 8]]))
     right_state = State(np.array([[1, 2, 3], [4, 6, 0], [7, 5, 8]]))
     down_state = State(np.array([[1, 2, 3], [4, 5, 6], [7, 0, 8]]))
     left_state = State(np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]]))
     neighbors = initial_state.neighbors()
     self.assertTrue(
         np.all(
             np.array([x.tile_seq for x in neighbors])
             == np.array(
                 [
                     right_state.tile_seq,
                     left_state.tile_seq,
                     up_state.tile_seq,
                     down_state.tile_seq,
                 ]
             )
         )
     )
示例#16
0
    def test_euclidean_distance(self):
        init_tile = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.euclidean_distance(goal), 5)

        init_tile = np.array([[3, 8, 7], [0, 4, 6], [2, 1, 5]])
        goal_tile = np.array([[0, 4, 3], [2, 6, 7], [5, 8, 1]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.euclidean_distance(goal), 12)

        init_tile = np.array([[0, 2, 3], [1, 4, 5], [8, 7, 6]])
        goal_tile = np.array([[1, 2, 3], [8, 0, 4], [7, 6, 5]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.euclidean_distance(goal), 7)
示例#17
0
 def test_serialise_1(self):
     ''' Serialise with bitflag 1 set '''
     state = State()
     state.bitflags[1] = True
     self.assertEqual(state.serialise_bitflags(), 2)
    def test_state_walk(self):
        init_tile = np.array([[1, 2, 3], [0, 4, 6], [7, 5, 8]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        uninformed_solver = UninformedSearchSolver(init, goal)

        self.assertEqual(len(uninformed_solver.opened), 1)
        self.assertEqual(len(uninformed_solver.closed), 0)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 3)
        self.assertEqual(len(uninformed_solver.closed), 1)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 5)
        self.assertEqual(len(uninformed_solver.closed), 2)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 5)
        self.assertEqual(len(uninformed_solver.closed), 3)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 5)
        self.assertEqual(len(uninformed_solver.closed), 4)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 6)
        self.assertEqual(len(uninformed_solver.closed), 5)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 7)
        self.assertEqual(len(uninformed_solver.closed), 6)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 8)
        self.assertEqual(len(uninformed_solver.closed), 7)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 9)
        self.assertEqual(len(uninformed_solver.closed), 8)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 10)
        self.assertEqual(len(uninformed_solver.closed), 9)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 10)
        self.assertEqual(len(uninformed_solver.closed), 10)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 10)
        self.assertEqual(len(uninformed_solver.closed), 11)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 10)
        self.assertEqual(len(uninformed_solver.closed), 12)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 10)
        self.assertEqual(len(uninformed_solver.closed), 13)
        uninformed_solver.next_state()

        self.assertEqual(len(uninformed_solver.opened), 10)
        self.assertEqual(len(uninformed_solver.closed), 14)
        with self.assertRaises(StopIteration):
            uninformed_solver.next_state()
示例#19
0
 def test_serialise_1_and_10(self):
     ''' Serialise with bitflags 1 and 10 set '''
     state = State()
     state.bitflags[1] = True
     state.bitflags[10] = True
     self.assertEqual(state.serialise_bitflags(), 2**1 + 2**10)
示例#20
0
 def test_deserialise_0(self):
     ''' Deserialise with no bitflags
     '''
     bitflags = State.deserialise_bitflags(0)
     self.assertEqual(bitflags, {})
示例#21
0
 def test_deserialise_1(self):
     ''' Deserialise expecting 1 bitflag set '''
     bitflags = State.deserialise_bitflags(2)
     self.assertEqual(bitflags, {1: True})
    def read_state(self, file_name=None, output_file_name=None):
        """Read a state file"""

        # basic variables
        config = Config()
        graph = nx.Graph()

        # revert to the default file
        if file_name is None:
            file_name = self.default_file_name

        # read from the file
        with open(file_name, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=' ', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            for row in reader:
                if len(row) == 2:
                    graph.add_edge(int(row[0]), int(row[1]))
                else:
                    print("invalid edge")

        # get the largest connected subgraph
        print("0) edges and nodes: {} - {}".format(graph.number_of_nodes(), graph.number_of_edges()))
        if graph.number_of_nodes() > 0:
            graph = list(nx.connected_component_subgraphs(graph))[0]
        print("1) edges and nodes: {} - {}".format(graph.number_of_nodes(), graph.number_of_edges()))

        # calculate the radius
        radius = nx.radius(graph)
        print("radius: {} > {}".format(radius, radius // 2))

        # choose a random node
        random_node = np.random.choice(graph.nodes())
        paths = nx.single_source_shortest_path_length(graph, random_node, radius // 2)
        print("paths: {}".format(len(paths)))

        # make subgraph using the random node and the radius
        subgraph = nx.Graph(graph.subgraph(paths.keys()))
        print("2) edges and nodes: {} - {}".format(subgraph.number_of_nodes(), subgraph.number_of_edges()))

        # create a dictionary
        node_reference = {}
        for i, node in enumerate(subgraph.nodes()):
            node_reference[node] = i

        # create the default edges
        edges = []
        for i, node in enumerate(subgraph.nodes()):
            edges.append([])
            for neighbor in enumerate(graph[node]):
                if neighbor[1] in node_reference and (not i == node_reference[neighbor[1]]):
                    edges[i].append(node_reference[neighbor[1]])                    

        # calculate the number of edges
        size_edges = 0
        for node in edges:
            size_edges += len(node)
        size_edges = size_edges // 2

        print("3) edges and nodes: {} - {}".format(len(edges), size_edges))

        config.num_nodes = len(edges)

        state = State(config, None, edges)

        reader = StateReader("snap_data.csv" if output_file_name is None else output_file_name)
        reader.write_state(state)
示例#23
0
    def test_reversed_tiles(self):
        # Test row swaps
        init_tile = np.array([[1, 2, 3], [4, 6, 5], [8, 7, 0]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.tile_reversals(goal), 2)

        # Test column swaps
        init_tile = np.array([[1, 2, 6], [4, 8, 3], [7, 5, 0]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.tile_reversals(goal), 2)

        # Test both
        init_tile = np.array([[1, 2, 6], [4, 5, 3], [8, 7, 0]])
        goal_tile = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])

        init = State(init_tile, 0, 0)
        goal = State(goal_tile, 0, 0)

        self.assertEqual(init.tile_reversals(goal), 2)
示例#24
0
 def test_deserialise_1026(self):
     ''' Deserialise expecting 1 and 10 bitflags set '''
     bitflags = State.deserialise_bitflags(2**1 + 2**10)
     self.assertEqual(bitflags, {1: True, 10: True})
示例#25
0
 def test_serialise_no_flags(self):
     ''' Serialise with no bitflags set '''
     state = State()
     self.assertEqual(state.serialise_bitflags(), 0)
示例#26
0
 def __init__(self):
     self._settings = Settings()
     self._state = State()
示例#27
0
# test for pareto.py

from game.state import State, Config
from game.reader import StateReader
from game.pareto import is_pareto_efficient_k0, is_pareto_sets_efficient
import numpy as np
import time
import random

# read and write existing state
reader = StateReader()
state = State(Config())
reader.write_state(state)
state.print_graph()
action_att = 0


def calc_score(state_x, action_a, action_d):
    """Read the data file and reset the score"""
    state_x = reader.read_state()
    score = state_x.make_move(action_a, action_d)
    return score


# choose an attack action
start_time = time.time()
actions = []
for i in range(6):
    for j in range(100):
        action_att = np.random.randint(0, state.size_graph)
        if state.actions_att[action_att] == 1:
示例#28
0
 def init_game(self):
     self.game_over = False
     self.state = State()
     self.state.table.init_deck()