def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._tree = Tree(puzzle) # build for UNDO self._previous = [Tree(puzzle)] # build for ATTEMPTS self._children_list = [] if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() print(self._display_config()) # Start the game. self._view.run()
def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type self: Controller @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Construct the state tree self._tree = Tree(puzzle) # Start the game. self._view.run()
def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._data = StateTree(puzzle) # with index [0, 0] self._index = [0, 0] self._undo = False if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run()
def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._puzzle_tree = PuzzleTree(self._puzzle, None) self._previous_moves = [None] if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run()
class Controller: """Class responsible for connection between puzzles and views. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller. # @type _view: View # The view associated with this game controller. # @type _tree: _ControllerTree # The entire tree associated with this controller. # @type _current_tree: _ControllerTree # The tree that represents the current state of the puzzle. def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._tree = _ControllerTree(puzzle) self._current_tree = self._tree if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str A string representation of the puzzle state. """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str The user input. @rtype: (str, bool) The current state of the puzzle or a message and whether the program should end. """ if action == 'exit': return '', True elif action == ':SOLVE': return self._act_solve() elif action == ':SOLVE-ALL': return self._act_solve_all() elif action == ':UNDO': return self._act_undo() elif action == ':ATTEMPTS': return self._act_attempts() elif action == ":HINT": return self._act_hint() elif action == ":DISPLAY": return str(self._puzzle), False else: try: return self._act_move(action) except ValueError: return 'Sorry, that is not a valid move. Please try again.', False def _act_solve(self): """Returns a solution of the puzzle if there is one or 'There are no solutions.' if no solutions exist, and tells the program to end. @type self: Controller @rtype: (str, bool) """ solution = solve(self._puzzle) if solution is not None: return str(solution), True else: return 'There are no solutions.', True def _act_solve_all(self): """Returns all the solution of the puzzle if there exists any or 'There are no solutions.' if no solutions exist, and tells the program to end. @type self: Controller @rtype: (str, bool) """ all_solutions = '' solutions = solve_complete(self._puzzle) for solution in solutions: all_solutions += str(solution) + '\n' if all_solutions != '': return all_solutions, True else: return 'There are no solutions.', True def _act_undo(self): """Returns the previous puzzle state if there is one or 'You have not made any moves.' if there is no previous state, and tells the program not to end. @type self: Controller @rtype: (str, bool) """ previous_state_tree = self._current_tree.find_parent(self._tree) if previous_state_tree is not None: self._current_tree = previous_state_tree[0] self._puzzle = previous_state_tree[1] return self.state(), False else: return 'You have not made any moves.', False def _act_attempts(self): """Prints all the puzzle states that have been reached from this puzzle state and tells the program not to end. @type self: Controller @rtype: (str, bool) """ puzzle_state, move = self._current_tree.return_subtrees() if len(puzzle_state) == 0: return 'You have never reached this state before.', False else: for i in range(len(puzzle_state)): print('You attempted... \n' + str(puzzle_state[i]) + "\nYour move was '" + move[i] + "'\n") return '', False def _act_hint(self): """Returns a hint that will either solve the puzzle, or if the the puzzle leads to no more moves, return 'No possible extensions!'. If the puzzle is already solved, return 'Already at a solution!'. Also, tells the program not to end. @type self: Controller @rtype: (str, bool) """ if type(self._puzzle) == WordLadderPuzzle: hint = hint_by_breadth(self._puzzle) else: hint = hint_by_depth(self._puzzle) return 'Try entering: ' + hint, False def _act_move(self, action): """Updates the state of the puzzle according to <action>. Returns 'Congratulations, you solved it!' and tells the program to end if the puzzle is solved or returns the new state of the puzzle and tells the program not to end. @type self: Controller @type action: str The user input. @rtype: (str, bool) """ self._puzzle = self._puzzle.move(action) if self._current_tree.in_subtree(self._puzzle): self._current_tree = self._current_tree.in_subtree(self._puzzle) else: new_subtree = _ControllerTree(self._puzzle, action) self._current_tree.add_subtree(new_subtree) self._current_tree = new_subtree if self._puzzle.is_solved(): return 'Congratulations, you solved it!', True return self.state(), False
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _tree: StateTree # The State tree of the system. # @type _view: View # The view associated with this game controller def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._tree = StateTree((self._puzzle, '')) if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ if action == ':EXIT': return ('', True) elif action == ':SOLVE': return (solve(self._puzzle), True) elif action == ':SOLVE-ALL': return (solve_complete(self._puzzle), True) elif list(action)[0] == '(' and list(action)[-6:-1] == list(') -> '): newp = self._puzzle.move(action) self._tree.put_item((newp, action), self._puzzle) self._puzzle = newp return (newp, newp.is_solved()) elif [x for x in list(abc) if x in list(action)]: newp = self._puzzle.move(action) self._tree.put_item((newp, action), self._puzzle) self._puzzle = newp return (newp, newp.is_solved()) elif action == ':UNDO': parent = self._tree.find_par(self._puzzle) if parent != None: self._puzzle = parent.root[0] else: print("The previous state does not exist.") return (self._puzzle, self._puzzle.is_solved()) elif action == ':ATTEMPTS': lst = self._tree.node_list() for i in range(len(lst)): if i != 0: print(i.root[1]) print('----------------') print(i.root[0]) return (self.state(), False) elif list(action)[:5] == list(':HINT'): num = '' for i in range(len(list(action)) - 6): num += action[6 + i] x = hint_by_depth(self._puzzle, int(num)) if x == 'No possible extensions!' or x == 'Already at a solution!': print(x) return (self.state(), False) return (x, self._puzzle.is_solved()) else: return (self.state(), False)
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller # @type _tree: Tree # The state tree. def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type self: Controller @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Construct the state tree self._tree = Tree(puzzle) # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ # : Add to this method to handle different actions. if action == 'exit': return '', True elif action == ":SOLVE": solution = solve(self._puzzle) if solution is None: return "There is no solution for this Puzzle!", True else: return str(solution), True elif action == ":SOLVE-ALL": solutions = solve_complete(self._puzzle) if len(solutions) == 0: return "There are no solutions for this Puzzle!", True else: values = [str(solution) for solution in solutions] return "\n".join(values), True elif action == ":UNDO": value = self._tree.undo() if value is None: print("There is no previous state.") else: self._puzzle = value return str(self._puzzle), self._puzzle.is_solved() elif action == ":ATTEMPTS": self._tree.attempts() return str(self._puzzle), self._puzzle.is_solved() elif len(action) > 5 and action[0:6] == ":HINT ": n = action[6:] try: n = int(n) print(hint_by_depth(self._puzzle, n)) print() return str(self._puzzle), self._puzzle.is_solved() except: return "Invalid action, please try again.", False else: # Parse the action to the puzzle and make the move try: value = self._puzzle.move(action) self._puzzle = value # add the state into the tree self._tree.act(action, self._puzzle) # return str(value), value.is_solved() except: return "Invalid action, please try again.", False
class Controller: """Class responsible for connection between puzzles and views.""" # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller # @type _previous_moves: list[None|str] # A list containing all previous moves made def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._puzzle_tree = PuzzleTree(self._puzzle, None) self._previous_moves = [None] if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ if action == 'exit': return '', True elif action == ':SOLVE': return process_solve(self) elif action == ':SOLVE-ALL': return process_solve_all(self) elif action == ':UNDO': return process_undo(self) elif action == ":ATTEMPTS": return process_attempts(self) elif check_if_hint(action): return process_hint(self, action) else: return custom_move(self, action)
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Create the tree data structure to record moves self._movetree = MoveTree(puzzle) # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ # TODO: Add to this method to handle different actions. # if the action command is 'EXIT' if action == ':EXIT': # return empty string and the program should end return ('', True) # else if the action command is 'SOLVE' elif action == ':SOLVE': # solve the puzzle state = solve(self._puzzle) # if the state exists if state: # return the solution, and the program should end return (str(state), True) # otherwise return the error message, the program should end return ('Failed to solve from this point!', True) # else if the action command is 'SOLVE-ALL' elif action == ':SOLVE-ALL': # get the all possible solution states = solve_complete(self._puzzle) # if the states exist if states: # return the all solutions in the correct format, and the # program should end return ('\n'.join(map(str, states)), True) # otherwise return the error message, and program should end return ('Failed to solve from this point!', True) # else if the action command let the program give hint elif action.startswith(':HINT'): # split the action command to the list of parts parts = action.split(' ') # if the length of parts are 2 if len(parts) != 2: # return the error message for action, the program should # not end return ('Incorrect action format for hints!', False) # try the following firstly try: # get the index 1 of parts n = int(parts[1]) # else raise value error except ValueError: # return the error message for action, the program # should not end return ('Incorrect action format for hints!', False) # if the n is less than 1 if n < 1: # return the error message for action, the program should # not end return ('Incorrect action format for hints!', False) # otherwise get the hint by calling hint by depth function, # the program should not end return (hint_by_depth(self._puzzle, n), False) # if the action command is 'UNDO' elif action == ':UNDO': # return the string of the new current state and the current # state of puzzle result, self._puzzle = self._movetree.undo() # return the string of new current state and the program should # not end return (result, False) # else if the action command is 'ATTEMPTS' elif action == ':ATTEMPTS': # return the all resulting from the user made at the current state # and the program should not end return (self._movetree.attempts(), False) # if the action command is ':' elif action == ':': # return the current state of puzzle, and the program should # not end return (self.state(), False) # otherwise else: # try following try: # get the current state of puzzleafter given move state = self._puzzle.move(action) # else the value error except ValueError as e: # return the string of e, and the program should not end return (str(e), False) # update the puzzle after move self._puzzle = state # get the puzzle state by finding the node of move from tree self._movetree.do(state, action) # return the current puzzle state # and check whether it has been solved return (self.state(), state.is_solved())
def wsgi_app(environ, start_response): """ ========================================================== * Logic for determining web view content is located here * ========================================================== """ # Activate session storage session = environ['pesto.session'] # Retrieve GET variables and store them as a dictionary form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) # Initialize web classes CalSwimView = WebView(base_dir, environ['wsgi.errors']) CalSwimDB = WebDB(base_dir, environ['wsgi.errors']); #print >> CalSwimView.errors, "Print Error Message In Apache Logs" """ ================================================ * Main switch to determine controller/template * ================================================ """ if 'get_map_locs' in form: """ Return AJAX call results for Google Map Pins """ CalSwimView.set_search(form.getvalue('get_map_locs'),form.getvalue('radius'),form.getvalue('keywords')) CalSwimView.content = CalSwimDB.get_map_locs(CalSwimView) elif 'get_data_details' in form: """ Return AJAX call results for data details """ dataID = form.getvalue('get_data_details') if 'format' in form: format = form.getvalue('format') else: format = 'json' CalSwimView.content = CalSwimDB.get_data_details(dataID, format) if format == 'csv': # Return CVS content start_response('200 OK', [('content-type', 'application/CSV'),('Content-Disposition','attachment; filename=ecodata'+dataID+'.csv')]) return CalSwimView.content if format == 'json': start_response('200 OK', [('content-type', 'application/json')]) return CalSwimView.content elif 'login' in form: # Logout from admin area if 'false' == form.getvalue('login'): session['user'] = "" # Set user name in session to mark successful login if 'username' in form: passwd = form.getvalue('password') if passwd=='EcoAdminPass2012': session['user'] = '******' else: session['user'] = "******" user = session.get('user') # Get user if it exists, and verify if it is admin if 'admin' == user: if 'edit' in form: """ Handler for a single item edit """ gd_id = form.getvalue('edit') if 'organization' in form: CalSwimView.content = CalSwimDB.set_data_details(gd_id, form) else: CalSwimView.set_content('admin') items = CalSwimDB.get_data_details(gd_id, 'html') CalSwimView.content = CalSwimView.content % {'Items' : items} elif 'import_data' in form: """ Handle AJAX call for data import into DB """ CalSwimDB.import_data(form) CalSwimView.content = CalSwimDB.return_message elif 'delete' in form: """ Handler for deleting items """ # Delete items from a list of ids CalSwimDB.delete_items(form.getlist('deletes')) # Get all records items = CalSwimDB.get_items() # Place all records in html frontend CalSwimView.set_content('admin') CalSwimView.content = CalSwimView.content % {'Items' : items} # CalSwimView.content = str(form.getlist('deletes')) else: # Get all records items = CalSwimDB.get_items() # Place all records in html frontend CalSwimView.set_content('admin') CalSwimView.content = CalSwimView.content % {'Items' : items} else: CalSwimView.set_content('index') CalSwimView.content = CalSwimView.content % {'uploadResult' : "Incorrect name or password."} else: CalSwimView.set_content('index') CalSwimView.content = CalSwimView.content % {'uploadResult' : ""} # Return finalized content start_response('200 OK', [('content-type', 'text/html')]) return CalSwimView.content
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller # @type _data: StateTree # The tree that stores all the state data associated with the game # @type _index: [int, int] # The index that labels every state data that is stored in the data # @type _undo: bool # The indicator that shows if the previous command is :UNDO or not def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._data = StateTree(puzzle) # with index [0, 0] self._index = [0, 0] self._undo = False if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def undo(self, current): """ Return the parent node info(includes its puzzle state and index) of the current position in the tree. @type current: Puzzle @rtype: list A list contains previous puzzle state and previous index """ if self._data.get_prev(current)[1]: return self._data.get_prev(current)[0] else: raise ValueError def attempt(self, current): """ Return a list of input info (including the command they typed and the puzzle state from that command) the user has tried under current state. @type current: Puzzle @rtype: list[list[str, Puzzle]] """ results = [] if self._data.get_attempt(current)[1]: for subtree in self._data.get_attempt(current)[0]: temp = subtree.command + '\n' + '----------------' +\ '\n' + str(subtree.state) results.append(temp) else: raise ValueError return results def save_move(self, action, prev_state, prev_index): """ Save the latest puzzle state into self._data as well as its previous information. @type action: str @type prev_state: Puzzle @type prev_index: tuple @rtype: None """ if self._undo: test = StateTree(self._puzzle, tuple(self._index), prev_state, prev_index, action) self._index[0] += 1 # if have a different input, update x and y and save # if have an existing input, update y only if test not in self._data: self._index[1] += 1 new = StateTree(self._puzzle, tuple(self._index), prev_state, prev_index, action) self._data.save(new, prev_state) self._undo = False else: self._index[0] += 1 new = StateTree(self._puzzle, tuple(self._index), prev_state, prev_index, action) if new not in self._data: self._data.save(new, prev_state) def to_solve(self): """ To solve the puzzle. @rtype: tuple """ result = solve(self._puzzle) if result is None: message = 'The puzzle is unsolvable from the current state' return (message, True) else: return (str(result), True) def to_solve_all(self): """ To give all solutions of the puzzle. @rtype: tuple """ result_all = solve_complete(self._puzzle) if len(result_all) == 0: message = 'The puzzle is unsolvable from the current state' return (message, True) else: return ('\n'.join(map(str, result_all)), True) def to_undo(self): """ To undo the puzzle. @rtype: tuple """ if self._index[0] > 0: current = self._puzzle self._puzzle = self.undo(current)[0] self._index = list(self.undo(current)[1]) self._undo = True return (self.state(), False) else: message = 'Already in the initial state.' return (message, False) def to_attempt(self): """ To give all previous attempts of the current state. @rtype: tuple """ current = self._puzzle attempts = self.attempt(current) if len(attempts) == 0: print('You have not tried anything yet!') return ('\n'.join(map(str, attempts)), False) def to_hint(self, action): """ To give hint of the puzzle at current state. @type action: str @rtype: tuple """ typed = action.split() if len(typed) == 2: try: n = int(typed[1]) except ValueError: message = 'Please type the number of moves!' return (message, False) if n < 1: message = 'Please type a positive number!' return (message, False) else: hint = hint_by_depth(self._puzzle, n) return (hint, False) else: message = 'Please type the number of moves!' return (message, False) def to_react(self, action): """ To change the puzzle state according to the user's command. @type action: str @rtype: tuple """ if len(action) == 0: if self._puzzle.is_solved(): return (self.state(), True) else: print('Invalid move. Please try again!\n') return (self.state(), False) else: if self._puzzle.is_valid(action): prev_state = self._puzzle prev_index = tuple(self._index) # move self._puzzle = self._puzzle.move(action) # save move self.save_move(action, prev_state, prev_index) # print the current state if self._puzzle.is_solved(): return (self.state(), True) else: return (self.state(), False) else: message = 'Invalid move. Please try again!\n' return (message, False) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ if action == 'exit': return ('', True) elif action == ':SOLVE': return self.to_solve() elif action == ':SOLVE-ALL': return self.to_solve_all() elif action == ':UNDO': return self.to_undo() elif action == ':ATTEMPTS': return self.to_attempt() elif action.startswith(':HINT'): return self.to_hint(action) else: return self.to_react(action)
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller # @type _state_tree: Tree # A Tree representation of the current puzzle state and the move to get # to it, with ancestors and descendants serving as references to # previous and attempted states. def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() self._state_tree = Tree(self._puzzle) # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ if action == 'exit': return '', True elif action == ':SOLVE': return solve(self._puzzle).__str__(), True elif action == ':SOLVE-ALL': return "\n".join(map(str, solve_complete(self._puzzle))), True # The remaining conditions use helpers for more complicated code. elif action == ':UNDO': return self._undo(), False elif action == ':ATTEMPTS': return self._state_tree.attempts(), False elif action[:6] == ":HINT ": return self._hint(action), False elif isinstance(action, str): # The action is some sort of move that depends on the puzzle. # rtype of _player_move is (str, bool), since a move could cause the # game to end. return self._player_move(action) # Nothing happens if input is somehow incorrect. else: return self.state(), False # ------------------------------------------------------------------------ # Helpers for method 'act' # ------------------------------------------------------------------------ def _undo(self): """Returns a string representation of the puzzle state that the player had before the current state. Returns "You can no longer undo" if the player has reached the initial puzzle state. @type self: Controller @rtype: str """ # Find the previous puzzle state as a Tree previous_puzzle_tree = self._state_tree.undo() if previous_puzzle_tree is None: return "You can no longer undo" else: # Sets current puzzle state to the previous state self._puzzle = previous_puzzle_tree._state self._state_tree = previous_puzzle_tree return self._puzzle.__str__() def _hint(self, action): """Returns a hint based on the players action Precondition: action must be in the following format: ':HINT n' where n is an integer. @type self: Controller @type action: str @rtype: str """ try: number = action[6:] number = int(number) except ValueError: return "That is not a proper value. Try again." return hint_by_depth(self._puzzle, number) def _player_move(self, action): """Changes current puzzle state to one according to <action>. Returns a string representation of the game, as well as whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ try: state = self._puzzle.move(action) except ValueError: return "This is not a valid input.", False self._state_tree = self._state_tree.add_state(state, action) self._puzzle = state if self._puzzle.is_solved(): return self._puzzle.__str__() + "\nCongratulations! You've " \ "solved the Puzzle!", True else: return self._puzzle.__str__(), False
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller # @type _tree: Tree # The tree associated with this game controller # @type _previous: lst[Tree] # A list of Tree associated with this game controller build for "UNDO" # @type _children_list: lst[Tree] # A list of Tree associated with this game controller build for "ATTEMPTS" def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use. By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle self._tree = Tree(puzzle) # build for UNDO self._previous = [Tree(puzzle)] # build for ATTEMPTS self._children_list = [] if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() print(self._display_config()) # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ if action == "SOLVE": if not solve(self._puzzle): return '* ERROR: no solution avaliable! *', True else: return solve(self._puzzle), True if action == "SOLVE-ALL": if solve_complete(self._puzzle) == []: return '* ERROR: no solution avaliable! *', True else: for item in solve_complete(self._puzzle): print(item) return '', True if action == 'exit': return '', True if self._check_hint(action): n = int(action[4:].strip()) return " ", False if action == "UNDO": if len(self._previous) == 1: print("======= ERROR =======\n no previous states") return " ", False else: parent_state = self._tree.parent.root self._puzzle = parent_state self._previous.remove(self._previous[-1]) self._tree = self._previous[-1] return parent_state, False if action == "ATTEMPTS": if self._tree.parent is None: print("======= ERROR =========\n no previous attempts") return '', False else: for item in self._children_list: if item.parent.root == self._tree.parent.root: s = " attempted move: {}\n".format(item.move) print(s) print(item.root) return '', False elif self._check(action): cur_state = self._puzzle.move(action) self._puzzle = cur_state children = Tree(cur_state, action, self._tree) if children not in self._tree.subtrees: self._tree.add_subtrees([children]) self._children_list.append(children) self._tree = children self._previous.append(self._tree) return cur_state, False elif action == 'exit': return '', True else: return self.state(), False def _check(self, move): """"Return True if a move is valid or display an error message otherwise @type self: Controller @type move: str @rtype: bool """ if not self._puzzle.is_valid(move): print( '======= ERROR =======\n* Invalid input, please try again *\n') return False else: return True def _check_hint(self, action): """Return whether an action is asking for hint @type self: Controller @type action: str @rtype: bool """ if "HINT" == action[:4]: if action[4:].strip() < 0: print( '=========== Error ===========\n please enter a valid positive number' ) else: return True return False def _display_config(self): """Return a string representation of starting configuration @type self: Controller @rtype: str """ a = '=' * 90 + '\n' + sudoku_config + '\n' + '=' * 90 b = '=' * 90 + '\n' + word_ladder_config + '\n' + '=' * 90 return a + '\n' + b
def wsgi_app(environ, start_response): """ ========================================================== * Logic for determining web view content is located here * ========================================================== """ # Activate session storage session = environ['pesto.session'] # Retrieve GET variables and store them as a dictionary form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) # Initialize web classes CalSwimView = WebView(base_dir, environ['wsgi.errors']) CalSwimDB = WebDB(base_dir, environ['wsgi.errors'], environ.get('HTTP_HOST')); #print >> CalSwimView.errors, "Print Error Message In Apache Logs" """ ================================================ * Main switch to determine controller/template * ================================================ """ if 'get_map_locs' in form: """ Return AJAX call results for Google Map Pins """ CalSwimView.set_search(form.getvalue('get_map_locs'),form.getvalue('radius'),form.getvalue('keywords')) CalSwimView.content = CalSwimDB.get_map_locs(CalSwimView) elif 'get_data_details' in form: """ Return AJAX call results for data details """ dataID = form.getvalue('get_data_details') if 'format' in form: format = form.getvalue('format') else: format = 'json' CalSwimView.content = CalSwimDB.get_data_details(dataID, format) if format == 'csv': # Return CVS content start_response('200 OK', [('content-type', 'application/CSV'),('Content-Disposition','attachment; filename=ecodata'+dataID+'.csv')]) return CalSwimView.content if format == 'json': start_response('200 OK', [('content-type', 'application/json')]) return CalSwimView.content elif 'login' in form: # Logout from admin area if 'false' == form.getvalue('login'): session['user'] = "" session['g_id'] = "" session['u_id'] = "" # Set user name in session to mark successful login if 'username' in form: username = form.getvalue('username') passwd = md5(form.getvalue('password')).hexdigest() valid_user = CalSwimDB.validate_user(username,passwd) if valid_user: session['user'] = username session['u_id'] = CalSwimDB.user['u_id'] session['g_id'] = ', '.join(map(str, CalSwimDB.user['g_id'])) else: session['user'] = "" user = session.get('user') u_id = session.get('u_id') g_id = session.get('g_id') # If user has account allow access to upload area if user and u_id: if 'get_items' in form: # Get all records and return json list #items = CalSwimDB.get_items() CalSwimView.content = CalSwimDB.get_items('json',g_id) elif form.getvalue('import_data') == "update_data": """ Handler for a single item edit """ gd_id = form.getvalue('edit') CalSwimView.content = CalSwimDB.set_data_details(gd_id, form, g_id) elif form.getvalue('import_data') == "import_data": """ Handle AJAX call for data import into DB """ CalSwimDB.import_data(form,g_id) CalSwimView.content = CalSwimDB.return_message elif 'delete' in form: """ Handler for deleting items """ # Delete items from a list of ids CalSwimDB.delete_items(form.getlist('deletes'),g_id) # Set template type CalSwimView.set_content('admin') # Set content CalSwimView.content = CalSwimView.content else: # Set template type CalSwimView.set_content('admin') # Set content CalSwimView.content = CalSwimView.content else: CalSwimView.set_content('index') CalSwimView.content = CalSwimView.content % {'uploadResult' : "Incorrect name or password."} else: CalSwimView.set_content('index') CalSwimView.content = CalSwimView.content % {'uploadResult' : ""} # Return finalized content start_response('200 OK', [('content-type', 'text/html')]) return CalSwimView.content
class Controller: """Class responsible for connection between puzzles and views. You may add new *private* attributes to this class to help you in your implementation. """ # === Private Attributes === # @type _puzzle: Puzzle # The puzzle associated with this game controller # @type _view: View # The view associated with this game controller def __init__(self, puzzle, mode='text'): """Create a new controller. <mode> is either 'text' or 'web', representing the type of view to use.ss By default, <mode> has a value of 'text'. @type puzzle: Puzzle @type mode: str @rtype: None """ self._puzzle = puzzle if mode == 'text': self._view = TextView(self) elif mode == 'web': self._view = WebView(self) else: raise ValueError() # Start the game. self._view.run() def state(self): """Return a string representation of the current puzzle state. @type self: Controller @rtype: str """ return str(self._puzzle) def act(self, action): """Run an action represented by string <action>. Return a string representing either the new state or an error message, and whether the program should end. @type self: Controller @type action: str @rtype: (str, bool) """ # TODO: Add to this method to handle different actions. if action == 'exit': return '', True elif action == "solve": return str(solve(self._puzzle)),True elif action == "solve-all": solution = solve_complete(self._puzzle) solution = list(map(lambda x: str(x), solution)) return "\n".join(solution),True elif "hint" in action: if action[5].isdigit() and int(action[5]) >= 1: return str(hint_by_depth(self._puzzle,int(action[5]))),False else: return "Please enter input again!" elif self._puzzle.check(action) == ValueError: return "Incorrect input", False elif self._puzzle.check(action): return self._puzzle.move(action), True else: return self.state(), False def tree(self, puzzle, move): pass