gpml/script/calendar.gd
2024-05-28 02:58:12 +02:00

112 lines
3 KiB
GDScript

class_name Calendar
extends Control
@export var month_scene: PackedScene
@onready var year_label = $CenterContainer/VBoxContainer/YearLabel
@onready var months = $CenterContainer/VBoxContainer/Months
var last_focused_day = null
var all_days = []
# Called when the node enters the scene tree for the first time.
func _ready():
var current_year = Time.get_date_dict_from_system().year
year_label.text = "%s" % current_year
for i in range(1, 13):
var month = month_scene.instantiate()
month.year = current_year
month.month = i
month.day_toggled.connect(_on_day_toggled)
month.fill_days.connect(_on_fill_days)
months.add_child(month)
if FileAccess.file_exists("user://savegame.save"):
load_days()
for month in months.get_children():
if month is Month:
for element in month.days.get_children():
if element is Day:
all_days.append(element)
func load_days():
var save_game = FileAccess.open("user://savegame.save", FileAccess.READ)
while save_game.get_position() < save_game.get_length():
var json_string = save_game.get_line()
var json = JSON.new()
var parse_result = json.parse(json_string)
if not parse_result == OK:
print("JSON parse error: %s in %s at line %s" % [json.get_error_message(), json_string, json.get_error_line()])
continue
var node_data = json.get_data()
var month = get_month(node_data["month"])
month.instantiate_day(node_data["day"], node_data["is_pressed"])
func get_month(month):
for child in months.get_children():
if child is Month and child.month == month:
return child
func _on_day_toggled(date):
# Update last focused day.
var focused_node = get_viewport().gui_get_focus_owner()
if focused_node is Day:
last_focused_day = focused_node
save()
func _on_fill_days(shift_clicked_day):
# Toogle day from last focused day to current day.
# Assert that last focused day is different from date.
if last_focused_day == null:
return
if shift_clicked_day == last_focused_day:
return
# Determine if date is before or after the last focused day.
var first_day = (
last_focused_day if last_focused_day.is_before(shift_clicked_day) else shift_clicked_day
)
var last_day = shift_clicked_day if first_day == last_focused_day else last_focused_day
# Toggle days between the two days.
var toggle = false
for day in all_days:
if first_day == day:
toggle = true
if toggle:
day.set_pressed_no_signal(true)
if last_day == day:
break
save()
func save():
var save_game = FileAccess.open("user://savegame.save", FileAccess.WRITE)
var saved_nodes = get_tree().get_nodes_in_group("persist")
for node in saved_nodes:
if node.scene_file_path.is_empty():
print("persistant node '%s' is not an instanced scene, skipped" % node.name)
continue
if !node.has_method("save"):
print("persistent node '%s' is missing a save() function, skipped" % node.name)
continue
var node_data = node.call("save")
var json_string = JSON.stringify(node_data)
save_game.store_line(json_string)