summaryrefslogtreecommitdiff
path: root/Game
diff options
context:
space:
mode:
authorDaniel Weipert <git@mail.dweipert.de>2024-11-27 14:36:20 +0100
committerDaniel Weipert <git@mail.dweipert.de>2024-11-27 14:36:20 +0100
commita854a1862a30632e49520f6e1e11333d5c8ff241 (patch)
tree2b10c4d19bb66b270a7726d660ed85d7fcf9482e /Game
parentcb9bb9d1c757b53707c741a3c8c218b513ffb5ec (diff)
next commitHEADmain
Diffstat (limited to 'Game')
-rw-r--r--Game/Client.gd56
-rw-r--r--Game/Client.tscn3
-rw-r--r--Game/Lobby/Server/index.php56
-rw-r--r--Game/Lobby/game_lobby.gd89
-rw-r--r--Game/Network.gd19
5 files changed, 153 insertions, 70 deletions
diff --git a/Game/Client.gd b/Game/Client.gd
index fd24a07..6e08a58 100644
--- a/Game/Client.gd
+++ b/Game/Client.gd
@@ -11,10 +11,6 @@ signal multi_select_finished(nodes)
var previous_scene: String
-var game_lobby_url := "http://localhost:8910"
-@onready var game_lobby_server: HTTPRequest = %GameLobbyServer
-var current_game_id := ""
-
var state: State :
set(value):
state = value
@@ -109,12 +105,26 @@ func update_unit(path: NodePath, data: Unit.NetworkData):
func change_scene_to_instance(scene: Node):
(func():
+ previous_scene = get_tree().current_scene.get_path()
+
get_tree().current_scene.queue_free()
get_tree().root.add_child(scene)
get_tree().current_scene = scene
).call_deferred()
+func get_config() -> ConfigFile:
+ var config := ConfigFile.new()
+ config.load("user://config")
+
+ if not FileAccess.file_exists("user://config"):
+ config.set_value("general", "host_default_port", 1234)
+ config.set_value("general", "game_lobby_server_base_url", "http://localhost:8910")
+ config.save("user://config")
+
+ return config
+
+
func array_intersect(first, second):
var compare = {}
for value in first:
@@ -125,41 +135,3 @@ func array_intersect(first, second):
return true
return false
-
-
-class HTTPResponse extends Resource:
- var result_code: HTTPRequest.Result
- var response_code: int
- var headers: PackedStringArray
- var body: PackedByteArray
- func parse_json() -> Dictionary:
- return JSON.parse_string(body.get_string_from_utf8())
-
-func request(
- url: String,
- custom_headers: PackedStringArray = PackedStringArray(),
- method: HTTPClient.Method = HTTPClient.METHOD_GET,
- request_data: String = ""
-) -> HTTPResponse:
- var response = HTTPResponse.new()
-
- %GameLobbyServer.request_completed.connect(
- func (
- result_code: int,
- response_code: int,
- headers: PackedStringArray,
- body: PackedByteArray
- ):
- response.result_code = result_code
- response.response_code = response_code
- response.headers = headers
- response.body = body
- )
- %GameLobbyServer.request(url, custom_headers, method, request_data)
-
- await %GameLobbyServer.request_completed
- return response
-
-func check_game_lobby_available() -> bool:
- var response = await Client.request("%s" % [Client.game_lobby_url], [], HTTPClient.METHOD_GET)
- return response.result_code == HTTPRequest.RESULT_SUCCESS
diff --git a/Game/Client.tscn b/Game/Client.tscn
index ba9a1a8..db2a8b2 100644
--- a/Game/Client.tscn
+++ b/Game/Client.tscn
@@ -4,6 +4,3 @@
[node name="Client" type="Node"]
script = ExtResource("1_kj0qy")
-
-[node name="GameLobbyServer" type="HTTPRequest" parent="."]
-unique_name_in_owner = true
diff --git a/Game/Lobby/Server/index.php b/Game/Lobby/Server/index.php
index 16be3ef..ae734a6 100644
--- a/Game/Lobby/Server/index.php
+++ b/Game/Lobby/Server/index.php
@@ -2,9 +2,11 @@
/*
* Routes:
- * /host ?host&port=$port&name=$name
- * /get-list ?get-list
- * /join ?join=$id
+ * /host ?port=$port&name=$name
+ * /get-list ?
+ * /join ?id=$id
+ * /close ?id=$id
+ * /keep-alive ?id=$id
*/
$dbname = $_ENV['DB_NAME'] ?? 'db';
@@ -24,7 +26,8 @@ if (php_sapi_name() == 'cli') {
port integer,
creation_time integer,
ping_time integer,
- name text
+ name text,
+ secret text
);
SQL)
->execute();
@@ -33,14 +36,19 @@ if (php_sapi_name() == 'cli') {
return;
}
-$inputPost = json_decode(file_get_contents('php://input'), true);
-if ($inputPost) {
- $_POST = $inputPost + $_POST;
+$url = parse_url("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
+$method = $_SERVER['REQUEST_METHOD'];
+
+if ($method == 'POST') {
+ $inputPost = json_decode(file_get_contents('php://input'), true);
+ if ($inputPost) {
+ $_POST = $inputPost + $_POST;
+ }
}
$response = [];
-if (isset($_POST['host'])) {
+if ($method == 'POST' && $url['path'] == '/host') {
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
if ($ip === false) {
@@ -54,9 +62,10 @@ if (isset($_POST['host'])) {
$port = intval($_POST['port']);
$name = $_POST['name'];
$id = md5($name . time());
+ $secret = md5($id . random_bytes($port));
$success = $db->prepare(<<<SQL
- insert or replace into games (id, ip, port, creation_time, ping_time, name) values (:id, :ip, :port, :timestamp, :timestamp, :name)
+ insert or replace into games (id, ip, port, creation_time, ping_time, name, secret) values (:id, :ip, :port, :timestamp, :timestamp, :name, :secret)
SQL)
->execute([
'id' => $id,
@@ -64,13 +73,16 @@ if (isset($_POST['host'])) {
'port' => $port,
'timestamp' => time(),
'name' => $name,
+ 'secret' => $secret,
]);
-
if ($success) {
$response = [
'success' => $success,
- 'data' => $id,
+ 'data' => [
+ 'id' => $id,
+ 'secret' => $secret,
+ ],
];
} else {
$response = [
@@ -81,7 +93,7 @@ if (isset($_POST['host'])) {
}
}
-else if (isset($_GET['get-list'])) {
+else if ($method == 'GET' && $url['path'] == '/get-list') {
$statement = $db->prepare(<<<SQL
select id, name from games
where ping_time > :comparison_time
@@ -105,8 +117,8 @@ else if (isset($_GET['get-list'])) {
];
}
-else if (isset($_GET['join'])) {
- $id = $_GET['join'];
+else if ($method == 'GET' && $url['path'] == '/join') {
+ $id = $_GET['id'];
$statement = $db->prepare(<<<SQL
select ip, port from games
@@ -136,14 +148,16 @@ else if (isset($_GET['join'])) {
}
}
-else if (isset($_POST['close'])) {
- $id = $_POST['close'];
+else if ($method == 'POST' && $url['path'] == '/close') {
+ $id = $_POST['id'];
+ $secret = $_POST['secret'];
$success = $db->prepare(<<<SQL
- delete from games where id = :id
+ delete from games where id = :id and secret = :secret
SQL)
->execute([
'id' => $id,
+ 'secret' => $secret,
]);
$response = [
@@ -151,14 +165,16 @@ else if (isset($_POST['close'])) {
];
}
-else if (isset($_POST['keep-alive'])) {
- $id = $_POST['keep-alive'];
+else if ($method == 'POST' && $url['path'] == '/keep-alive') {
+ $id = $_POST['id'];
+ $secret = $_POST['secret'];
$success = $db->prepare(<<<SQL
- update games set ping_time = :ping_time where id = :id
+ update games set ping_time = :ping_time where id = :id and secret = :secret
SQL)
->execute([
'id' => $id,
+ 'secret' => $secret,
'ping_time' => time(),
]);
diff --git a/Game/Lobby/game_lobby.gd b/Game/Lobby/game_lobby.gd
new file mode 100644
index 0000000..6bfa8be
--- /dev/null
+++ b/Game/Lobby/game_lobby.gd
@@ -0,0 +1,89 @@
+extends Node
+
+
+class HTTPRequestConfig extends Resource:
+ var headers: PackedStringArray
+ var method: HTTPClient.Method
+ var data: Dictionary
+ var node: HTTPRequest
+
+ @warning_ignore("shadowed_variable")
+ func _init(
+ headers := PackedStringArray(),
+ method := HTTPClient.METHOD_GET,
+ data := {},
+ node := HTTPRequest.new()
+ ) -> void:
+ self.headers = headers
+ self.method = method
+ self.data = data
+ self.node = node
+
+
+class HTTPResponse extends Resource:
+ var result_code: HTTPRequest.Result
+ var response_code: int
+ var headers: PackedStringArray
+ var body: PackedByteArray
+
+ func parse_json() -> Dictionary:
+ return JSON.parse_string(body.get_string_from_utf8())
+
+
+var server_base_url: String = Client.get_config().get_value("general", "game_lobby_server_base_url")
+var current_game_id: String
+var current_secret: String
+
+
+func request(
+ url: String,
+ config: HTTPRequestConfig = HTTPRequestConfig.new()
+) -> HTTPResponse:
+ get_tree().root.add_child(config.node)
+
+ if config.method == HTTPClient.METHOD_POST:
+ config.set("id", current_game_id)
+ config.set("secret", current_secret)
+
+ var response = HTTPResponse.new()
+ config.node.request_completed.connect(
+ func (
+ result_code: int,
+ response_code: int,
+ headers: PackedStringArray,
+ body: PackedByteArray
+ ):
+ response.result_code = result_code
+ response.response_code = response_code
+ response.headers = headers
+ response.body = body
+
+ get_tree().root.remove_child(config.node)
+ )
+ config.node.request(
+ "%s%s" % [server_base_url, url],
+ config.headers,
+ config.method,
+ JSON.stringify(config.data)
+ )
+
+ await config.node.request_completed
+ return response
+
+
+func request_get(url: String, headers := PackedStringArray()):
+ var config := HTTPRequestConfig.new(headers)
+
+ return await request(url, config)
+
+
+func request_post(url: String, data: Dictionary = {}, headers := PackedStringArray()):
+ var config := HTTPRequestConfig.new(headers, HTTPClient.METHOD_POST, data)
+
+ return await request(url, config)
+
+
+func check_available() -> bool:
+ var response = await GameLobby.request_get("")
+
+ return response.result_code == HTTPRequest.RESULT_SUCCESS
diff --git a/Game/Network.gd b/Game/Network.gd
index 23542e2..2858d98 100644
--- a/Game/Network.gd
+++ b/Game/Network.gd
@@ -16,17 +16,25 @@ func _ready():
multiplayer.allow_object_decoding = true
-func host_game(port):
+func host_game(port) -> Error:
var peer = ENetMultiplayerPeer.new()
- peer.create_server(int(port))
+ var error = peer.create_server(int(port))
+
+ if error != OK:
+ return error
multiplayer.multiplayer_peer = peer
Client.player.id = multiplayer.get_unique_id()
+
+ return error
func join_game(ip, port):
var peer = ENetMultiplayerPeer.new()
- peer.create_client(ip, int(port))
+ var error = peer.create_client(ip, int(port))
+
+ if error != OK:
+ return error
multiplayer.multiplayer_peer = peer
@@ -37,8 +45,9 @@ func close_game():
multiplayer.multiplayer_peer = OfflineMultiplayerPeer.new()
reset_players()
- await Client.request(Client.game_lobby_url, [], HTTPClient.METHOD_POST, JSON.stringify({"close": Client.current_game_id}))
- Client.current_game_id = ""
+ await GameLobby.request_post("/close")
+ GameLobby.current_game_id = ""
+ GameLobby.current_secret = ""
func _on_connected_to_server():