taqin/src/Main.gd

110 lines
2.9 KiB
GDScript

extends Control
onready var container = $GridContainer
onready var taquin = $GridContainer/Taquin
var _first_popup_call := true
func _ready():
taquin.rect_min_size = get_viewport().get_visible_rect().size * (2.0 / 3.0)
layout_reflow()
if not load_game():
start_fresh()
print("Starting state: ", taquin.current_state_name())
func _notification(what):
if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
save_game()
get_tree().quit() # default behavior
func _gui_input(event):
# Forward events to taquin so we can swipe from anywhere
taquin._gui_input(event)
func layout_reflow():
if container == null:
return
if container.rect_size.x < container.rect_size.y:
# portrait
container.columns = 1
else:
# landscape
container.columns = 2
update()
# https://docs.godotengine.org/en/3.2/tutorials/io/saving_games.html
func save_game():
var save_game = File.new()
save_game.open("user://savegame.save", File.WRITE)
var save_nodes = get_tree().get_nodes_in_group("Persist")
for node in save_nodes:
# Check the node has a save function
if !node.has_method("save"):
print("persistent node '%s' is missing a save() function, skipped" % node.name)
continue
# Call the node's save function
var node_data = node.call("save")
# Augment data with origin
node_data["path"] = node.get_path()
# Store the save dictionary as a new line in the save file
save_game.store_line(to_json(node_data))
save_game.close()
func load_game():
var save_game = File.new()
if not save_game.file_exists("user://savegame.save"):
return false # Error! We don't have a save to load.
# Load the file line by line and process that dictionary to restore
# the object it represents.
save_game.open("user://savegame.save", File.READ)
while save_game.get_position() < save_game.get_len():
# Get the saved dictionary from the next line in the save file
var node_data = parse_json(save_game.get_line())
# Call the node's save function
var node = get_node(node_data["path"])
if node != null:
if node.call("load", node_data) == false:
return false
else:
print("Cannot load node ", node_data["path"])
save_game.close()
return true
func start_fresh():
taquin.start_fresh()
#
# Signals
#
func _on_Taquin_state_changed(previous, new):
print("Taquin state: ", Taquin.State.keys()[previous], " -> ", Taquin.State.keys()[new])
match new:
Taquin.State.WINNING:
print("Solved!")
Taquin.State.GAME_OVER:
pass
func _on_New_game_pressed():
$NewGamePanel.rect_position = Vector2.ZERO
if _first_popup_call:
# We only call popup_centered() once, otherwise the popup shifts to the
# bottom right after each call.
$NewGamePanel.popup_centered_ratio($NewGamePanel.window_scale_factor)
_first_popup_call = false
else:
# After the 1st call, the position should be settled.
$NewGamePanel.popup()
func _on_NewGamePanel_about_to_show():
taquin.set_process_input(false)
func _on_NewGamePanel_popup_hide():
taquin.set_process_input(true)