bca5ae359d5c17c0fa6a54d4914f6cccdef4d1c0
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 # Shader client code to manage the game context
24 # Context of the game, either local or remote
25 var context
: GameContext is lazy
do
29 var port
= default_listening_port
31 if args
.not_empty
then
32 # Use first argument as the server address
34 if args
.length
> 1 then port
= args
[1].to_i
36 print
"Looking for a server..."
39 s
.enable_broadcast
= true
41 s
.broadcast
(discovery_port
, "Server? {handshake_app_name}")
42 nanosleep
(0, 100_000_000)
44 var ptr
= new Ref[nullable SocketAddress](null)
45 var resp
= s
.recv_from
(1024, ptr
)
48 if not resp
.is_empty
then
49 var words
= resp
.split
(" ")
50 if words
.length
== 3 and words
[0] == "Server!" and words
[1] == handshake_app_name
and words
[2].is_numeric
then
57 if address
== null then
58 print
"Launching a local server"
61 return new LocalServerContext
63 print
"Connecting to:{address}:{port}"
65 # Args are: tinks server_address {port}
66 if args
.length
> 1 then port
= args
[1].to_i
68 # Setup connection config
69 var server_config
= new RemoteServerConfig(address
, port
)
70 var server
= new RemoteServer(server_config
)
72 # Connect then complete handshake
73 assert server
.connect
else print_error
"Connection to server failed with {server.socket.last_error or else "none"}"
74 assert server
.handshake
else print_error
"Handshake with server failed"
76 # Download and setup remote game
77 var context
= new RemoteGameContext(server
)
84 # `Tank` of the local player, if any
85 fun local_tank
: nullable Tank
87 # FIXME use a ? to one line this
88 var local_player
= context
.local_player
89 if local_player
== null then return null
90 return local_player
.tank