harvest/game/scripts/main.gd
2026-10-04 12:07:36 -04:00

384 lines
12 KiB
GDScript

class_name Main
extends Node
## The game's entry scene (game/scenes/main.tscn): the farm (farm.tscn) with the menus over it.
## * Starts at the main menu: the tree is paused (the farm stands still) and a camera slowly
## circles the farm behind the menu; the HUD is hidden.
## * New vacation (asks first when it would replace a save), Continue (the saved morning,
## SaveGame; refused with the reason when the save can't be used), Settings, Quit.
## * During play, Escape / Start pauses (PauseMenu): the tree pauses, so the simulation tick,
## timers, enemies, and game sounds all freeze. Resume, Restart the night (asks first),
## Settings, Save & quit to menu, Quit the game (asks first).
## * Every morning is autosaved (CampaignController.save_path). Back at the menu the farm is
## put back at that morning without saving again, so the menu never changes the save.
## * Settings (GameSettings) load at start and are applied and saved on every change.
## * Play with a friend (CoopMenu): host (continue or start a vacation, then the lobby opens,
## CoopLobby) or join (the games found). When both are in, the farm's CoopSession takes over
## over GD-Sync (GDSyncLink), with voice chat. In co-op the menus don't pause the farm; the
## host's leaving ends the partner's game (back to this menu, which says why), the partner's
## leaving leaves the host alone. [M] mutes the microphone.
## Main processes while paused; the farm doesn't. Tests set save_path and settings_path
## before adding it to the tree.
enum Screen { MENU, PLAYING, PAUSED }
const ORBIT_CENTER := Vector3(17.0, 0.0, -15.0)
const ORBIT_RADIUS := 44.0
const ORBIT_HEIGHT := 26.0
const ORBIT_SPEED := 0.035
var save_path := SaveGame.PATH
var settings_path := GameSettings.PATH
var screen: Screen = Screen.MENU
var settings: GameSettings
var quitting := false
## Why the last co-op game ended, for the main menu after the scene reloads.
static var notice := ""
var lobby: CoopLobby
var coop_hud: CoopHud
@onready var farm: Node3D = $Farm
@onready var sim: FarmSim = $Farm/FarmSim
@onready var main_menu: MainMenu = $Menus/MainMenu
@onready var pause_menu: PauseMenu = $Menus/PauseMenu
@onready var settings_menu: SettingsMenu = $Menus/SettingsMenu
@onready var confirm: ConfirmBox = $Menus/ConfirmBox
@onready var coop_menu: CoopMenu = $Menus/CoopMenu
var _menu_camera: Camera3D
var _orbit: float = 0.6
func _ready() -> void:
get_tree().auto_accept_quit = false # the window's close button goes through quit_game()
process_mode = Node.PROCESS_MODE_ALWAYS
farm.process_mode = Node.PROCESS_MODE_PAUSABLE
settings = GameSettings.load_from(settings_path)
settings.apply(get_viewport(), sim.config)
sim.campaign.save_path = save_path
if sim.end_panel != null:
sim.end_panel.has_menu = true
sim.end_panel.menu_requested.connect(to_menu)
if sim.tutorial != null:
sim.tutorial.enabled = settings.show_tips
main_menu.continue_requested.connect(continue_vacation)
main_menu.new_requested.connect(_ask_new_vacation)
main_menu.settings_requested.connect(_open_settings)
main_menu.quit_requested.connect(quit_game)
pause_menu.resume_requested.connect(resume)
pause_menu.restart_requested.connect(func() -> void:
confirm.ask("Restart night %d from this morning? Everything since the morning is lost." % sim.campaign.state.night,
"Restart the night", restart_night))
pause_menu.settings_requested.connect(_open_settings)
pause_menu.menu_requested.connect(to_menu)
pause_menu.quit_requested.connect(func() -> void:
confirm.ask("Quit the game? Continue picks up at the morning of day %d." % sim.campaign.state.night, "Quit", quit_game))
settings_menu.changed.connect(_on_settings_changed)
settings_menu.closed.connect(_on_settings_closed)
lobby = CoopLobby.new()
lobby.name = "Lobby"
add_child(lobby)
main_menu.coop_requested.connect(func() -> void:
main_menu.close()
coop_menu.open(SaveGame.read(save_path), sim.config.campaign_nights, settings.player_name))
coop_menu.back_requested.connect(func() -> void:
lobby.leave()
coop_menu.close()
show_main_menu())
coop_menu.host_requested.connect(_host_coop)
coop_menu.search_requested.connect(func(mode: CoopLobby.Mode, player: String) -> void:
_remember_name(player)
lobby.search(mode, player))
coop_menu.join_requested.connect(func(n: String) -> void: lobby.join(n))
coop_menu.join_address_requested.connect(func(a: String) -> void:
_remember_name(coop_menu.player_name())
lobby.join_address(a, coop_menu.player_name()))
lobby.status_changed.connect(func(text: String) -> void:
if coop_menu.is_open:
coop_menu.set_status(text))
lobby.failed.connect(func(text: String) -> void:
if coop_menu.is_open:
coop_menu.set_status(text)
elif sim.toasts != null:
sim.toasts.push(text, Color(1.0, 0.6, 0.4)))
lobby.lobbies_found.connect(func(list: Array) -> void: coop_menu.show_lobbies(list))
lobby.partner_arrived.connect(_on_partner_arrived)
lobby.joined.connect(_on_joined)
lobby.other_left.connect(_on_other_left)
var session := sim.coop
session.process_mode = Node.PROCESS_MODE_ALWAYS # a join arrives while the menus pause the farm
if lobby.gdsync != null:
lobby.gdsync.expose_func(session.net_receive) # before anyone can call it
session.welcomed.connect(_on_welcomed)
session.ended.connect(_on_session_ended)
coop_hud = CoopHud.new()
coop_hud.name = "CoopHud"
coop_hud.setup(sim, session, lobby)
var hud_layer := farm.get_node_or_null("Hud")
if hud_layer != null:
hud_layer.add_child(coop_hud)
if sim.audio != null:
sim.audio.wire_buttons($Menus)
_menu_camera = Camera3D.new()
_menu_camera.fov = 50.0
add_child(_menu_camera)
show_main_menu()
func _process(delta: float) -> void:
if screen == Screen.MENU:
_orbit += ORBIT_SPEED * delta
_place_menu_camera()
func show_main_menu() -> void:
screen = Screen.MENU
get_tree().paused = true
_set_hud(false)
pause_menu.close()
_place_menu_camera()
_menu_camera.make_current()
main_menu.open(SaveGame.read(save_path), sim.config.campaign_nights)
main_menu.notice.text = notice
notice = ""
## Continue: the saved morning, if it can be used.
func continue_vacation() -> bool:
var saved := SaveGame.read(save_path)
if saved.status != SaveGame.Status.OK:
main_menu.open(saved, sim.config.campaign_nights)
if sim.audio != null:
sim.audio.ui("error")
return false
_play()
sim.campaign.load_state(saved.state)
return true
## New vacation: a fresh farm, the morning of night 1 (saved at once, replacing any save).
func new_vacation() -> void:
_play()
sim.campaign.new_campaign()
func pause() -> void:
if screen != Screen.PLAYING:
return
screen = Screen.PAUSED
var coop := 0
if sim.coop.is_host():
coop = 1
elif sim.coop.is_client():
coop = 2
if coop == 0:
get_tree().paused = true
else:
sim.freeze_local(true) # co-op: the farm doesn't stop for one player's menu
pause_menu.open(sim.campaign, coop)
func resume() -> void:
if screen != Screen.PAUSED:
return
confirm.close()
settings_menu.close()
pause_menu.close()
screen = Screen.PLAYING
get_tree().paused = false
if sim.local_frozen:
sim.freeze_local(false)
func restart_night() -> void:
resume()
sim.campaign.retry_night()
## Back to the main menu, with the farm reset to the saved morning (nothing is saved). In co-op
## the host ends the game for both; a partner leaves (their game resets).
func to_menu() -> void:
confirm.close()
settings_menu.close()
if sim.coop.is_client():
_leave_as_partner("")
return
sim.coop.stop()
lobby.leave()
var c := sim.campaign
c.save_path = ""
if c.outcome == CampaignController.Outcome.VACATION_COMPLETE or not SaveGame.exists(save_path):
c.new_campaign()
else:
c.retry_night()
c.save_path = save_path
show_main_menu()
## Quits (the save is the morning's; nothing else to write): the farm goes first, and the audio
## server gets a moment to drop its stopped sounds.
func quit_game() -> void:
if quitting:
return
quitting = true
sim.coop.stop()
lobby.leave()
if is_instance_valid(farm):
farm.queue_free()
await get_tree().process_frame
await get_tree().create_timer(0.2, true, false, true).timeout
get_tree().quit()
func _notification(what: int) -> void:
if what == NOTIFICATION_WM_CLOSE_REQUEST:
quit_game()
func _play() -> void:
main_menu.close()
confirm.close()
settings_menu.close()
pause_menu.close()
_set_hud(true)
sim.camera.make_current()
screen = Screen.PLAYING
get_tree().paused = false
## Hosting: the vacation first (the save, or a new one), then the lobby opens; the friend can
## join any time.
func _host_coop(mode: CoopLobby.Mode, player: String, resume: bool) -> void:
_remember_name(player)
var go := func() -> void:
coop_menu.close()
if resume:
if not continue_vacation():
return
else:
new_vacation()
lobby.host(mode, player)
if not resume and SaveGame.read(save_path).status == SaveGame.Status.OK:
confirm.ask("Start a new vacation? It replaces your saved one.", "New vacation", go)
else:
go.call()
func _on_partner_arrived(client_id: int) -> void:
var gd := lobby.gdsync
gd.expose_func(sim.coop.net_receive)
var link := GDSyncLink.new(gd, client_id, sim.coop)
sim.coop.start_host(sim, link, lobby.my_name, String(gd.player_get_username(client_id, "Friend")))
sim.coop.start_voice(gd, [lobby.my_id(), client_id], settings.microphone)
func _on_joined(host_id: int) -> void:
var gd := lobby.gdsync
gd.expose_func(sim.coop.net_receive)
var link := GDSyncLink.new(gd, host_id, sim.coop)
sim.coop.start_client(sim, link, lobby.my_name)
sim.coop.start_voice(gd, [host_id, lobby.my_id()], settings.microphone)
coop_menu.set_status("Joined: waiting for the farm...")
func _on_welcomed() -> void:
coop_menu.close()
_play()
func _on_other_left(_client_id: int) -> void:
if sim.coop.is_host():
sim.coop.stop() # the host plays on alone; the lobby stays open
elif sim.coop.is_client():
sim.coop.stop("The host left the game")
func _on_session_ended(reason: String) -> void:
_leave_as_partner(reason)
## A partner's game is a replica of the host's: leaving resets it by reloading the scene.
func _leave_as_partner(reason: String) -> void:
notice = reason
sim.coop.stop()
lobby.leave()
get_tree().paused = false
get_tree().reload_current_scene.call_deferred()
func _remember_name(player: String) -> void:
if player != settings.player_name:
settings.player_name = player
settings.save_to(settings_path)
func _ask_new_vacation() -> void:
var saved := SaveGame.read(save_path)
if saved.status == SaveGame.Status.OK:
confirm.ask("Start a new vacation? It replaces your saved one (the morning of day %d of %d)." % [saved.state.night,
sim.config.campaign_nights], "New vacation", new_vacation)
else:
new_vacation()
func _open_settings() -> void:
pause_menu.visible = false # one menu at a time
settings_menu.open(settings)
func _on_settings_changed() -> void:
settings.apply(get_viewport(), sim.config)
sim.coop.set_microphone(settings.microphone)
if sim.tutorial != null:
sim.tutorial.enabled = settings.show_tips
var err := settings.save_to(settings_path)
if err != OK:
push_warning("Couldn't save settings to %s: %s" % [settings_path, error_string(err)])
func _on_settings_closed() -> void:
match screen:
Screen.MENU:
main_menu.settings_button.grab_focus.call_deferred()
Screen.PAUSED:
pause_menu.visible = true
pause_menu.settings_button.grab_focus.call_deferred()
func _set_hud(on: bool) -> void:
for layer_name in ["Hud", "ZoneBanner"]:
var layer := farm.get_node_or_null(layer_name) as CanvasLayer
if layer != null:
layer.visible = on
func _place_menu_camera() -> void:
var at := ORBIT_CENTER + Vector3(cos(_orbit) * ORBIT_RADIUS, ORBIT_HEIGHT, sin(_orbit) * ORBIT_RADIUS)
_menu_camera.global_position = at
_menu_camera.look_at(ORBIT_CENTER + Vector3(4.0, 0.0, 0.0), Vector3.UP)
func _unhandled_input(event: InputEvent) -> void:
if quitting:
return
if event.is_action_pressed("toggle_mic") and sim.coop.is_active() and not sim.coop.voices.is_empty():
settings.microphone = not settings.microphone
sim.coop.set_microphone(settings.microphone)
settings.save_to(settings_path)
if sim.toasts != null:
sim.toasts.push("Microphone %s" % ("on" if settings.microphone else "muted"), Color(0.85, 0.95, 1.0))
get_viewport().set_input_as_handled()
return
if not event.is_action_pressed("pause"):
return
match screen:
Screen.PLAYING:
pause()
get_viewport().set_input_as_handled()
Screen.PAUSED:
if confirm.is_open:
confirm.close()
elif settings_menu.is_open:
settings_menu.close()
else:
resume()
get_viewport().set_input_as_handled()