def test_grid():
    # Positive tests
    # 1.The first test case for grid_to_string function
    # 2.create one grid
    grid_one = read_lines("board_simple.txt")
    # 3.create one player
    player = Player(0, 2)
    # 4.test if grid_to_string function work fine
    assert grid_to_string(grid_one,
                          player) == "**A**\n*   *\n**Y**\n\nYou have 0 " \
                                     "water buckets.", "Test one did not pass"
    print("Test case 1 for Grid pass")

    # 5.The second test case for grid_to_string function
    # 6.create the second grid for testing
    grid_two = read_lines("board_medium.txt")
    # 7.creat one player
    player = Player(0, 2)
    # 8.test if grid_to_string function works fine
    assert grid_to_string(grid_two, player) == "**A***\n*    *\n* ** *\n*    *\n*    *\n" \
                                               "****Y*\n\nYou have 0 water buckets.", "Test t" \
                                                                                      "wo did not pass "
    print("Test case 2 for Grid pass")

    # The third test case for grid_to_string function
    grid_three = read_lines("board_normal.txt")
    player = Player(0, 2)
    assert grid_to_string(grid_three
                          , player) == "**A****\n*  " \
                                       "3  *\n* 3   *\n****Y**\n" \
                                       "\nYou have 0 water " \
                                       "buckets.", "Test three did not pass."
    print("Test case 3 for Grid pass")
Ejemplo n.º 2
0
def test_grid():
    assert grid_to_string(parse(read_lines("board_test.txt")), p) == """*X*
*Y*

You have 0 water buckets.""", "Test case 1 failed"
    print("Simple Grid to String passed!")

    assert grid_to_string(parse(read_lines("board_test.txt")), o) == """*X*
*Y*

You have 1 water bucket.""", "Test case 2 failed"
    print("Increase Water Bucket to String passed!")

    assert grid_to_string(parse(read_lines("board_test.txt")), c) == """*X*
*Y*

You have p water buckets.""", "Test case 3 failed"
    print("Various amounts of water buckets case passed!")

    assert grid_to_string(parse(read_lines("board_test.txt")), d) == """*X*
*Y*

You have  water buckets.""", "Test case 4 failed"
    print("No water buckets case passed!")

    assert grid_to_string(parse(read_lines("board_test.txt")), e) == """*X*
*Y*

You have !@#$%^&*() water buckets.""", "Test case 5 failed"
    print("Various amounts of water buckets case 2 passed!")
    try:
        grid_to_string((1), e)
        print("Test Case Grid to String TypeError Failed!")
    except TypeError:
        print("Test Case Grid to String TypeError Passed!")
Ejemplo n.º 3
0
def test_parse():

    try:
        grid_bad_letter = read_lines("board_bad_letter.txt")
        assert False
    except ValueError:
        print("Test 04: Bad Letter Check passed!")
    except AssertionError:
        print("Test 04: Bad Letter Check failed! (did not throw an exception)")

    try:
        grid_no_starting = read_lines("board_no_starting.txt")
        assert False
    except ValueError:
        print("Test 05: Starting Point Check passed!")
    except AssertionError:
        print("Test 05: Starting Point Check failed! (did not throw an exception)")

    try:
        grid_no_ending = read_lines("board_no_ending.txt")
        assert False
    except ValueError:
        print("Test 06: Ending Point Check passed!")
    except AssertionError:
        print("Test 06: Ending Point Check failed! (did not throw an exception)")

    try:
        grid_mismatch_port = read_lines("board_mismatch_port.txt")
        assert False
    except ValueError:
        print("Test 07: Port Pad Match Check passed!")
    except AssertionError:
        print("Test 07: Port Pad Match Check failed! (did not throw an exception)")
Ejemplo n.º 4
0
def test_read_lines():
    ''' Empty configuration file '''
    try:
        read_lines('board_empty.txt')
    except AssertionError:
        print("read_lines: Testcase 1 failed (did not throw an exception)")
    except ValueError:
        pass
