File: client.cpp

package info (click to toggle)
burgerspace 1.9.2-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,524 kB
  • sloc: sh: 10,939; cpp: 5,791; makefile: 240
file content (374 lines) | stat: -rw-r--r-- 11,283 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*  $Id: client.cpp,v 1.5 2010/11/18 05:35:02 sarrazip Exp $
    client.cpp - main() function for BurgerSpace

    burgerspace - A hamburger-smashing video game.
    Copyright (C) 2001-2010 Pierre Sarrazin <http://sarrazip.com/>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "BurgerSpaceClient.h"

#include "LocalServer.h"
#include "RemoteServer.h"
#include "util.h"

#include <errno.h>
#include <time.h>
#include <string.h>

#include <sys/types.h>

#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#endif

#ifndef DEFAULT_UDP_SERVER_PORT
#error DEFAULT_UDP_SERVER_PORT must be defined to valid UDP port number
#endif

using namespace std;


#ifdef HAVE_GETOPT_LONG
static struct option knownOptions[] =
{
    { "help",          no_argument,       NULL, 'h' },
    { "version",       no_argument,       NULL, 'v' },
    { "initial-level", required_argument, NULL, 'i' },
    { "ms-per-frame",  required_argument, NULL, 'm' },
    { "no-sound",      no_argument,       NULL, 'n' },
    { "full-screen",   no_argument,       NULL, 'f' },
    { "old-motion",    no_argument,       NULL, 'o' },
    { "z-for-pepper",  no_argument,       NULL, 'z' },
    { "server",        required_argument, NULL, 's' },
    { "port",          required_argument, NULL, 'p' },
    { "chef",          no_argument,       NULL, 'c' },
    { "enemy",         no_argument,       NULL, 'e' },

    { NULL, 0, NULL, 0 }  // marks the end
};


static
void
displayVersionNo()
{
    cout << PROGRAM << " " << VERSION << endl;
}


static
void
displayHelp()
{
    cout << "\n";

    displayVersionNo();

    cout <<
"\n"
"Copyright (C) 2001-2010 Pierre Sarrazin <http://sarrazip.com/>\n"
"This program is free software; you may redistribute it under the terms of\n"
"the GNU General Public License.  This program has absolutely no warranty.\n"
    ;

    cout <<
"\n"
"Known options:\n"
"--help             Display this help page and exit\n"
"--version          Display this program's version number and exit\n"
"--initial-level=N  Start game at level N (N >= 1) [default=1]\n"
"--ms-per-frame=N   N milliseconds per animation frame [default=55]\n"
"                   Min. 1, max. 1000.  50 ms means 20 frames per second\n"
"--no-sound         Disable sound effects [default is to enable them]\n"
"--full-screen      Attempt to use full screen mode [default is window mode]\n"
"--old-motion       Use the old player motion system [default is new system]\n"
"--z-for-pepper     Use Z key to shoot pepper [default is Ctrl key]\n"
"--server=HOSTNAME  Run as a network client and use specified server\n"
"--port=PORT        Specify UDP port of server (only relevant with --server)\n"
"--chef             In network game, play the role of the chef\n"
"--enemy            In network game, play the role of one of the enemies\n"
"\n"
    ;
}
#endif  /* HAVE_GETOPT_LONG */


static RemoteServer *
createRemoteServer(BurgerSpaceClient &client,
                   const string &serverHostname,
                   unsigned short port,
                   Role role,
                   int &errorCode)
{
    // Try to resolve the server hostname:
    hostent *ent = gethostbyname(serverHostname.c_str());
    if (ent == NULL)
    {
        errorCode = -1;
        return NULL;
    }

    try
    {
        // Create and initialize an object representing the remote server:
        RemoteServer *rs = new RemoteServer(client,
                                            (unsigned char *) ent->h_addr_list[0],
                                            port,
                                            role);
        rs->describeClient();
        rs->requestLevelDescription();
        errorCode = 0;
        return rs;
    }
    catch (int errNo)
    {
        errorCode = errNo;
        return NULL;
    }
}


