def test_restore(self): model = Model("data") memento = model.save() caretaker = Caretaker() caretaker.add(memento) model.data = "data2" memento2 = caretaker.get(0) model.restore(memento2) self.assertEqual(model.data, memento2.data)
def __init__(self, height=8, width=10, bombs=10): """ :param height: Height of grid :param width: Width of grid :param bombs: Amount of bombs in grid """ self.difficulty = Difficulty.EASY self.height = height self.width = width self.bombs = bombs self.bombs_left = bombs self.set_parameters(self.difficulty, self.height, self.width, self.bombs) self.grid = Grid(self.width, self.height, self.bombs) self.squares_revealed = 0 self.init_time = time.time() self.originator = Originator() self.caretaker = Caretaker(self.originator) self.state = dict() self.memento_instances = 0 self.undos_remaining = DEFAULT_UNDO_TRIES
def test_simple_restore(self): caretaker = Caretaker() editor = TextEditor("content!") self.assertEqual("content!", editor.get_content()) caretaker.push(editor.save()) editor.add_new_content("more content!") self.assertEqual("content!\nmore content!", editor.get_content()) caretaker.push(editor.save()) editor.add_new_content("more contenttttttt!") self.assertEqual("content!\nmore content!\nmore contenttttttt!", editor.get_content()) editor.restore(caretaker.pop()) self.assertEqual("content!\nmore content!", editor.get_content()) editor.restore(caretaker.pop()) self.assertEqual("content!", editor.get_content())
"""Общая функция.""" caretaker.backup() Hero.backpack.add_to_backpack({"Тотем": 1}) class RestoreSnapshot(Strategy): """Конкретная стратгия восстановления сохранённого состояния из тотема.""" def do_algorithm(self, monster_power) -> int: """Общая функция.""" caretaker.undo() Hero.backpack.update_backpack('Тотем', 1) print(Hero.print_specification()) # ------------------------------------------Конец стратегии ------------------------------------# caretaker = Caretaker(originator=Hero) def generate_random_events() -> None: """Инициализация случайных событий и то, что происходит с каждым событием.""" while Hero._killed_enemies <= 10 and Hero.is_alive(): options = ['Магический предмет', 'Монстр'] event = random.choice(options) if event == 'Магический предмет': tool = generate_magic_tool() if 'Яблочко' in tool: apple_power = tool['Яблочко'] event_apple(apple_power) continue b = input(f"\nТы видишь {tool}\n 1 - Взять, 2 - Пройти мимо\n") if valid_input(b):
class Model: def __init__(self, height=8, width=10, bombs=10): """ :param height: Height of grid :param width: Width of grid :param bombs: Amount of bombs in grid """ self.difficulty = Difficulty.EASY self.height = height self.width = width self.bombs = bombs self.bombs_left = bombs self.set_parameters(self.difficulty, self.height, self.width, self.bombs) self.grid = Grid(self.width, self.height, self.bombs) self.squares_revealed = 0 self.init_time = time.time() self.originator = Originator() self.caretaker = Caretaker(self.originator) self.state = dict() self.memento_instances = 0 self.undos_remaining = DEFAULT_UNDO_TRIES def save_state(self): """ Save current state as memento """ self.state = {'squares_revealed': self.squares_revealed, 'grid_state': self.grid.get_state(), 'bombs_left': self.bombs_left} self.originator.set(self.state) self.caretaker.backup() self.memento_instances += 1 def undo_state(self) -> bool: """ Undo state to previous one :return: True/False whether undo was successful """ if self.undos_remaining == 0: return False try: self.state = self.caretaker.undo() except IndexError: print('No memento to undo') return False self.squares_revealed = self.state['squares_revealed'] self.bombs_left = self.state['bombs_left'] self.grid.set_state(self.state['grid_state']) self.memento_instances -= 1 self.undos_remaining -= 1 return True def set_parameters(self, difficulty: Difficulty, *argv): """ set parameters height, width, bombs :param difficulty: Enum of Difficulty :param argv: height, width, bombs to set values at :return: True/False whether parameters were set successfully """ if len(argv) != 3 and len(argv) != 0: print("Warning : Invalid parameters") print("Need 4 arguments (difficulty, height, width, bombs) or 1 argument (difficulty)") return False if len(argv) == 0: # Only difficulty given if difficulty == Difficulty.EASY: self.difficulty = Difficulty.EASY return self.set_parameters(Difficulty.EASY, 8, 10, 10) elif difficulty == Difficulty.MEDIUM: self.difficulty = Difficulty.MEDIUM return self.set_parameters(Difficulty.MEDIUM, 14, 18, 40) elif difficulty == Difficulty.HARD: self.difficulty = Difficulty.HARD return self.set_parameters(Difficulty.HARD, 20, 24, 99) else: return False # if they aren't ints try: height = int(argv[0]) width = int(argv[1]) bombs = int(argv[2]) except ValueError: print("Warning : Invalid parameters") print("Arguments aren't ints") return False # if constraints aren't respected if height <= 0 or width <= 0 or bombs <= 0 or bombs >= height * width: print("Warning : Invalid parameters") print("Can't create game with these values") return False self.height = height self.width = width self.bombs = bombs self.bombs_left = bombs self.difficulty = difficulty return True def new_game(self): """ Resets model values and start a new game """ self.caretaker.clear() self.memento_instances = 0 self.grid.reset() self.grid.add_bombs() self.set_squares_revealed(0) self.set_bombs_left(self.bombs) self.undos_remaining = DEFAULT_UNDO_TRIES self.set_init_time(time.time()) def get_grid(self): return self.grid def get_squares_revealed(self): return self.squares_revealed def get_width(self): return self.grid.width def get_height(self): return self.grid.height def get_bombs(self): return self.bombs def get_bombs_left(self): return self.bombs_left def get_init_time(self): return self.init_time def set_squares_revealed(self, num_squares_revealed): self.squares_revealed = num_squares_revealed def set_bombs_left(self, num_bombs_left): if num_bombs_left < 0: return False self.bombs_left = num_bombs_left return True def set_bombs(self, num_bombs): self.bombs = num_bombs def set_height(self, height_num): self.height = height_num def set_width(self, width_num): self.width = width_num def set_init_time(self, set_time): self.init_time = set_time def update_grid(self): self.grid = Grid(self.width, self.height, self.bombs) def is_square_revealed(self, i, j): return self.grid.board[i][j].is_revealed
def memento(ls1: Orders, originator: Creator, caretaker: Caretaker): originator.change(ls1) caretaker.filling_stack() ls = originator.get_condition_o() return ls
ls1.add_to_list(i) return ls1 def memento(ls1: Orders, originator: Creator, caretaker: Caretaker): originator.change(ls1) caretaker.filling_stack() ls = originator.get_condition_o() return ls ls = Orders() file_name = validate_file_input() ls.fill_list_from_file(file_name) originator = Creator(ls) caretaker = Caretaker(originator) caretaker.filling_stack() while True: userchoice = input('''welcome user choose your choice: 1.) Search orders with value 2.) Delete orders 3.) Add order 4.) Print all orders 5.) Undo 6.) Redo 7.)Exit''' + '\n') if userchoice == '1': val = input('Input value for order: ') ls.search_in_list(val) elif userchoice == '2':