Ejemplo n.º 5
0
def test_read_lines():
    #test board_medium.txt: positive test case
    assert isinstance(read_lines("board_medium.txt")[0][2],
                      Start), "Coordinate 0,2 is not a Start Cell"
    assert isinstance(read_lines("board_medium.txt")[5][4],
                      End), "Coordinate 5,4 is not a End Cell"
    assert isinstance(read_lines("board_medium.txt")[1][1],
                      Air), "Coordinate 1,1 is not a Air Cell"
    assert isinstance(read_lines("board_medium.txt")[0][5],
                      Wall), "Coordinate 0,5 is not a Wall Cell"

    #test file with grid only made of Fire cells: edge case
    all_fire = True
    for row in read_lines("fire.txt"):
        for cell in row:
            if isinstance(cell, Fire) == False and isinstance(
                    cell, Start) == False and isinstance(cell, End) == False:
                all_fire = False
    assert all_fire == True, "Non-fire (or start/end) cell detected."

    #test file with 4 teleports of the same number: negative test case
    value_error_caught = False
    try:
        read_lines("board_four_teleports.txt")
    except:
        ValueError
        value_error_caught = True
    assert value_error_caught == True

    #test file with just XY: edge case
    assert isinstance(read_lines("board_XY.txt")[0][0],
                      Start), "Coordinate 0,0 is not a Start Cell"
    assert isinstance(read_lines("board_XY.txt")[0][1],
                      End), "Coordinate 0,1 is not a End Cell"
Ejemplo n.º 6
0
def test_game():
    game = Game("board_simple.txt")
    grid = read_lines(game.filename)

    coords_result = {
        'X': [[0, 2]],
        ' ': [[1, 1], [1, 2], [1, 3]],
        'Y': [[2, 2]],
        '*': [[0, 0], [0, 1], [0, 3], [0, 4], [1, 0], [1, 4], [2, 0], [2, 1],
              [2, 3], [2, 4]],
        'W': [],
        'F': [],
        '1': [],
        '2': [],
        '3': [],
        '4': [],
        '5': [],
        '6': [],
        '7': [],
        '8': [],
        '9': [],
        'A': []
    }

    try:
        assert game.collect_coords(grid) == coords_result
        print("Test 09: Coordinates Collection passed!")
    except AssertionError:
        print("Test 09: Coordinates Collection failed!")
Ejemplo n.º 7
0
def main():

    if len(sys.argv) < 3:
        print("Usage: python3 solver.py <filename> <mode>")
        sys.exit(0)

    file = sys.argv[1]
    game = Game(file)

    # *** get grid ***
    grid = read_lines(file)

    # *** get coords ***
    game_coords = game.collect_coords(grid)

    # set player to start point
    game.player.row = game_coords['X'][0][0]
    game.player.col = game_coords['X'][0][1]

    if sys.argv[2] == "DFS":
        result, count, trace = dfs(game, game_coords)
    elif sys.argv[2] == "BFS":
        result, count, trace = bfs(game, game_coords)

    return result, count, trace
Ejemplo n.º 8
0
    def __init__(self, filename, player):
        #Initialize game attributes
        self.grid = read_lines(filename)
        self.player = player
        self.display = grid_to_string(self.grid, self.player)
        self.player_coordinate = grid_start(self.grid)
        self.player_col = self.player_coordinate.get_col()
        self.player_row = self.player_coordinate.get_row()
        self.player_water_buckets = 0

        #Initialize move trackers
        self.num_moves = 0
        self.moves_made = []

        #Move effects
        self.hit_wall = False
        self.fire_extinguished = False
        self.has_teleported = False
        self.invalid_move = False
        self.found_water = False
        self.won = False
        self.lost = False
        self.consecutive_waits = 0  #Used to keep solver waiting too many times

        #Initialize player attributes
        self.player.game = self
        self.player.coordinate = self.player_coordinate
        self.player.col = self.player_col
        self.player.row = self.player_row