int
main(int argc, char *argv[])
{
    /*  Default game parameters:
    */
    int initLevelNo = 1;
    int millisecondsPerFrame = 55;
    bool useSound = true;
    bool fullScreen = false;
    bool useOldMotionMode = false;
    SDLKey pepperKey = SDLK_LCTRL;
    string serverHostname;  // UDP server hostname if not empty; local server otherwise
    unsigned short port = DEFAULT_UDP_SERVER_PORT;
    Role role = ROLE_SPECTATOR;


    #ifdef HAVE_GETOPT_LONG

    /*  Interpret the command-line options:
    */
    int c;
    do
    {
        c = getopt_long(argc, argv, "", knownOptions, NULL);

        switch (c)
        {
            case EOF:
                break;  // nothing to do

            case 'i':
                {
                    errno = 0;
                    long n = strtol(optarg, NULL, 10);
                    if (errno == ERANGE || n < 1 || n > 500)
                    {
                        cout << "Invalid initial level number.\n";
                        displayHelp();
                        return EXIT_FAILURE;
                    }

                    initLevelNo = int(n);
                }
                break;

            case 'm':
                {
                    errno = 0;
                    long n = strtol(optarg, NULL, 10);
                    if (errno == ERANGE || n < 1 || n > 1000)
                    {
                        cout << "Invalid number of ms per frame.\n";
                        displayHelp();
                        return EXIT_FAILURE;
                    }

                    millisecondsPerFrame = int(n);
                }
                break;

            case 'n':
                useSound = false;
                break;

            case 'f':
                fullScreen = true;
                break;

            case 'o':
                useOldMotionMode = true;
                break;

            case 'z':
                pepperKey = SDLK_z;
                break;

            case 's':
                serverHostname = optarg;
                break;

            case 'p':
                {
                    char *end = NULL;
                    long n = strtol(optarg, &end, 10);
                    if (n < 0 || n > 65535 || end == optarg || *end != '\0')
                    {
                        cerr << PROGRAM << ": --port: invalid UDP port number " << optarg << endl;
                        return EXIT_FAILURE;
                    }
                    port = static_cast<unsigned short>(n);
                }
                break;

            case 'c':
                role = ROLE_CHEF;
                break;

            case 'e':
                role = ROLE_ENEMY;
                break;

            case 'v':
                displayVersionNo();
                return EXIT_SUCCESS;

            case 'h':
                displayHelp();
                return EXIT_SUCCESS;

            default:
                displayHelp();
                return EXIT_FAILURE;
        }
    } while (c != EOF && c != '?');

    #elif defined(_MSC_VER)

    if (argc >= 2)
    {
        if (strcmp(argv[1], "--help") == 0)
        {
            cout << PROGRAM << " " << VERSION << ": copyrighted and distributed under GNU GPL\n"
                 << "\n"
                 << "Stand-alone:    " PACKAGE "\n"
                 << "Network client: " PACKAGE " SERVER [chef|enemy]\n";
            return EXIT_SUCCESS;
        }

        // argv[1] expected to be of form "SERVER KEYWORD" where
        // SERVER is a hostname and KEYWORD is either 'chef' or 'enemy'
        size_t i;
        const char *arg = argv[1];
        for (i = 0; arg[i] != '\0' && !isspace(arg[i]); ++i)
            ;

        serverHostname.assign(arg, i);  // prefix of 'arg' up to space or end

        for ( ; isspace(arg[i]); ++i)
            ;

        if (strcmp(arg + i, "chef") == 0)
            role = ROLE_CHEF;
        else if (strcmp(arg + i, "enemy") == 0)
            role = ROLE_ENEMY;
    }

    #endif  /* defined(_MSC_VER) */


    try
    {
        bool standAlone = serverHostname.empty();

        BurgerSpaceClient theBurgerSpaceClient(
                                standAlone ? ROLE_CHEF : role,
                                !standAlone /* show role */,
                                useSound, pepperKey, fullScreen,
                                standAlone);

        BurgerSpaceServerInterface *serverInterface = NULL;

        if (standAlone)
        {
            // Create a "local server":
            LocalServer *ls = new LocalServer(theBurgerSpaceClient, initLevelNo, useOldMotionMode);
            ls->finishInit();
            serverInterface = ls;
        }
        else  // remote server version:
        {
            // Upon a successful connection, createRemoteServer() sends
            // a description of this client to the server and requests
            // a level update from the server.
            //
            int errorCode = 0;
            serverInterface = createRemoteServer(theBurgerSpaceClient, serverHostname, port, role, errorCode);
            if (serverInterface == NULL)
            {
                switch (errorCode)
                {
                    case -1:
                        cerr << PROGRAM << ": failed to resolve hostname "
                                        << serverHostname << endl;
                        break;
                    default:
                        assert(errorCode > 0);
                        cerr << PROGRAM << ": failed to initialize UDP socket for server "
                                        << serverHostname << ":" << port << ": "
                                        << strerror(errorCode) << endl;
                }
                return EXIT_FAILURE;
            }

            cout << PROGRAM << ": using server " << serverHostname << " on port " << port << endl;
        }

        // Associate the created server object with the client,
        // and run the game:
        theBurgerSpaceClient.setServer(serverInterface);
        theBurgerSpaceClient.runClientMode(millisecondsPerFrame);
        serverInterface->disconnect();  // in remote mode, this notifies server of client's departure

        delete serverInterface;
    }
    catch (const string &s)
    {
        cerr << PROGRAM << ": server init error: " << s << endl;
        return EXIT_FAILURE;
    }
    catch (int e)
    {
        cerr << PROGRAM << ": init error # " << e << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}


#ifdef _MSC_VER
int CALLBACK WinMain(__in HINSTANCE hInstance,
                     __in HINSTANCE hPrevInstance,
                     __in LPSTR lpCmdLine,
                     __in int nCmdShow)
{
    char *argv[] = { PROGRAM, NULL };
    return main(1, argv);
}
#endif  // def _MSC_VER