From ec537a3a1f9ca54c0a40c0ac9864b8e348bbba4d Mon Sep 17 00:00:00 2001 From: Sebastian Morr Date: Mon, 28 Sep 2020 16:18:06 +0200 Subject: [PATCH] Persistent command history --- game.gd | 30 ++++++++++++++++++++++++++++++ terminal.gd | 18 ++++++++++-------- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/game.gd b/game.gd index ea921fa..bce77d2 100644 --- a/game.gd +++ b/game.gd @@ -5,10 +5,40 @@ var global_shell var debug_file_io = false var fake_editor +var _file = "user://savegame.json" +var state = {} + func _ready(): global_shell = Shell.new() fake_editor = copy_file_to_game_env("fake-editor") copy_file_to_game_env("fake-editor-noblock") + load_state() + +func _initial_state(): + return {"history": []} + +func save_state() -> bool: + var savegame = File.new() + + savegame.open(_file, File.WRITE) + savegame.store_line(to_json(state)) + savegame.close() + return true + +func load_state() -> bool: + var savegame = File.new() + if not savegame.file_exists(_file): + save_state() + + savegame.open(_file, File.READ) + + state = _initial_state() + var new_state = parse_json(savegame.get_line()) + for key in new_state: + state[key] = new_state[key] + savegame.close() + return true + func copy_file_to_game_env(filename): diff --git a/terminal.gd b/terminal.gd index 67f3514..0af05cb 100644 --- a/terminal.gd +++ b/terminal.gd @@ -2,7 +2,6 @@ extends Control var thread -var history = [] var history_position = 0 var git_commands = [] @@ -39,20 +38,22 @@ func _ready(): git_commands.pop_back() completions.hide() + history_position = game.state["history"].size() func _input(event): - if history.size() > 0: + #print(game.state) + if game.state["history"].size() > 0: if event.is_action_pressed("ui_up"): if history_position > 0: history_position -= 1 - input.text = history[history_position] + input.text = game.state["history"][history_position] input.caret_position = input.text.length() # This prevents the Input taking the arrow as a "skip to beginning" command. get_tree().set_input_as_handled() if event.is_action_pressed("ui_down"): - if history_position < history.size()-1: + if history_position < game.state["history"].size()-1: history_position += 1 - input.text = history[history_position] + input.text = game.state["history"][history_position] input.caret_position = input.text.length() get_tree().set_input_as_handled() @@ -61,8 +62,9 @@ func load_command(id): input.caret_position = input.text.length() func send_command(command): - history.push_back(command) - history_position = history.size() + game.state["history"].push_back(command) + game.save_state() + history_position = game.state["history"].size() input.editable = false completions.hide() @@ -123,7 +125,7 @@ func regenerate_completions_menu(new_text): func relevant_subcommands(): var result = {} - for h in history: + for h in game.state["history"]: var parts = Array(h.split(" ")) if parts[0] == "git": var subcommand = parts[1]