Ejemplo n.º 9
0
def test_player():
    player = Player()
    ## Testing Player.move() ##
    ## Positive test cases ##
    assert player.move('a') == 'a', 'Positive test case 1 failed, move "a".'
    assert player.move('w') == 'w', 'Positive test case 2 failed, move "w".'
    assert player.move('s') == 's', 'Positive test case 3 failed, move "s".'
    assert player.move('d') == 'd', 'Positive test case 4 failed, move "d".'
    assert player.move('e') == 'e', 'Positive test case 5 failed, move "e".'

    ## Negative test cases ##
    assert player.move(
        5) == None, 'Negative test case 1 failed, non-string move.'

    ## Edge cases ##

    ## Testing Player.initial_player_position() ##

    ## Positive test cases ##
    grid = game_parser.parse(game_parser.read_lines('board_simple.txt'))
    assert player.initial_player_position(grid) == [
        0, 2
    ], 'Positive test case 1 failed.'
    grid = game_parser.parse(game_parser.read_lines('board_medium.txt'))
    assert player.initial_player_position(grid) == [
        0, 2
    ], 'Positive test case 2 failed.'
    grid = game_parser.parse(game_parser.read_lines('board_hard.txt'))
    assert player.initial_player_position(grid) == [
        0, 1
    ], 'Positive test case 3 failed.'
    grid = game_parser.parse(game_parser.read_lines('board.txt'))
    assert player.initial_player_position(grid) == [
        0, 1
    ], 'Positive test case 4 failed.'
    grid = game_parser.parse(game_parser.read_lines('board_test.txt'))
    assert player.initial_player_position(grid) == [
        1, 0
    ], 'Positive test case 5 failed.'

    ## Negative test cases ##
    assert player.initial_player_position(
        'string') == None, 'Negative test case 1 failed.'
    assert player.initial_player_position(
        [1, 2, 3]) == None, 'Negative test case 2 failed.'
    assert player.initial_player_position(
        []) == None, 'Negative test case 3 failed.'
Ejemplo n.º 10
0
def test_grid_simple():
    grid = read_lines('board_simple2.txt')
    game_object = Game('board_simple2.txt')
    game_object.start()
    output = '***\nA Y\n***\n\nYou have 0 water buckets.'
    assert output == grid_to_string(grid,
                                    game_object.player), "Invalid grid display"
    print('Simple grid test passed')
Ejemplo n.º 11
0
 def __init__(self, filename):
     self.filename = filename
     self.moves_made = []
     self.move_ct = 0
     self.player = None
     self.map = read_lines(filename)
     self.message = None
     self.death = False
     self.win = False
Ejemplo n.º 12
0
 def __init__(self, filename):
     self.cells=read_lines(filename)
     self.moves=[]
     self.move_count=0
     self.player=Player(self)
     self.temp_move=''
     self.state='running'
     self.traversed=[]
     self.bounds=[len(self.cells)-1,len(self.cells[0])-1]
Ejemplo n.º 13
0
def test_grid():
    grid = read_lines("board_simple.txt")
    player = Player([0, 0])

    string_result_one = "A*X**\n*   *\n**Y**\n\nYou have 0 water buckets.\n"

    try:
        assert grid_to_string(grid, player) == string_result_one
        print("Test 08: Grid To String passed!")
    except AssertionError:
        print("Test 08: Grid To String failed!")
Ejemplo n.º 14
0
def test_run():
    game = Game("board_simple.txt")
    grid = read_lines("board_simple.txt")

    game_coords = game.collect_coords(grid)

    try:
        assert search_coords(game_coords, [1, 2]) == ' '
        assert search_coords(game_coords, [2, 2]) == 'Y'
        print("Test 10: Coordinates Search passed!\n")
    except AssertionError:
        print("Test 10: Coordinates Search failed!\n")
