def test_taboo_cells(n):
    problem_file = "./warehouses/warehouse_%s.txt" % str(n)
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    answer = taboo_cells(wh)
    print(set(find_2D_iterator(answer.split('\n'), "X")))
    print(answer)
Exemple #2
0
def test_solve_comparison():
    problem_file = "./warehouses/warehouse_35.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print(wh)

    bfs = True
    elem = True
    macro = True    

    if (bfs):
        sp = SokobanPuzzle(wh)
        start = time.time()
        answer = breadth_first_graph_search(sp).solution()
        end = time.time()
        print("BFS Elem took:", end - start, "secs")
        print(answer)
        
    if (elem):
        start = time.time()
        answer = solve_sokoban_elem(wh)
        end = time.time()
        print("A* elem took:", end - start, "secs")
        print(answer)

    if (macro):
        start = time.time()
        answer = solve_sokoban_macro(wh)
        end = time.time()
        print("A* macro took:", end - start, "secs")
        print(answer)
def test_check_elem_action_seq():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print(wh)
    answer = check_action_seq(wh, ['Right', 'Right', 'Down', 'Left'])
    print(answer)
    assert (answer == expected_answer_1)
def test_taboo_cells():
    problem_file = "./warehouses/warehouse_171.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    #    wh.extract_locations(problem_file.split(sep='\n'))
    answer = taboo_cells(wh)
    print(answer)
    assert (answer == expected_answer_3)
def test_can_go_there():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    answer = can_go_there(wh, (30, 2))
    assert (answer == False)
    answer = can_go_there(wh, (6, 2))
    assert (answer == True)
Exemple #6
0
def test_warehouse_2():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print("\nPuzzle from file")
    print(wh)
    print(wh.worker) # x,y  coords !!
    print(wh.walls)  # x,y  coords !!
Exemple #7
0
def test_solve_sokoban_elem():
    problem_file = "./warehouses/warehouse_27.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    # wh.extract_locations(puzzle_t1.split(sep='\n'))
    print(wh)
    print('\nElementary solution')
    answer = solve_sokoban_elem(wh)
    print(answer)
def test_search():
    problem_file = "./warehouses/warehouse_143.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print(wh)
    sp = SokobanPuzzle(wh)
    start = time.time()
    node = breadth_first_graph_search(sp)
    end = time.time()
    print(node.solution(), "found in", end - start, "seconds")
def test_can_go_there():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    answer = can_go_there(wh, (30, 2))
    if answer == False:
        print("Test_can_go_there() test 1 pass")
    answer = can_go_there(wh, (6, 2))
    if answer == True:
        print("Test_can_go_there() test 2 pass")
Exemple #10
0
def test_can_go_there():
    problem_file = "./warehouses/warehouse_02.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print(wh)
    answer = can_go_there(wh,(2,6))
    #assert( answer ==  False)
    answer = can_go_there(wh,(2,6))
    #assert( answer ==  True)
    print(answer)
Exemple #11
0
def test_can_go_there():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print(wh)
    print(wh.worker)
    answer = can_go_there(wh,(30,2))
    assert( answer ==  False)
    answer = can_go_there(wh,(6,4))
    assert( answer ==  True)
    print('We did it!')
Exemple #12
0
def test_check_elem_action_seq():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    print('Initial state \n', wh ,'\n')
    answer = check_action_seq(wh, ['Right', 'Right','Down'])
    
    if same_multi_line_strings(answer,expected_answer_1):
        print('Test check_elem_action_seq passed\n')
    else:
        print('** Test check_elem_action_seq failed\n')
Exemple #13
0
def test_solve_sokoban_elem():
    problem_file = "./warehouses/warehouse_99.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    #wh.extract_locations(puzzle_t1.split(sep='\n'))
    print(wh)
    print('\nElementary solution')
    answer = solve_sokoban_elem(wh)
    print(answer)
    if  answer ==  ['Right', 'Right']:
        print('Test solve_sokoban_elem passed\n')
    else:
        print('** Test solve_sokoban_elem failed\n')
Exemple #14
0
def test_taboo_cells():
    problem_file = "./warehouses/warehouse_99.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    answer = taboo_cells(wh)
    # begin debug
    print(answer)
    print(len(answer))
    print(expected_answer_3)
    print(len(expected_answer_3))
    # end debug
    if same_multi_line_strings(answer,expected_answer_3):
        print('Test taboo_cells passed\n')
    else:
        print('** Test taboo_cells failed\n')
