93 lines
2.4 KiB
GDScript
93 lines
2.4 KiB
GDScript
extends Panel
|
|
|
|
const SERVER_HISTORY_PATH := "user://server_history"
|
|
|
|
var _server_history: PackedStringArray = []
|
|
var _history_position: int = 0
|
|
|
|
@onready var _name_edit: LineEdit = $MarginContainer/GridContainer/NameEdit
|
|
@onready var _address_edit: LineEdit = $MarginContainer/GridContainer/AddressEdit
|
|
@onready var _host_button: Button = $MarginContainer/GridContainer/HostButton
|
|
@onready var _join_button: Button = $MarginContainer/GridContainer/JoinButton
|
|
@onready var _error_label: Label = $ErrorLabel
|
|
|
|
|
|
func _ready() -> void:
|
|
if Networker.is_dedicated_server():
|
|
return
|
|
|
|
_host_button.pressed.connect(_on_host_button_pressed)
|
|
_join_button.pressed.connect(_on_join_button_pressed)
|
|
Networker.network_error.connect(_on_networker_network_error)
|
|
_error_label.text = ""
|
|
_name_edit.grab_focus()
|
|
|
|
var file := FileAccess.open(SERVER_HISTORY_PATH, FileAccess.READ)
|
|
if file:
|
|
_server_history = file.get_as_text().strip_edges().split("\n")
|
|
|
|
|
|
func _input(event: InputEvent) -> void:
|
|
if _address_edit.has_focus():
|
|
if (
|
|
event.is_action_pressed("ui_up")
|
|
and _history_position + 1 <= _server_history.size()
|
|
):
|
|
_history_position += 1
|
|
_set_address_from_history()
|
|
|
|
if event.is_action_pressed("ui_down") and _history_position - 1 >= 0:
|
|
_history_position -= 1
|
|
_set_address_from_history()
|
|
|
|
|
|
func _set_address_from_history() -> void:
|
|
if _history_position > 0:
|
|
var address := _server_history[-_history_position]
|
|
_address_edit.text = address
|
|
else:
|
|
_address_edit.text = ""
|
|
|
|
|
|
func _display_error(message: String) -> void:
|
|
_error_label.text = message
|
|
|
|
|
|
func _on_host_button_pressed() -> void:
|
|
if !_name_edit.text:
|
|
_display_error("Name cannot be empty")
|
|
return
|
|
|
|
Networker.set_local_player_info(_name_edit.text)
|
|
Networker.host_game()
|
|
|
|
|
|
func _on_join_button_pressed() -> void:
|
|
if !_name_edit.text:
|
|
_display_error("Name cannot be empty")
|
|
return
|
|
|
|
_join_button.disabled = true
|
|
_host_button.disabled = true
|
|
|
|
var address := _address_edit.text
|
|
|
|
if not (address in _server_history):
|
|
_server_history.append(address)
|
|
var file := FileAccess.open(SERVER_HISTORY_PATH, FileAccess.READ_WRITE)
|
|
if file:
|
|
file.seek_end()
|
|
file.store_line(address)
|
|
else:
|
|
file = FileAccess.open(SERVER_HISTORY_PATH, FileAccess.WRITE)
|
|
file.store_line(address)
|
|
|
|
Networker.set_local_player_info(_name_edit.text)
|
|
Networker.join_game(address)
|
|
|
|
|
|
func _on_networker_network_error(message: String) -> void:
|
|
_join_button.disabled = false
|
|
_host_button.disabled = false
|
|
_display_error(message)
|