Ejemplo n.º 15
0
def test_grid():
    player = Player()

    ## Positive test cases ##

    grid = game_parser.parse(game_parser.read_lines('board_simple.txt'))
    assert grid_to_string(grid, player) == "A*X**\n*   *\n**Y**\n\nYou have 0 water buckets.", "Positive test case 1 failed."
    grid = game_parser.parse(game_parser.read_lines('board_medium.txt'))
    assert grid_to_string(grid, player) == "A*X***\n*    *\n* ** *\n*    *\n*    *\n****Y*\n\nYou have 0 water buckets.", "Positive test case 2 failed."
    grid = game_parser.parse(game_parser.read_lines('board_hard.txt'))
    assert grid_to_string(grid, player) == "AX*************\n*       2 *   *\n* *** ** **** *\n* *  W*   1   *\n* ***** ***** *\n*  2 *   ** *F*\n* ** ***      *\n* 1********F  *\n*************Y*\n\nYou have 0 water buckets.", "Positive test case 3 failed."
    grid = game_parser.parse(game_parser.read_lines('board.txt'))
    assert grid_to_string(grid, player) == "AXY*********\n*          *\n*     1    *\n*          *\n***        *\n*1*        *\n************\n\nYou have 0 water buckets.", "Positive test case 4 failed."
    grid = game_parser.parse(game_parser.read_lines('1move.txt'))
    assert grid_to_string(grid, player) == "A*\nXY\n**\n\nYou have 0 water buckets.", "Positive test case 5 failed."

    ## Negative test cases ##

    grid = game_parser.parse(game_parser.read_lines('board_simple.txt'))
    assert grid_to_string(grid, 'Jack') == None, 'Negative test case 1 failed, player is not a Player object.'
    assert grid_to_string(34, player) == None, 'Negative test case 2 failed, grid is not a list.'
    bad_grid = [1, 2, 'a']
    assert grid_to_string(bad_grid, player) == None, 'Negative test case 3 failed, element in grid is not a list.'

    ## Edge cases ##
    empty_grid = []
    assert grid_to_string(empty_grid, player) == None, 'Edge case 1 failed, empty grid.'
Ejemplo n.º 16
0
    def __init__(self, filename):
        self.player = Player()
        self.filename = filename
        self.moves_made = []
        self.finished = False
        self.lost = False
        self.grid = read_lines(filename)
        self.msg = ''
        self.start()

        # Attributes used by the solver
        self.picked_bucket = False
        self.on_tp_pad = False
Ejemplo n.º 17
0
def solve(maze):
    nums = []
    add = ''
    nums.append(add)
    maze = parse(read_lines(filename))
    while not find_end(maze, add):
        add = nums[0]
        nums.remove(nums[0])
        for j in ["a", "d", "w", "s"]:
            put = add + '{}, '.format(j)
            if valid(maze, put):
                nums.append(put)
    return True
Ejemplo n.º 18
0
 def __init__(self, filename):
     self.exit = False
     self.filename = filename
     self.Player1 = Player()
     self.grid = read_lines(self.filename)
     self.success = False
     self.failure = False
     self.teleport = False
     self.total_moves = []
     self.total_moves_count = 0
     self.oob = False
     self.incorrect_input = False
     self.e_count = 0
 def __init__(self, filename):
     self.filename = filename
     self.grid = read_lines(filename)
     self.row = 0
     self.col = 0
     self.find_x()
     self.player = Player(self.row, self.col)
     self.print_water = 0
     self.print_fire = 0
     self.print_live_fire = 0
     self.print_wall = 0
     self.print_magic = 0
     self.print_end_game = 0
     self.bad_input  = 0
Ejemplo n.º 20
0
def test_game():
    player = Player()
    player.row = 0
    player.col = 1
    game = Game('board_hard.txt')
    grid = parse(read_lines('board_hard.txt'))

    ## Testing gameMove() ##

    ## Positive test cases ##
    assert game.gameMove('a') == [1, 'a, '], 'Positive testcase 1 failed.'
    assert game.gameMove('d') == [2, 'a, d, '], 'Positive testcase 2 failed.'
    assert game.gameMove('s') == [3,
                                  'a, d, s, '], 'Positive testcase 3 failed.'
    assert game.gameMove('w') == [4, 'a, d, s, w, '
                                  ], 'Positive testcase 5 failed.'

    ## Negative test cases ##
    assert game.gameMove(
        1) == None, 'Negative testcase 1 failed, integer type move.'
    assert game.gameMove(
        []) == None, 'Negative testcase 2 failed, list type move.'

    ## Edge cases ##

    ## move_action() ##

    ## Positive test cases ##
    assert game.move_action(grid, player,
                            's') == '', 'Postive testcase 1 failed.'
    assert game.move_action(grid, player,
                            'a') == '', 'Positve testcase 2 failed.'

    ## Negative test cases ##
    assert game.move_action(grid, player,
                            1) == None, 'Negative testcase 1 failed'

    ## Edge cases ##
    player.row = -1
    player.col = 1
    assert game.move_action(
        grid, player, 'w'
    ) == '\nYou walked into a wall. Oof!\n', 'Edgecase 1 failed, should act as a wall when stepping off the grid.'
    player.row = 1
    player.col = -1
    assert game.move_action(
        grid, player, 'a'
    ) == '\nYou walked into a wall. Oof!\n', 'Edgecase 2 failed, should act as a wall when stepping off the grid.'