Exemple #15
0
def test_warehouse(warehouse_number):
    average_time = 0
    result = None
    for i in range(TESTS_PER_WAREHOUSE):
        problem_file = "./warehouses/warehouse_{:02d}.txt".format(
            warehouse_number)
        wh = Warehouse()
        wh.read_warehouse_file(problem_file)
        start_time = time.process_time()
        result = solve_sokoban_elem(wh)
        average_time += (time.process_time() -
                         start_time) / TESTS_PER_WAREHOUSE
        print("{}%".format((i + 1) * 100 / TESTS_PER_WAREHOUSE))

    with open(DATA_FILENAME, 'a') as file:
        file.write("{:02d},{},{}\n".format(warehouse_number, average_time,
                                           result))
Exemple #16
0
class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.configure(background="black")
        self.master.title("Sokoban v%s" % (__version__))
        self.master.resizable(0, 0)
        self.image_dict = {
            'wall':
            tk.PhotoImage(file=os.path.join(_ROOT, 'images/wall.gif')),
            'target':
            tk.PhotoImage(file=os.path.join(_ROOT, 'images/hole.gif')),
            'box_on_target':
            tk.PhotoImage(
                file=os.path.join(_ROOT, 'images/crate-in-hole.gif')),
            'box':
            tk.PhotoImage(file=os.path.join(_ROOT, 'images/crate.gif')),
            'worker':
            tk.PhotoImage(file=os.path.join(_ROOT, 'images/player.gif')),
            'smiley':
            tk.PhotoImage(file=os.path.join(_ROOT, 'images/smiley.gif')),
            'worker_on_target':
            tk.PhotoImage(
                file=os.path.join(_ROOT, 'images/player-in-hole.gif')),
        }
        icon = self.image_dict['box']
        self.warehouse_symbol = {
            'wall': '#',
            'target': '.',
            'box_on_target': '*',
            'box': '$',
            'worker': '@',
            'worker_on_target': '!',
            'floor': ' '
        }
        self.direction_offset = {
            'Left': (-1, 0),
            'Right': (1, 0),
            'Up': (0, -1),
            'Down': (0, 1)
        }  # (x,y) = (column,row)

        self.master.tk.call('wm', 'iconphoto', self.master._w, icon)
        self.create_menu()

        self.DEFAULT_SIZE = 200
        self.frame = tk.Frame(self,
                              height=self.DEFAULT_SIZE,
                              width=self.DEFAULT_SIZE)
        self.frame.grid()
        self.default_frame()
        self.cells = {
        }  # dict with key (x,y) and value Label widget to keep track of the Labels in the grid
        self.level_file_name = None
        self.warehouse = Warehouse()

    def key(self, event):
        if event.keysym in ('Left', 'Right', 'Up', 'Down'):
            self.move_player(event.keysym)
        if event.keysym in ('r', 'R'):
            self.restart_level()

    def create_menu(self):
        root = self.master
        menu = tk.Menu(root)
        user_menu = Menu(self)
        root.config(menu=menu)

        file_menu = tk.Menu(menu)
        menu.add_cascade(label="File", menu=file_menu)
        file_menu.add_command(label="Restart", command=self.restart_level)
        file_menu.add_command(label="Open...", command=user_menu.OpenFile)
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=menu.quit)

        help_menu = tk.Menu(menu)
        menu.add_cascade(label="Help", menu=help_menu)
        help_menu.add_command(label="About", command=user_menu.About)

    def default_frame(self):
        start_width = 50
        start_label = tk.Label(self.frame,
                               text="\n *** Welcome to Sokoban! ***\n",
                               width=start_width)
        start_label.grid(row=0, column=0)

        start_label2 = tk.Label(self.frame,
                                text="To play: File -> Open\n",
                                width=start_width)
        start_label2.grid(row=1, column=0)

        start_label3 = tk.Label(
            self.frame,
            text="To reset current warehouse: press the 'r' key \n",
            width=start_width)
        start_label3.grid(row=3, column=0)

    def clear_level(self):
        self.frame.destroy()
        self.frame = tk.Frame(self)
        self.frame.grid()
        self.warehouse = Warehouse()  # warehouse
        self.cells = {}

    def start_level(self):
        self.clear_level()
        self.warehouse.read_warehouse_file(self.level_file_name)
        self.master.title("Sokoban v%s - %s" %
                          (__version__, self.level_file_name.split("/")[-1]))
        self.fresh_display()

    def restart_level(self):
        if self.level_file_name:
            self.start_level()

    def fresh_display(self):
        '''
        First display of the warehouse
        Setup the self.cells dictionary
        '''
        for x, y in self.warehouse.walls:
            w = tk.Label(self.frame, image=self.image_dict['wall'])
            w.grid(row=y, column=x)
            self.cells[(x, y)] = w
        for x, y in self.warehouse.targets:
            w = tk.Label(self.frame, image=self.image_dict['target'])
            w.grid(row=y, column=x)
            self.cells[(x, y)] = w
        for x, y in self.warehouse.boxes:
            if (x, y) in self.warehouse.targets:
                w = self.cells[(x, y)]
                w['image'] = self.image_dict['box_on_target']
            else:
                w = tk.Label(self.frame, image=self.image_dict['box'])
                w.grid(row=y, column=x)
            self.cells[(x, y)] = w
        x, y = self.warehouse.worker
        if (x, y) in self.warehouse.targets:
            w = self.cells[(x, y)]
            w['image'] = self.image_dict['worker_on_target']
        else:
            w = tk.Label(self.frame, image=self.image_dict['worker'])
            w.grid(row=y, column=x)
            self.cells[(x, y)] = w
        self.pack()

    def move_player(self, direction):
        '''
        direction in ['Left', 'Right', 'Up', 'Down']:
        Check whether the worker is pushing a box
        '''
        x, y = self.warehouse.worker
        ##        print 'worker x,y = ',x,y
        xy_offset = self.direction_offset[direction]
        ##        print 'xy_offset = ', xy_offset
        next_x, next_y = x + xy_offset[0], y + xy_offset[
            1]  # where the player will go if possible
        ##        print 'next_x , next_y = ', next_x , next_y
        # Let's find out if it is possible to move the player in this direction
        if (next_x, next_y) in self.warehouse.walls:
            return  # impossible move
        if (next_x, next_y) in self.warehouse.boxes:
            if self.try_move_box(
                (next_x, next_y),
                (next_x + xy_offset[0], next_y + xy_offset[1])) == False:
                return  # box next to the player could not be pushed
        # now, the cell next to the player must be empty
        # we still have to move the player


