bca5ae359d5c17c0fa6a54d4914f6cccdef4d1c0
[nit.git] / contrib / tinks / src / client / base.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 # Shader client code to manage the game context
16 module base
17
18 import app
19
20 import context
21
22 redef class App
23
24 # Context of the game, either local or remote
25 var context: GameContext is lazy do
26
27 # Server info
28 var address = null
29 var port = default_listening_port
30
31 if args.not_empty then
32 # Use first argument as the server address
33 address = args[0]
34 if args.length > 1 then port = args[1].to_i
35 else
36 print "Looking for a server..."
37
38 var s = new UDPSocket
39 s.enable_broadcast = true
40 s.blocking = false
41 s.broadcast(discovery_port, "Server? {handshake_app_name}")
42 nanosleep(0, 100_000_000)
43
44 var ptr = new Ref[nullable SocketAddress](null)
45 var resp = s.recv_from(1024, ptr)
46 var src = ptr.item
47
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
51 address = src.address
52 port = words[2].to_i
53 end
54 end
55 end
56
57 if address == null then
58 print "Launching a local server"
59
60 # No command line
61 return new LocalServerContext
62 else
63 print "Connecting to:{address}:{port}"
64
65 # Args are: tinks server_address {port}
66 if args.length > 1 then port = args[1].to_i
67
68 # Setup connection config
69 var server_config = new RemoteServerConfig(address, port)
70 var server = new RemoteServer(server_config)
71
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"
75
76 # Download and setup remote game
77 var context = new RemoteGameContext(server)
78 context.setup
79
80 return context
81 end
82 end
83
84 # `Tank` of the local player, if any
85 fun local_tank: nullable Tank
86 do
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
91 end
92 end