Ejemplo n.º 21
0
def main():
    file = sys.argv[1]
    game = Game(file)

    grid = read_lines(file)
    game_coords = game.collect_coords(grid)

    game.player.row = game_coords['X'][0][0]
    game.player.col = game_coords['X'][0][1]

    if sys.argv[2] == "DFS":
        result, count, trace = dfs(game, game_coords)
    elif sys.argv[2] == "BFS":
        result, count, trace = bfs(game, game_coords)

    return result, count, trace
Ejemplo n.º 22
0
def test_grid_super_hard():
    grid = read_lines('board_super_hard.txt')
    game_object = Game('board_super_hard.txt')
    output = """*A*************
*       2 *  W*
* *** ** **** *
* * WW*   1   *
* ***** ***** *
*  2 *   ** *F*
*W**W***   FFF*
* 1********FFF*
*************Y*

You have 0 water buckets."""
    assert output == grid_to_string(grid,
                                    game_object.player), "Invalid grid display"
    print("Super hard grid test passed")
Ejemplo n.º 23
0
def test_parse():
    assert type(parse(read_lines("parsetest1.txt"))[0]
                [0]) == Start, "Parse Start Case Failed!"
    print("Parse Start Case Passed!")
    assert type(parse(
        read_lines("parsetest1.txt"))[0][1]) == End, "Parse End Case Failed!"
    print("Parse End Case Passed!")
    assert type(parse(
        read_lines("parsetest1.txt"))[0][2]) == Wall, "Parse Wall Case Failed!"
    print("Parse Wall Case Passed!")
    assert type(parse(read_lines("parsetest1.txt"))[0]
                [3]) == Teleport, "Parse Teleport Case Failed!"
    print("Parse Teleport Case Passed!")
    assert type(parse(read_lines("parsetest1.txt"))[0]
                [4]) == Teleport, "Parse Teleport Case Failed!"
    print("Parse Teleport Case Passed!")
    assert type(parse(
        read_lines("parsetest1.txt"))[0][5]) == Fire, "Parse Fire Case Failed!"
    print("Parse Fire Case Passed!")
    assert type(parse(read_lines("parsetest1.txt"))[0]
                [6]) == Water, "Parse Water Case Failed!"
    print("Parse Water Case Passed!")
    try:
        parse(read_lines("parsetest2.txt"))
        print("Parse ValueError case 1 Failed!")
    except ValueError:
        print("Parse ValueError case 1 Passed!")
    try:
        parse(["Y"])
        print("Parse Missing X Failed!")
    except ValueError:
        print("Parse Missing X Passed!")
    try:
        parse(["X"])
        print("Parse Missing Y Failed!")
    except ValueError:
        print("Parse Missing Y Passed!")
    try:
        parse(["XY1"])
        print("Parse Teleporter Pairs Failed!")
    except ValueError:
        print("Parse Teleporter Pairs Passed!")
