Last active
November 23, 2023 12:23
-
-
Save brettchalupa/717d96ab01ba59beafdeb8ac5c153405 to your computer and use it in GitHub Desktop.
Godot Saving and Loading Data from Disk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node2D | |
var times_pressed := 0 | |
var high_score := 0 | |
var playing := false | |
@onready var timer:Timer = $Gameplay/Timer | |
func _ready() -> void: | |
load_high_score() | |
func _process(delta: float) -> void: | |
if playing: | |
$Gameplay/TimerCountdown.text = "Time Left: %s" % roundf(timer.time_left) | |
func _on_start_button_pressed() -> void: | |
playing = true | |
times_pressed = 0 | |
set_pressed_text() | |
$StartButton.hide() | |
$Gameplay.show() | |
$Gameplay/Timer.start() | |
func _on_gameplay_timer_timeout() -> void: | |
$StartButton.show() | |
$Gameplay.hide() | |
if high_score < times_pressed: | |
set_new_high_score() | |
const HIGH_SCORE_FILE = "user://high-score.txt" | |
func set_new_high_score(): | |
high_score = times_pressed | |
set_high_score_text() | |
var file = FileAccess.open(HIGH_SCORE_FILE, FileAccess.WRITE) | |
file.store_string("%s" % high_score) | |
func load_high_score() -> void: | |
if FileAccess.file_exists(HIGH_SCORE_FILE): | |
var file = FileAccess.open(HIGH_SCORE_FILE, FileAccess.READ) | |
high_score = file.get_as_text(true).to_int() | |
set_high_score_text() | |
func _on_gameplay_button_pressed() -> void: | |
times_pressed += 1 | |
set_pressed_text() | |
func set_pressed_text(): | |
$PressedLabel.text = "Times Pressed: %s" % times_pressed | |
func set_high_score_text(): | |
$HighScoreLabel.text = "High-Score: %s" % high_score |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment