TableTower/core/tower_board.gd

79 lines
2 KiB
GDScript3
Raw Normal View History

class_name TowerBoard
extends RefCounted
## Every table on the board, plus loading and saving as JSON.
const SAVE_PATH := "user://board.json"
const FORMAT_VERSION := 1
static var _counter: int = 0
static var _salt: String = ""
var tables: Array[RollTable] = []
static func new_id(prefix: String) -> String:
if _salt == "":
_salt = "%x" % (int(Time.get_unix_time_from_system()) % 0xfffff)
_counter += 1
return "%s%s_%d" % [prefix, _salt, _counter]
func get_table(id: String) -> RollTable:
for t in tables:
if t.id == id:
return t
return null
## Removes a table and every pipe that pointed at it.
func remove_table(id: String) -> void:
for i in range(tables.size() - 1, -1, -1):
if tables[i].id == id:
tables.remove_at(i)
for t in tables:
for e in t.entries:
e.pipes.erase(id)
func to_dict() -> Dictionary:
var list: Array = []
for t in tables:
list.append(t.to_dict())
return {"format_version": FORMAT_VERSION, "tables": list}
func to_json() -> String:
return JSON.stringify(to_dict(), " ")
## Replaces the board's tables from JSON text. Returns false if the text isn't a board.
func load_json(text: String) -> bool:
var parsed: Variant = JSON.parse_string(text)
if not (parsed is Dictionary) or not (parsed.get("tables") is Array):
return false
var loaded: Array[RollTable] = []
for td in parsed["tables"]:
if td is Dictionary:
loaded.append(RollTable.from_dict(td))
tables = loaded
return true
func save(path: String = SAVE_PATH) -> bool:
var f := FileAccess.open(path, FileAccess.WRITE)
if f == null:
push_warning("Couldn't save the board to %s: %s" % [path, error_string(FileAccess.get_open_error())])
return false
f.store_string(to_json())
return true
## Loads the saved board, or returns null if there isn't a usable one.
static func load_saved(path: String = SAVE_PATH) -> TowerBoard:
if not FileAccess.file_exists(path):
return null
var b := TowerBoard.new()
if not b.load_json(FileAccess.get_file_as_string(path)) or b.tables.is_empty():
return null
return b