Ejemplo n.º 24
0
def test_cells():
    game = Game('board_hard.txt')
    player = Player()
    grid = game_parser.parse(game_parser.read_lines('board_hard.txt'))

    ## Testing cell.step() ##
    cell = Start('X')
    assert cell.step(game, player, grid,
                     'a') == '', 'cells testcase 1 failed, Start.step.'
    cell = End('Y')
    assert cell.step(
        game, player, grid, 'a'
    ) == 'end of game - successful', 'cells testcase 2 failed, End.step.'
    cell = Air(' ')
    assert cell.step(game, player, grid,
                     'w') == '', 'cells testcase 3 failed, Air.step.'
    cell = Wall('*')
    assert cell.step(
        game, player, grid, 's'
    ) == '\nYou walked into a wall. Oof!\n', 'cells testcase 4 failed, Wall.step.'
    cell = Fire('F')
    assert cell.step(
        game, player, grid, 'd'
    ) == 'end of game - unsuccessful', 'cells testcase 5 failed, Fire.step with no water buckets.'
    player.num_water_buckets = 1
    assert cell.step(game, player, grid, 'a') == '\nWith your strong acorn arms, you throw a water bucket at the fire.' \
                'You acorn roll your way through the extinguished flames!\n', 'cells testcase 6 failed, Fire.step with water bucket.'
    cell = Water('W')
    assert cell.step(
        game, player, grid, 's'
    ) == "\nThank the Honourable Furious Forest, you've found a bucket of water!\n", 'cells testcase 7 failed, Water.step'
    assert cell.step(
        game, player, grid, 'a'
    ) == '', 'cells testcase 8 failed, Water.step should only function when stepped on for the first time.'
    cell = Teleport('1')
    assert cell.step(game, player, grid, 'a') == '\nWhoosh! The magical gates break Physics as we know ' \
            'it and opens a wormhole through space and time.\n', 'cells testcase 9 failed, Teleport.step.'
