def score(g, verbose=False): '''generate a score on how advanced techniques are needed to solve''' score = 0 opts = [[range(9) if g[x][y] == -1 else [] for y in xrange(9)] for x in xrange(9)] req = [[g[x][y] in (0, 8) for y in xrange(9)] for x in xrange(9)] # true if tile must be a 1 or 9 col_sums = g[9] row_sums = g[10] col_sets = [list(SUM_SETS[s]) for s in col_sums] row_sets = [list(SUM_SETS[s]) for s in row_sums] if verbose: print 'STARTING POSITION 0' print grid_to_string(g) while any(g[x][y] == -1 for x, y in product(xrange(9), xrange(9))): s, name, display = make_step(g, opts, req, col_sets, row_sets, col_sums, row_sums) if s == -1: break score += s if verbose: print name + ' ' + str(score) if display: print grid_to_string(g) stdout.flush() for x, y in product(xrange(9), xrange(9)): if g[x][y] == -1: return -1 return score
def score(g, verbose = False): '''generate a score on how advanced techniques are needed to solve''' score = 0 opts = [[range(9) if g[x][y] == -1 else [] for y in xrange(9)] for x in xrange(9)] if verbose: print 'STARTING POSITION 0' print grid_to_string(g) while True: s, name, display = make_step(g, opts) if s == -1: break score += s if verbose: print name+' '+str(score) if display: print grid_to_string(g) stdout.flush() for x, y in product(xrange(9), xrange(9)): if g[x][y] == -1: return -1 return score
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")
def test_grid_empty(): grid = [' '] player = Player() try: grid_to_string(grid, player) except AttributeError as e: assert str(e) == "'str' object has no attribute 'display'"
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.'
def test_grid(): #positive test case: board_simple.txt player = Player() game = Game("board_simple.txt", player) assert grid_to_string( read_lines("board_simple.txt"), player) == "**A**\n* *\n**Y**\n\nYou have 0 water buckets." player = Player() game = Game("board_super_hard.txt", player) assert grid_to_string( read_lines("board_super_hard.txt"), player ) == "*A*************\n* 2 * W*\n* *** ** **** *\n* * WW* 1 *\n* ***** ***** *\n* 2 * ** *F*\n*W**W*** FFF*\n* 1********FFF*\n*************Y*\n\nYou have 0 water buckets."
def test_grid(): """ create a new grid """ string_grid = grid_to_string(New8.grid, New8.Player1) # positive cases """ check string returned """ assert type(string_grid) == str, 'Test Failed!' """ check contents of string """ assert string_grid == "A*X**\n* *\n**Y**\n\nYou have 0 water buckets.\n", 'Test Failed!' """ check grid changes work - changing second wall cell to AIR cell """ New77 = Game(filename) New77.Player1.grid_changes = True New77.Player1.change_coordinates.append([[0, 1]]) string_grid = grid_to_string(New77.grid, New77.Player1) assert type(string_grid) == str, 'Test Failed!' assert string_grid == "A X**\n* *\n**Y**\n\nYou have 0 water buckets.\n", 'Test Failed!' New77.Player1.change_coordinates = None New77.Player1.grid_changes = False """ confirm water buckets increase updated in string """ New9 = Game(filename) New9.Player1.num_water_buckets += 1 string_grid1 = grid_to_string(New9.grid, New9.Player1) assert string_grid1 == "A*X**\n* *\n**Y**\n\nYou have 1 water bucket.\n", 'Test Failed!' # negative """ passing string grid instead of cell grid """ try: stringy = grid_to_string('x***', New7.Player1) except ValueError: pass else: print("Test Failed!") # list of cells instead of list of list of cells try: stringy = grid_to_string([Wall(), Start(), End()], New7.Player1) except TypeError: pass else: print("Test Failed!") #corner/edge """ 1d grid horizontal """ one_dimensional_grid = grid_to_string( [[Wall(), Start(), End()]], New9.Player1) assert one_dimensional_grid == 'AXY\n\nYou have 1 water bucket.\n' """ 1d grid vertical """ one_dimensional_grid2 = grid_to_string([[Wall()], [Start()], [End()]], New9.Player1) assert one_dimensional_grid2 == 'A\nX\nY\n\nYou have 1 water bucket.\n' """ 1cell grid """ try: one_cell_grid = grid_to_string([[Start()]], New7.Player1) except ValueError: pass else: print('Test Failed')
def test_grid_non_rectangular(): '''tests normal operation of grid_to_function. Should return single string which displays player position on board and water buckets''' player=Player.__new__(Player) player.display='A' player.col=1 player.row=2 player.num_water_buckets=2 assert grid_to_string(parse(config_2),player)=='*X*\n* *\n*A****\n* Y\n******\n\nYou have 2 water buckets.\n','Failed non rectangular grid: wrong string returned'
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')
def test_grid_player_not_air(): '''tests behaviour of grid_to_function when player postion is on a non whitespace display cell.'A' should replace pre-existing display''' player=Player.__new__(Player) player.display='A' player.col=5 player.row=2 player.num_water_buckets=0 assert grid_to_string(parse(config_1),player)=='*X*************\n* 1 * *\n* ***A** **** *\n* 1********F *\n*************Y*\n\nYou have 0 water buckets.\n','Failed non Air grid: wrong string returned'
def test_grid_water_buckets(): '''tests behaviour of grid_to_function when player has non-zero water buckets''' player=Player.__new__(Player) player.display='A' player.col=1 player.row=1 player.num_water_buckets=8 assert grid_to_string(parse(config_1),player)=='*X*************\n*A 1 * *\n* ***W** **** *\n* 1********F *\n*************Y*\n\nYou have 8 water buckets.\n','Failed water buckets grid: wrong string returned'
def test_grid_normal(): '''tests normal operation of grid_to_function. Should return single string which displays player position on board and water buckets''' player=Player.__new__(Player) player.display='A' player.col=1 player.row=0 player.num_water_buckets=0 assert grid_to_string(parse(config_1),player)=='*A*************\n* 1 * *\n* ***W** **** *\n* 1********F *\n*************Y*\n\nYou have 0 water buckets.\n','Failed normal grid: wrong string returned'
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!")
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!")
def read_cells(self, grid): """Turns a grid and the default player into a string, invoking grid_to_string() from grid.py Arguments: grid -- list of list of Cells Returns: str: a string representation of the grid and default player """ return grid_to_string(grid, self.player)
def display(self): print(grid_to_string(self.grid, self.player)) print() if self.print_water > 0: print("Thank the Honourable Furious Forest, you've found a bucket of water!") print() self.print_water = self.print_water - 1 elif self.print_fire > 0: self.player.reverse_move() self.player.lose_game() elif self.print_live_fire > 0: print( "With your strong acorn arms, you throw a water bucket at the fire. You acorn roll your way through the extinguished flames!") print() self.print_live_fire -= 1 elif self.print_wall > 0: print("You walked into a wall. Oof!") print() self.print_wall -= 1 elif self.print_magic > 0: print("Whoosh! The magical gates break Physics as we know it and opens a wormhole through space and time.") self.print_magic -= 1 print() elif self.print_end_game > 0: if len(self.player.moves) == 1: print() print( "You 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.") print() print("You made {} move.".format(len(self.player.moves))) print("Your move: {}".format(self.player.integration_moves())) print() print("=====================\n====== YOU WIN! =====\n=====================") exit() else: print() print( "You 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.") print() print("You made {} moves.".format(len(self.player.moves))) print("Your moves: {}".format(self.player.integration_moves())) print() print("=====================\n====== YOU WIN! =====\n=====================") exit() elif self.bad_input > 0: print("Please enter a valid move (w, a, s, d, e, q).") print() self.bad_input -= 1
def test_grid2(): #edge case with 0 waterbucket at the initial postion grid = [[Wall(), Wall(), Start(), Wall(), Wall()], [Wall(), Water(), Teleport('1'), Wall(), Wall()], [Wall(), Air(), Fire(), Teleport('1'), Wall()], [Wall(), Wall(), End(), Wall(), Wall()]] player = Player() actual = grid_to_string(grid, player) excepted = 'A*X**\n*W1**\n* F1*\n**Y**\n\nYou have 0 water buckets.' assert actual == excepted, 'testcase test_grid2 failed.'
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")
def test_grid3(): #edge case with 1 waterbucket at the other position grid = [[Wall(), Wall(), Start(), Wall(), Wall()], [Wall(), Water(), Teleport('1'), Wall(), Wall()], [Wall(), Air(), Fire(), Teleport('1'), Wall()], [Wall(), Wall(), End(), Wall(), Wall()]] player = Player() player.row = 2 player.col = 1 player.num_water_buckets = 1 actual = grid_to_string(grid, player) excepted = '**X**\n*W1**\n*AF1*\n**Y**\n\nYou have 1 water bucket.' assert actual == excepted, 'tesecase test_grid3 failed.'
def starting(self, player): '''getter method: let the player in the starting point X :param: player -- receive an object of player :return a map with the player at starting point X ''' for row in range(len(self.map)): for col in range(len(self.map[row])): if self.map[row][col].display == 'X': player.row = row player.col = col map = grid_to_string(self.map, player) return map
def test_grid1(): #postive testcase with 2 waterbucket at the other position grid = [[Wall(), Wall(), Start(), Wall(), Wall()], [Wall(), Water(), Teleport('1'), Wall(), Wall()], [Wall(), Air(), Fire(), Teleport('1'), Wall()], [Wall(), Wall(), End(), Wall(), Wall()]] player = Player() player.row = 1 player.col = 1 player.num_water_buckets = 2 actual = grid_to_string(grid, player) excepted = '**X**\n*A1**\n* F1*\n**Y**\n\nYou have 2 water buckets.' assert actual == excepted, 'testcase test_grid1 failed.'
def gameMove(self, move): '''Sets player position, calls the step() method of a corresponding cell and then returns display of the game. If position is out of game bounds then a wall step() method is called''' try: if move=='q': self.state='quit' return self.player.move(move) self.temp_move=move if self.player.row>self.bounds[0] or self.player.col>self.bounds[1] or self.player.col<0 or self.player.row<0: msg=self.cells[0][0].step(self) else: msg=self.cells[self.player.row][self.player.col].step(self) except ValueError as e: msg=str(e) game_display=(grid_to_string(self.cells,self.player)) if msg!=None: game_display+='\n' + msg return game_display
def normal(self, player): '''getter method: normal map :param: player -- receive an object of player :return: normal map ''' self.throw_water_bucket = False self.get_water_bucket = False self.tp = False row = player.row col = player.col tp_gate = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] if self.move_illegal == False: if self.map[row][col].display == 'W': self.water_wall(row, col, player) if self.map[row][col].display == 'F': self.fire_wall(row, col, player) if self.map[row][col].display in tp_gate: if self.wait == False: self.teleport(row, col, player) elif self.wait == True: self.teleport(row, col, player) if self.map[row][col].display == 'Y': self.win = True map = grid_to_string(self.map, player) return map
def grid_output(self, end_lines, player): return grid_to_string(end_lines, player)
def map_load(self): print(grid_to_string(self.map, self.player))
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': print('\nBye!') break move = Player.move(player, player_input)
def print_grid_to_string(self): print(grid_to_string(self.grid, self.player))