Save the quiz and continue it after a restart; load characters from a folder
Build / test (push) Successful in 1m25s
Build / build (push) Successful in 1m12s

The quiz is saved to current_quiz.json in the config folder after every
change, and the game goes on where it was when it starts again: the
players with their points and characters, every song with who got a point
for it and whether it was played, answered or is playing, and the songs
downloaded ahead with their files. The song that was playing is ready to
play again. Songs whose files are gone are downloaded again.

On a server, the saved songs are checked against the server's playlist. If
it changed, e.g. after a sync, or another server is used, the quiz starts
over with the same players. A quiz from a music folder continues offline,
including how far a prepared quiz has come. A new game is saved like any
other change, and a file that can't be read starts a new quiz.

Characters can be read from a folder picked in Settings instead of the
server, for this session. A music folder with a characters folder brings
its own characters, e.g. for a themed quiz; that folder is not counted as
a soundtrack. When the characters come from somewhere else, players pick
their characters again.

Closes #11, closes #44
This commit is contained in:
Sansan committed 2026-10-09 18:08:50 +02:00
1 parent 4a934840f6
commit e4352a9f34
33 files changed
+2886 -499

No files matched your search

+44 -2
View File
@@ -8,19 +8,25 @@ extends RefCounted
## order or at random, and only the song's name is the answer.
##
## Hidden files and folders, and files the game can't play (see [AudioFile]), are left
## out.
## out. A subfolder called [code]characters[/code] holds the quiz's own characters
## instead of songs, see [member characters_path].
enum Kind { EMPTY, SOUNDTRACKS, PREPARED_QUIZ }
enum PlayOrder { IN_ORDER, RANDOM }
## How many files are tried before giving up when files can't be read.
const MAX_TRIES: int = 20
## The subfolder with the quiz's own characters. Any case, e.g. "Characters", works.
const CHARACTERS_FOLDER: String = "characters"
## The folder's path.
var path: String = ""
var kind: Kind = Kind.EMPTY
## How a prepared quiz is played. Change it with [method set_play_order].
var play_order: PlayOrder = PlayOrder.IN_ORDER
## The folder's [constant CHARACTERS_FOLDER] subfolder when it has pictures, so a themed
## quiz can bring its own characters. Empty when there is none.
var characters_path: String = ""
# Soundtrack folder: soundtrack name -> paths of its songs
var _soundtracks: Dictionary[String, PackedStringArray] = {}
@@ -35,7 +41,14 @@ var _quiz_next: int = 0
static func scan(folder_path: String) -> MusicFolder:
var folder: MusicFolder = MusicFolder.new()
folder.path = folder_path.trim_suffix("/")
var subfolders: PackedStringArray = _visible(DirAccess.get_directories_at(folder.path))
var subfolders: PackedStringArray = []
for subfolder: String in _visible(DirAccess.get_directories_at(folder.path)):
if subfolder.to_lower() == CHARACTERS_FOLDER:
var characters: String = folder.path.path_join(subfolder)
if !FolderCharacters.picture_names(characters).is_empty():
folder.characters_path = characters
else:
subfolders.append(subfolder)
if !subfolders.is_empty():
for subfolder: String in subfolders:
var songs: PackedStringArray = _songs_in(folder.path.path_join(subfolder), true)
@@ -86,6 +99,35 @@ func restart() -> void:
_quiz_next = 0
## How far a prepared quiz has come, to continue it after a restart with
## [method restore_progress].
func progress() -> Dictionary:
return {"play_order": play_order, "queue": Array(_quiz_queue), "next": _quiz_next}
## Continues a prepared quiz from [param saved], as given by [method progress]. Songs
## that are no longer in the folder are left out. Returns false, changing nothing, when
## [param saved] does not fit this folder.
func restore_progress(saved: Dictionary) -> bool:
if kind != Kind.PREPARED_QUIZ || !(saved.get("queue") is Array) \
|| !(saved.get("next") is float || saved.get("next") is int):
return false
var queue: PackedStringArray = []
var next: int = int(saved.next)
var known: Dictionary = {}
for song_path: String in _quiz_songs:
known[song_path] = true
for i: int in saved.queue.size():
if known.has(str(saved.queue[i])):
queue.append(str(saved.queue[i]))
elif i < int(saved.next):
next -= 1
play_order = int(saved.get("play_order", play_order)) as PlayOrder
_quiz_queue = queue
_quiz_next = clampi(next, 0, queue.size())
return true
## The next song to play, or null when a prepared quiz has played every song or no file
## can be read.
func next_song() -> SongObject:
+36
View File
@@ -21,6 +21,9 @@ var id: String = _generate_uuid()
var is_first_point: bool = true
var character: Texture = load(NO_CHARACTER_PATH)
## The name of the picked character, its picture's file name, or empty when none is
## picked. Saved with the quiz, so the picture can be found again after a restart.
var character_name: String = ""
func _init(new_name: String) -> void:
@@ -28,6 +31,39 @@ func _init(new_name: String) -> void:
player_score = 0
## Shows [param texture], the character called [param new_name], for the player.
func set_character(texture: Texture, new_name: String) -> void:
character = texture
character_name = new_name
## Goes back to no character, e.g. when the characters come from somewhere else.
func clear_character() -> void:
character = load(NO_CHARACTER_PATH)
character_name = ""
## The player as a Dictionary that can be written as JSON, for [QuizSave].
func to_dict() -> Dictionary:
return {
"id": id, "name": player_name, "score": player_score,
"is_first_point": is_first_point, "character": character_name,
}
## A player made from [param data], as given by [method to_dict], or null when
## [param data] is not a player. The character's picture is not loaded here.
static func from_dict(data: Variant) -> PlayerObject:
if !(data is Dictionary) || !(data.get("name") is String) || !(data.get("id") is String):
return null
var player: PlayerObject = PlayerObject.new(data.name)
player.id = data.id
player.player_score = maxi(int(data.get("score", 0)), 0)
player.is_first_point = bool(data.get("is_first_point", player.player_score == 0))
player.character_name = str(data.get("character", ""))
return player
## Returns a random version 4 UUID, e.g. "3f2b8c1e-9a4d-4e7f-b2c6-5d8e1f0a7b93".
static func _generate_uuid() -> String:
var bytes: PackedByteArray = Crypto.new().generate_random_bytes(16)
+12 -9
View File
@@ -5,8 +5,9 @@ extends Node
## Registered as the [code]Playlist[/code] autoload.
##
## Downloaded songs are kept on disk in the [code]songs[/code] folder next to the
## settings, not in memory. The folder only holds the current playlist: it is emptied when
## the game starts and when the playlist is reset.
## settings, not in memory. The folder only holds the current playlist: when the game
## starts, songs the saved quiz does not use are deleted (see [QuizSave]), and the folder
## is emptied when the playlist is reset.
const SONGS_FOLDER_NAME: String = "songs"
@@ -25,10 +26,6 @@ var game_start_song: int = 0
var _song_files_written: int = 0
func _ready() -> void:
clear_song_files()
## The folder downloaded songs are kept in.
static func songs_folder() -> String:
return Settings.config_dir().path_join(SONGS_FOLDER_NAME)
@@ -152,7 +149,11 @@ func add_song_to_song_object(song_no: int, mp3: PackedByteArray) -> void:
## written, the song is kept in memory instead.
func store_song(song_object: SongObject, mp3: PackedByteArray) -> void:
DirAccess.make_dir_recursive_absolute(songs_folder())
# Songs kept from a saved quiz already have files, which must not be written over
var path: String = songs_folder().path_join("song_%d.mp3" % _song_files_written)
while FileAccess.file_exists(path):
_song_files_written += 1
path = songs_folder().path_join("song_%d.mp3" % _song_files_written)
_song_files_written += 1
var file: FileAccess = FileAccess.open(path, FileAccess.WRITE)
if file == null:
@@ -169,12 +170,14 @@ func store_song(song_object: SongObject, mp3: PackedByteArray) -> void:
song_object.song_path = path
## Deletes the files of the songs downloaded so far.
func clear_song_files() -> void:
## Deletes the files of the songs downloaded so far, except those in [param keep].
func clear_song_files(keep: PackedStringArray = []) -> void:
if !DirAccess.dir_exists_absolute(songs_folder()):
return
for file_name: String in DirAccess.get_files_at(songs_folder()):
DirAccess.remove_absolute(songs_folder().path_join(file_name))
var path: String = songs_folder().path_join(file_name)
if !keep.has(path):
DirAccess.remove_absolute(path)
func song_has_played(song_no: int = latest_played_song) -> void:
+174
View File
@@ -0,0 +1,174 @@
class_name QuizSave
extends RefCounted
## The quiz going on, saved to a file after every change, so the game goes on where it
## was when it is started again: the players with their points and characters, and every
## song with who got a point for it and whether it was played, answered or is playing.
##
## Songs downloaded ahead keep their files, so they are not downloaded again. A new game
## (Reset points, a sync or another server) is saved like any other change, so the file
## always holds the quiz as it is now.
##
## Kept in [code]current_quiz.json[/code] next to the settings, or
## [code]current_quiz_debug.json[/code] in debug mode, like the saved settings.
const FILE_NAME: String = "current_quiz.json"
const DEBUG_FILE_NAME: String = "current_quiz_debug.json"
## Files with another version are from a game that saved differently, and are ignored.
const VERSION: int = 1
var players: Array[PlayerObject] = []
var songs: Array[SongObject] = []
var currently_playing_song: int = -1
var latest_played_song: int = 0
var game_start_song: int = 0
var first_song_played: bool = false
## Whether statistics were turned off because a player won, see [code]Quiz[/code].
var stats_paused_by_win: bool = false
## The server the songs came from. Empty when they came from a music folder.
var server: String = ""
## The music folder the songs came from, or empty when they came from the server.
var music_folder_path: String = ""
## How far a prepared quiz in [member music_folder_path] has come, see
## [method MusicFolder.progress].
var music_folder_progress: Dictionary = {}
## Where the characters came from, see [method Settings.characters_dir].
var characters_dir: String = ""
## Where the quiz is saved.
static func path() -> String:
return Settings.config_dir().path_join(DEBUG_FILE_NAME if Settings.is_debug else FILE_NAME)
## The quiz as it is now, in [code]Settings[/code] and [code]Playlist[/code].
static func capture(paused_by_win: bool) -> QuizSave:
var save: QuizSave = QuizSave.new()
save.players = Settings.player_array.duplicate()
save.songs = Playlist.song_object_array.duplicate()
save.currently_playing_song = Playlist.currently_playing_song
save.latest_played_song = Playlist.latest_played_song
save.game_start_song = Playlist.game_start_song
save.first_song_played = Playlist.first_song_played
save.stats_paused_by_win = paused_by_win
if Settings.is_offline():
save.music_folder_path = Settings.music_folder.path
save.music_folder_progress = Settings.music_folder.progress()
else:
save.server = Settings.default_path
save.characters_dir = Settings.characters_dir()
return save
## Reads the saved quiz, or returns null when there is none or it can't be read.
static func read() -> QuizSave:
if !FileAccess.file_exists(path()):
return null
var save: QuizSave = from_dict(JSON.parse_string(FileAccess.get_file_as_string(path())))
if save == null:
GameLog.warning("Could not read the saved quiz in ", path(), ", starting a new one")
return save
## Deletes the saved quiz.
static func delete() -> void:
if FileAccess.file_exists(path()):
DirAccess.remove_absolute(path())
## Saves the quiz. It is written to another file first and then moved, so a crash while
## saving never leaves half a file. Returns false when it could not be saved.
func write() -> bool:
var target: String = path()
var temporary: String = target + ".tmp"
DirAccess.make_dir_recursive_absolute(target.get_base_dir())
var file: FileAccess = FileAccess.open(temporary, FileAccess.WRITE)
if file == null:
GameLog.warning("Could not save the quiz to ", temporary, ": ",
error_string(FileAccess.get_open_error()))
return false
file.store_string(JSON.stringify(to_dict(), "\t"))
file.close()
var error: Error = DirAccess.rename_absolute(temporary, target)
if error != OK:
GameLog.warning("Could not save the quiz to ", target, ": ", error_string(error))
return false
return true
## The song files the saved songs use, which must not be deleted.
func song_files() -> PackedStringArray:
var files: PackedStringArray = []
for song_object: SongObject in songs:
if !song_object.song_path.is_empty():
files.append(song_object.song_path)
return files
func to_dict() -> Dictionary:
var player_list: Array[Dictionary] = []
for player: PlayerObject in players:
player_list.append(player.to_dict())
var song_list: Array[Dictionary] = []
for song_object: SongObject in songs:
song_list.append(song_object.to_dict())
return {
"version": VERSION,
"players": player_list,
"songs": song_list,
"currently_playing_song": currently_playing_song,
"latest_played_song": latest_played_song,
"game_start_song": game_start_song,
"first_song_played": first_song_played,
"stats_paused_by_win": stats_paused_by_win,
"server": server,
"music_folder": {"path": music_folder_path, "progress": music_folder_progress},
"characters_dir": characters_dir,
}
## A save made from [param data], as given by [method to_dict], or null when
## [param data] is not a saved quiz of this [constant VERSION]. Players and songs that
## can't be read are left out.
static func from_dict(data: Variant) -> QuizSave:
if !(data is Dictionary) || int(data.get("version", 0)) != VERSION \
|| !(data.get("players") is Array) || !(data.get("songs") is Array):
return null
var save: QuizSave = QuizSave.new()
for player_data: Variant in data.players:
var player: PlayerObject = PlayerObject.from_dict(player_data)
if player != null && save.players.size() < Settings.MAX_NUMBER_OF_PLAYERS:
save.players.append(player)
for song_data: Variant in data.songs:
var song_object: SongObject = SongObject.from_dict(song_data)
if song_object == null:
# The songs' places in the list are their numbers, so none can be left out
save.songs.clear()
break
save.songs.append(song_object)
save.currently_playing_song = clampi(int(data.get("currently_playing_song", -1)), -1,
save.songs.size() - 1)
save.latest_played_song = clampi(int(data.get("latest_played_song", 0)), 0,
maxi(save.songs.size() - 1, 0))
save.game_start_song = clampi(int(data.get("game_start_song", 0)), 0, save.songs.size())
save.first_song_played = bool(data.get("first_song_played", false))
save.stats_paused_by_win = bool(data.get("stats_paused_by_win", false))
save.server = str(data.get("server", ""))
var folder: Variant = data.get("music_folder", {})
if folder is Dictionary:
save.music_folder_path = str(folder.get("path", ""))
if folder.get("progress") is Dictionary:
save.music_folder_progress = folder.progress
save.characters_dir = str(data.get("characters_dir", ""))
return save
## Forgets the songs, e.g. when the server's playlist no longer has them. The players are
## kept, without points.
func drop_songs() -> void:
songs.clear()
currently_playing_song = -1
latest_played_song = 0
game_start_song = 0
first_song_played = false
for player: PlayerObject in players:
player.reset_points()
+1
View File
@@ -0,0 +1 @@
uid://cfabuhf854ukp
+13
View File
@@ -88,6 +88,9 @@ var last_seen_version: String = ""
## The folder songs are played from instead of the server, picked in the settings, or null
## to use the server. Kept for this session only.
var music_folder: MusicFolder = null
## The folder characters are read from instead of the server, picked in the settings, or
## empty. Kept for this session only. See [method characters_dir].
var character_folder: String = ""
## The game version, set in Project Settings > Application > Config > Version.
## Releases are made from it, see RELEASING.md.
@@ -233,6 +236,16 @@ func is_prepared_quiz() -> bool:
return music_folder != null && music_folder.kind == MusicFolder.Kind.PREPARED_QUIZ
## The folder the characters come from, or empty for the server's: the folder picked in
## the settings, otherwise the [code]characters[/code] folder of the music folder played.
func characters_dir() -> String:
if !character_folder.is_empty():
return character_folder
if music_folder != null:
return music_folder.characters_path
return ""
func delete_children(node: Node) -> void:
for n: Node in node.get_children():
node.remove_child(n)
+29
View File
@@ -61,6 +61,35 @@ func remove_point(player_id: String) -> void:
players_given_point.erase(player_id)
## The song as a Dictionary that can be written as JSON, for [QuizSave]. A song kept only
## in memory is saved without its file.
func to_dict() -> Dictionary:
return {
"number": song_number, "soundtrack": soundtrack_title, "song": song_title,
"points": players_given_point.duplicate(), "answered": is_answered,
"played": has_played, "playing": is_playing, "path": song_path,
}
## A song made from [param data], as given by [method to_dict], or null when [param data]
## is not a song.
static func from_dict(data: Variant) -> SongObject:
if !(data is Dictionary) || !(data.get("number") is float || data.get("number") is int):
return null
var song_object: SongObject = SongObject.new()
song_object.song_number = int(data.number)
song_object.soundtrack_title = str(data.get("soundtrack", ""))
song_object.song_title = str(data.get("song", ""))
if data.get("points") is Array:
for player_id: Variant in data.points:
song_object.add_point(str(player_id))
song_object.is_answered = bool(data.get("answered", false))
song_object.has_played = bool(data.get("played", false))
song_object.is_playing = bool(data.get("playing", false))
song_object.song_path = str(data.get("path", ""))
return song_object
func _to_string() -> String:
var format_string: String = "song_number: %d | soundtrack_title: %s | song_title: %s" \
+ " | is_answered: %s | has_played: %s | is_playing: %s"