Ejemplo n.º 25
0
def test_parse():
    assert True

    # positive cases
    """testing normal output of cells"""
    grid = parse(["*XY"])
    assert type(grid[0][0]) == type(Wall()), "Failed Parse!"
    assert type(grid[0][1]) == type(Start()), "Failed Parse!"
    assert type(grid[0][2]) == type(End()), "Failed Parse!"
    """testing normal output of cells"""
    grid1 = ["*XY", "WF*", "11*"]
    grid1p = parse(grid1)
    assert type(grid1p[1][0]) == type(Water()), "Failed Parse!"
    assert type(grid1p[1][1]) == type(Fire()), "Failed Parse!"
    assert type(grid1p[1][2]) == type(Wall()), "Failed Parse!"
    assert type(grid1p[2][0]) == type(Teleport(1)), "Failed Parse!"
    assert type(grid1p[2][1]) == type(Teleport(1)), "Failed Parse!"
    assert type(grid1p[2][2]) == type(Wall()), "Failed Parse!"

    # negative cases
    """ Type error for No file - readlines"""
    try:
        read_lines(None)
    except TypeError:
        pass
    else:
        print("Test Failed")
    """ two start positions """
    try:
        grid1 = parse(["*XXY"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ two end positions """
    try:
        grid1 = parse(["*XYY"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ Single teleporter """
    try:
        grid1 = parse(["*XA1"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ Single teleporter2 """
    try:
        grid1 = parse(["*XA2"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ 3 teleporter """
    try:
        grid1 = parse(["*XA111"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ 0 teleporter """
    try:
        grid1 = parse(["*XA00"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ no start end or player """
    try:
        grid1 = parse(["***"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ 1cell """
    try:
        grid1 = parse(["*"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ only player """
    try:
        grid1 = parse(["*A"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ no start """
    try:
        grid1 = parse(["*Y"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ no end """
    try:
        grid1 = parse(["X*A"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ lowercase grid """
    try:
        grid1 = parse(["xyA"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ invalid character """
    try:
        grid1 = parse(["XYb"])
    except ValueError:
        pass
    else:
        print("Test failed!")

    # edge cases
    """ uneven lines of grid """
    try:
        grid1 = parse(["X*A", "Y11*"])
    except ValueError:
        pass
    else:
        print("Test failed!")
    """ two cell grid  """
    grid1 = parse(["XY"])
    assert type(grid1[0][0]) == type(Start()), "Failed Parse!"
    assert type(grid1[0][1]) == type(End()), "Failed Parse!"
Ejemplo n.º 26
0
from game import Game
from player import Player
import game_parser
from grid import grid_to_string
import os
import sys

try:
    filename = sys.argv[1]
except IndexError:  ## Checking if a command line argument is given ##
    print('Usage: python3 run.py <filename> [play]')
    exit()

## Running the Game ##
try:
    grid = game_parser.parse(game_parser.read_lines(filename))
    player = Player()
    Player.initial_player_position(player, grid)
    board = grid_to_string(grid, player)
    game = Game(filename)
    print(board)
    print()
except ValueError as e:
    print(e)
    exit()

while True:
    player_input = input("Input a move: ")
    #os.system('clear')
    player_input = player_input.lower()
    if player_input == 'q':
Ejemplo n.º 27
0
 def read_lines_output(self, filename):
     return read_lines(filename)
Ejemplo n.º 28
0
def main():

    if len(sys.argv) < 2:
        print("Usage: python3 run.py <filename> [play]")
        sys.exit(0)

    file = sys.argv[1]
    game = Game(file)

    # *** get grid ***
    try:
        grid = read_lines(game.filename)
    except FileNotFoundError:
        print(file + " does not exist!")
        sys.exit(0)

    # *** get coords ***
    game_coords = game.collect_coords(grid)

    # set player to start point
    game.player.row = game_coords['X'][0][0]
    game.player.col = game_coords['X'][0][1]

    # display initial game board
    game_view = game.read_cells(grid)
    print(game_view)

    # *** initialize important parameters ***
    total_moves = 0
    move_record = ''
    result = 1  # 0 -> loss, 1 -> win
    port_no = -1

    while [game.player.row, game.player.col
           ] != game_coords['Y'][0]:  # break when wins
        cmd = input("Input a move: ").lower()

        # read cmd
        if cmd == 's':
            will_move = game.game_move([1, 0])
        elif cmd == 'w':
            will_move = game.game_move([-1, 0])
        elif cmd == 'a':
            will_move = game.game_move([0, -1])
        elif cmd == 'd':
            will_move = game.game_move([0, 1])
        elif cmd == 'q':
            print("\nBye!")
            sys.exit(0)
        elif cmd == 'e':
            will_move = game.game_move([0, 0])
        else:
            print(game_view)
            print("Please enter a valid move (w, a, s, d, e, q).\n")
            continue

        # check if move is legal
        item = search_coords(game_coords, will_move)

        if item == '*' or item == -1:
            print(game_view)
            print("You walked into a wall. Oof!\n")
            continue

        elif item == 'W':
            game.player.num_water_buckets += 1
        elif item == 'F':
            game.player.num_water_buckets -= 1
        elif item in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
            for coords in game_coords[item]:
                if coords != will_move:
                    will_move = coords
                    break

        # reset previous location
        if port_no == -1:
            grid[game.player.row][game.player.col] = ' '
        else:
            # port should be restored
            grid[game.player.row][game.player.col] = str(port_no)
            port_no = -1

        # display start point
        if game_coords['X']:
            grid[game_coords['X'][0][0]][game_coords['X'][0][1]] = 'X'
        else:
            grid[game.player.row][game.player.col] = 'X'

        # *** move the player ***
        game.player.row = will_move[0]
        game.player.col = will_move[1]

        # update coords and view
        game_coords = game.collect_coords(grid)
        game_view = game.read_cells(grid)

        print(game_view)

        # record move numbers and details
        total_moves += 1
        move_record += cmd + ', '

        # additional displayed message
        if item == 'W':
            print(
                "Thank the Honourable Furious Forest, you've found a bucket of water!\n"
            )
        elif item == 'F':
            if game.player.num_water_buckets < 0:
                print(
                    "\nYou step into the fires and watch your dreams disappear :(.\n"
                )
                result = 0
                break
            print(
                "With your strong acorn arms, you throw a water bucket at the fire. "
                + "You acorn roll your way through the extinguished flames!\n")
        elif item in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
            print(
                "Whoosh! The magical gates break Physics as we know it and opens a wormhole through space and time.\n"
            )
            port_no = int(item)

    if result == 1:
        # Victory Hint
        print(
            "\nYou conquer the treacherous maze set up by the Fire Nation and reclaim the Honourable Furious Forest "
            + "Throne," +
            " restoring your hometown back to its former glory of rainbow and sunshine! Peace reigns over the lands.\n"
        )
    else:
        # Defeat Hint
        print(
            "The Fire Nation triumphs! The Honourable Furious Forest is reduced to a pile of ash "
            +
            "and is scattered to the winds by the next storm... You have been roasted.\n"
        )

    if total_moves == 1:
        print("You made 1 move.")
        print("Your move: " + move_record[:-2] + "\n")
    else:
        print("You made " + str(total_moves) + " moves.")
        print("Your moves: " + move_record[:-2] + "\n")

    if result == 1:
        # Victory Hint
        print("=====================\n"
              "====== YOU WIN! =====\n"
              "=====================")
    else:
        #  Defeat Hint
        print("=====================\n"
              "===== GAME OVER =====\n"
              "=====================")
Ejemplo n.º 29
0
def test_parse():

    lines = read_lines('small_board.txt')
    grid = parse(lines)
    assert type(grid[0][0]) == Wall
    assert type(grid[0][1]) == Start
    assert type(grid[0][2]) == End
    lines = read_lines('board_everything.txt')
    grid = parse(lines)
    assert type(grid[0][0]) == Wall
    assert type(grid[0][1]) == Start
    assert type(grid[0][2]) == Wall
    assert type(grid[0][3]) == Wall
    assert type(grid[1][0]) == Wall
    assert type(grid[1][1]) == Water
    assert type(grid[1][2]) == Fire
    assert type(grid[1][3]) == Wall
    assert type(grid[2][0]) == Wall
    assert type(grid[2][1]) == Teleport
    assert type(grid[2][2]) == Teleport
    assert type(grid[2][3]) == Wall
    assert type(grid[3][0]) == Wall
    assert type(grid[3][1]) == Air
    assert type(grid[3][2]) == Air
    assert type(grid[3][3]) == Wall
    assert type(grid[4][0]) == Wall
    assert type(grid[4][1]) == End
    assert type(grid[4][2]) == Wall
    assert type(grid[4][3]) == Wall

    ## Negative test cases ##
    ''' Bad letter in configuration file '''
    lines = read_lines('board_bad.txt')
    try:
        parse(lines)
        assert False
    except AssertionError:
        print("parse: Testcase 1 failed (did not throw an exception)")
    except ValueError:
        pass
    ''' No ending position '''
    lines = read_lines('board_noend.txt')
    try:
        parse(lines)
        assert False
    except AssertionError:
        print("parse: Testcase 2 failed (did not throw an exception)")
    except ValueError:
        pass
    ''' No starting position '''
    lines = read_lines('board_nostart.txt')
    try:
        parse(lines)
        assert False
    except AssertionError:
        print("parse: Testcase 3 failed (did not throw an exception)")
    except ValueError:
        pass
    ''' Teleport pad with out matching pad '''
    lines = read_lines('board_onepad.txt')
    try:
        parse(lines)
        assert False
    except AssertionError:
        print("parse: Testcase 4 failed (did not throw an exception)")
    except ValueError:
        pass
Ejemplo n.º 30
0
        for x in moves:
            if x == ',' or x == ' ':
                pass
            else:
                counter += 1
        print('Path has {} moves.'.format(counter))
        moves = moves[:-2]
        print('Path: {}'.format(moves))
        return True
    return False
        
def solve(maze):
    nums = []
    add = ''
    nums.append(add)
    maze = parse(read_lines(filename))
    while not find_end(maze, add):
        add = nums[0]
        nums.remove(nums[0])
        for j in ["a", "d", "w", "s"]:
            put = add + '{}, '.format(j)
            if valid(maze, put):
                nums.append(put)
    return True
 
if __name__ == "__main__":
    try:
        maze = parse(read_lines(filename))
        solution_found = solve(maze)
    except IndexError:
        print("There is no possible path.")