##        print 'let s move the player! '
        w = self.cells[(
            x, y)]  # Label widget in the cell currently containing the player
        del self.cells[(x, y)]
        w.destroy()
        w = tk.Label(self.frame)  #, image=self.image_dict['worker'])
        w.grid(row=next_y, column=next_x)  # move it to the next cell
        self.cells[(next_x, next_y)] = w
        self.warehouse.worker = (next_x, next_y)
        # Test whether the appearance of the player need to change on the next cell
        if (next_x, next_y) in self.warehouse.targets:
            w['image'] = self.image_dict['worker_on_target']
        else:
            w['image'] = self.image_dict['worker']
        # update the cell where the player was
        if (x, y) in self.warehouse.targets:
            w = tk.Label(self.frame, image=self.image_dict['target'])
            w.grid(row=y, column=x)
            self.cells[(x, y)] = w
        puzzle_solved = all(z in self.warehouse.targets
                            for z in self.warehouse.boxes)
        if puzzle_solved:
            x, y = self.warehouse.worker
            w = self.cells[(
                x,
                y)]  # Label widget in the cell currently containing the player
            del self.cells[(x, y)]
            w.destroy()
            w = tk.Label(self.frame, image=self.image_dict['smiley'])
            w.grid(row=y, column=x)
            self.cells[(x, y)] = w
        self.pack()

    def try_move_box(self, location, next_location):
        '''
        location and next_location are (x,y) tuples
        Move the box  from 'location' to 'next_location'
        Note that we assume that there is a wall around the warehouse!
        Return True if the box was moved, return False if the box could not be moved
        Update the position and the image of the Label widget for this box
        '''
        x, y = location
        next_x, next_y = next_location

        assert (x, y) in self.warehouse.boxes
        if (next_x, next_y) not in self.warehouse.walls and (
                next_x, next_y) not in self.warehouse.boxes:
            # can move the box!
            # clean cell (x,y)
            w = self.cells[(x, y)]
            del self.cells[(x, y)]
            w.destroy()
            # clean cell (next_x,next_y)
            if (next_x, next_y) in self.cells:
                assert (next_x, next_y) in self.warehouse.targets
                w = self.cells[(next_x, next_y)]
                del self.cells[(next_x, next_y)]
                w.destroy()
            # new Label for the moved box
            w = tk.Label(self.frame)
            if (next_x, next_y) in self.warehouse.targets:
                w['image'] = self.image_dict['box_on_target']
            else:
                w['image'] = self.image_dict['box']
            w.grid(row=next_y, column=next_x)
            self.cells[(next_x, next_y)] = w
            self.warehouse.boxes.remove((x, y))
            self.warehouse.boxes.append((next_x, next_y))
            # we don't have to update (x,y), this will be done while moving the player
            return True  # move successful
        else:
            return False  # box was blocked
Exemple #17
0
def test_solve_sokoban_elem():
    problem_file = "./warehouses/warehouse_01.txt"
    wh = Warehouse()
    wh.read_warehouse_file(problem_file)
    answer = solve_sokoban_elem(wh)
    assert (answer == ['Right', 'Right'])