1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Server to host multiplayer games
18 import gamnit
::network
23 redef class RemoteClient
24 # `Player` associated to this client
25 var player
= new Player
31 var game
= new TGame is lazy
, writable
33 # Is this a dedicated server
36 # Create and run a new `Game`
42 print
"Server: Setup game"
46 print
"Server: Starting play"
50 # Run the server logic over a single turn
56 var turn
= game
.do_turn
58 # Respond to discovery requests sent over UDP
59 answer_discovery_requests
62 var new_clients
= accept_clients
63 for client
in new_clients
do
64 # Register player and spawn first tank
65 game
.players
.add client
.player
66 turn
.spawn_tank client
.player
68 client
.writer
.serialize game
69 client
.writer
.serialize client
.player
75 if dedicated
and clients
.is_empty
then
76 # No clients, sleep for a while
77 nanosleep
(0, 10000000)
84 # Get orders from players
85 var clients_to_remove
= new Array[RemoteClient]
86 for client
in clients
do
87 if not client
.socket
.poll_in
then continue
89 var orders
= client
.reader
.deserialize
90 var errors
= client
.reader
.errors
91 if errors
.not_empty
then
92 print_error
"Comm Error: (Dropping client) {errors.join(", ")}"
93 clients_to_remove
.add client
94 else if not orders
isa Array[TOrder] then
95 if orders
== null then
96 print_error
"Comm Error: (Dropping client) Unexpected null"
97 else print_error
"Comm Error: (Dropping client) Unexpected {orders.class_name}"
98 # TODO remove code duplication when we have ? or an equivalent
100 clients_to_remove
.add client
102 client
.player
.orders
.add_all orders
106 for client
in clients_to_remove
do clients
.remove client