Skip to content

Instantly share code, notes, and snippets.

@brettchalupa
Last active November 23, 2023 12:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettchalupa/717d96ab01ba59beafdeb8ac5c153405 to your computer and use it in GitHub Desktop.
Save brettchalupa/717d96ab01ba59beafdeb8ac5c153405 to your computer and use it in GitHub Desktop.
Godot Saving and Loading Data from Disk
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