Imported Debian patch 0.52-2
[pkg/netris.git] / game.c
1 /*
2  * Netris -- A free networked version of T*tris
3  * Copyright (C) 1994,1995,1996  Mark H. Weaver <mhw@netris.org>
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  * $Id: game.c,v 1.39 1999/05/16 06:56:27 mhw Exp $
20  */
21
22 #define NOEXT
23 #include "netris.h"
24 #include <stdlib.h>
25 #include <ctype.h>
26 #include <string.h>
27 #include <sys/types.h>
28 #include <netinet/in.h>
29
30 enum { KT_left, KT_rotate, KT_right, KT_drop, KT_down,
31         KT_toggleSpy, KT_pause, KT_faster, KT_redraw, KT_new, KT_numKeys };
32
33 static char *keyNames[KT_numKeys+1] = {
34         "Left", "Rotate", "Right", "Drop", "Down", "ToggleSpy", "Pause",
35         "Faster", "Redraw", "New", NULL };
36
37 static char *gameNames[GT_len] = { "OnePlayer", "ClassicTwo" };
38
39 static char keyTable[KT_numKeys+1];
40 static int dropModeEnable = 0;
41 static char *robotProg;
42
43 static int wonLast = 0;
44 int lost = 0, won = 0;
45 enum States gameState = STATE_STARTING;
46
47 ExtFunc void MapKeys(char *newKeys)
48 {
49         int i, k, ch;
50         char used[256];
51         int errs = 0;
52
53         /* XXX assumptions about ASCII encoding here */
54         for (i = k = 0; newKeys[i] && k < KT_numKeys; i++,k++) {
55                 if (newKeys[i] == '^' && newKeys[i+1])
56                         keyTable[k] = toupper(newKeys[++i]) - ('A' - 1);
57                 else
58                         keyTable[k] = newKeys[i];
59         }
60         memset(used, 0, sizeof(used));
61         for (k = 0; k < KT_numKeys; k++) {
62                 ch = (unsigned char) keyTable[k];
63                 if (used[ch]) {
64                         if (iscntrl(ch) && ch < ' ')
65                                 sprintf(scratch, "Ctrl-%c", ch + ('A' - 1));
66                         else if (isprint(ch))
67                                 sprintf(scratch, "\"%c\"", ch);
68                         else
69                                 sprintf(scratch, "0x%X", ch);
70                         if (!errs)
71                                 fprintf(stderr, "Duplicate key mappings:\n");
72                         errs++;
73                         fprintf(stderr, "  %s mapped to both %s and %s\n",
74                                         scratch, keyNames[used[ch]-1], keyNames[k]);
75                 }
76                 used[ch] = k + 1;
77         }
78         if (errs)
79                 exit(1);
80 }
81
82 ExtFunc int StartNewPiece(int scr, Shape *shape)
83 {
84         curShape[scr] = shape;
85         curY[scr] = boardVisible[scr] + 4;
86         curX[scr] = boardWidth[scr] / 2;
87         while (!ShapeVisible(shape, scr, curY[scr], curX[scr]))
88                 --curY[scr];
89         if (!ShapeFits(shape, scr, curY[scr], curX[scr]))
90                 return 0;
91         PlotShape(shape, scr, curY[scr], curX[scr], 1);
92         return 1;
93 }
94
95 ExtFunc void OneGame(int scr, int scr2)
96 {
97         MyEvent event;
98         int linesCleared, changed = 0;
99         int spied = 0, spying = 0, dropMode = 0;
100         int oldPaused = 0, paused = 0, pausedByMe = 0, pausedByThem = 0;
101         long pauseTimeLeft;
102         int pieceCount = 0;
103         int key;
104         char *p, *cmd;
105
106         speed = stepDownInterval;
107         ResetBaseTime();
108         InitBoard(scr);
109         if (scr2 >= 0) {
110                 spied = 1;
111                 spying = 1;
112                 InitBoard(scr2);
113                 UpdateOpponentDisplay();
114         }
115         ShowDisplayInfo();
116         SetITimer(speed, speed);
117         if (robotEnable) {
118                 RobotCmd(0, "GameType %s\n", gameNames[game]);
119                 RobotCmd(0, "BoardSize 0 %d %d\n",
120                                 boardVisible[scr], boardWidth[scr]);
121                 if (scr2 >= 0) {
122                         RobotCmd(0, "BoardSize 1 %d %d\n",
123                                         boardVisible[scr2], boardWidth[scr2]);
124                         RobotCmd(0, "Opponent 1 %s %s\n", opponentName, opponentHost);
125                         if (opponentFlags & SCF_usingRobot)
126                                 RobotCmd(0, "OpponentFlag 1 robot\n");
127                         if (opponentFlags & SCF_fairRobot)
128                                 RobotCmd(0, "OpponentFlag 1 fairRobot\n");
129                 }
130                 RobotCmd(0, "TickLength %.3f\n", speed / 1.0e6);
131                 RobotCmd(0, "BeginGame\n");
132                 RobotTimeStamp();
133         }
134         while (StartNewPiece(scr, ChooseOption(stdOptions))) {
135                 if (robotEnable && !fairRobot)
136                         RobotCmd(1, "NewPiece %d\n", ++pieceCount);
137                 if (spied) {
138                         short shapeNum;
139                         netint2 data[1];
140
141                         shapeNum = ShapeToNetNum(curShape[scr]);
142                         data[0] = hton2(shapeNum);
143                         SendPacket(NP_newPiece, sizeof(data), data);
144                 }
145                 for (;;) {
146                         changed = RefreshBoard(scr) || changed;
147                         if (spying)
148                                 changed = RefreshBoard(scr2) || changed;
149                         if (changed) {
150                                 RefreshScreen();
151                                 changed = 0;
152                         }
153                         CheckNetConn();
154                         switch (WaitMyEvent(&event, EM_any)) {
155                                 case E_alarm:
156                                         if (!MovePiece(scr, -1, 0))
157                                                 goto nextPiece;
158                                         else if (spied)
159                                                 SendPacket(NP_down, 0, NULL);
160                                         break;
161                                 case E_key:
162                                         p = strchr(keyTable, tolower(event.u.key));
163                                         key = p - keyTable;
164                                         if (robotEnable) {
165                                                 RobotCmd(1, "UserKey %d %s\n",
166                                                                 (int)(unsigned char)event.u.key,
167                                                                 p ? keyNames[key] : "?");
168                                                 break;
169                                         }
170                                         if (!p)
171                                                 break;
172                                 keyEvent:
173                                         if (paused && (key != KT_pause) && (key != KT_redraw))
174                                                 break;
175                                         switch(key) {
176                                                 case KT_left:
177                                                         if (MovePiece(scr, 0, -1) && spied)
178                                                                 SendPacket(NP_left, 0, NULL);
179                                                         break;
180                                                 case KT_right:
181                                                         if (MovePiece(scr, 0, 1) && spied)
182                                                                 SendPacket(NP_right, 0, NULL);
183                                                         break;
184                                                 case KT_rotate:
185                                                         if (RotatePiece(scr) && spied)
186                                                                 SendPacket(NP_rotate, 0, NULL);
187                                                         break;
188                                                 case KT_down:
189                                                         if (MovePiece(scr, -1, 0) && spied)
190                                                                 SendPacket(NP_down, 0, NULL);
191                                                         break;
192                                                 case KT_toggleSpy:
193                                                         spying = (!spying) && (scr2 >= 0);
194                                                         break;
195                                                 case KT_drop:
196                                                         if (DropPiece(scr) > 0) {
197                                                                 if (spied)
198                                                                         SendPacket(NP_drop, 0, NULL);
199                                                                 SetITimer(speed, speed);
200                                                         }
201                                                         dropMode = dropModeEnable;
202                                                         break;
203                                                 case KT_pause:
204                                                         pausedByMe = !pausedByMe;
205                                                         if (game == GT_classicTwo) {
206                                                                 netint2 data[1];
207
208                                                                 data[0] = hton2(pausedByMe);
209                                                                 SendPacket(NP_pause, sizeof(data), data);
210                                                         }
211                                                         paused = pausedByMe || pausedByThem;
212                                                         if (robotEnable)
213                                                                 RobotCmd(1, "Pause %d %d\n", pausedByMe,
214                                                                         pausedByThem);
215                                                         ShowPause(pausedByMe, pausedByThem);
216                                                         changed = 1;
217                                                         break;
218                                                 case KT_faster:
219                                                         if (game != GT_onePlayer)
220                                                                 break;
221                                                         speed = speed * 0.8;
222                                                         SetITimer(speed, SetITimer(0, 0));
223                                                         ShowDisplayInfo();
224                                                         changed = 1;
225                                                         break;
226                                                 case KT_redraw:
227                                                         ScheduleFullRedraw();
228                                                         if (paused)
229                                                                 RefreshScreen();
230                                                         break;
231                                         }
232                                         if (dropMode && DropPiece(scr) > 0) {
233                                                 if (spied)
234                                                         SendPacket(NP_drop, 0, NULL);
235                                                 SetITimer(speed, speed);
236                                         }
237                                         break;
238                                 case E_robot:
239                                 {
240                                         int num;
241
242                                         cmd = event.u.robot.data;
243                                         if ((p = strchr(cmd, ' ')))
244                                                 *p++ = 0;
245                                         else
246                                                 p = cmd + strlen(cmd);
247                                         for (key = 0; keyNames[key]; ++key)
248                                                 if (!strcmp(keyNames[key], cmd) &&
249                                                                 (fairRobot || (1 == sscanf(p, "%d", &num) &&
250                                                                         num == pieceCount)))
251                                                         goto keyEvent;
252                                         if (!strcmp(cmd, "Message")) {
253                                                 Message(p);
254                                                 changed = 1;
255                                         }
256                                         break;
257                                 }
258                                 case E_net:
259                                         switch(event.u.net.type) {
260                                                 case NP_giveJunk:
261                                                 {
262                                                         netint2 data[2];
263                                                         short column;
264
265                                                         memcpy(data, event.u.net.data, sizeof(data[0]));
266                                                         column = Random(0, boardWidth[scr]);
267                                                         data[1] = hton2(column);
268                                                         InsertJunk(scr, ntoh2(data[0]), column);
269                                                         if (spied)
270                                                                 SendPacket(NP_insertJunk, sizeof(data), data);
271                                                         break;
272                                                 }
273                                                 case NP_newPiece:
274                                                 {
275                                                         short shapeNum;
276                                                         netint2 data[1];
277
278                                                         FreezePiece(scr2);
279                                                         memcpy(data, event.u.net.data, sizeof(data));
280                                                         shapeNum = ntoh2(data[0]);
281                                                         StartNewPiece(scr2, NetNumToShape(shapeNum));
282                                                         break;
283                                                 }
284                                                 case NP_down:
285                                                         MovePiece(scr2, -1, 0);
286                                                         break;
287                                                 case NP_left:
288                                                         MovePiece(scr2, 0, -1);
289                                                         break;
290                                                 case NP_right:
291                                                         MovePiece(scr2, 0, 1);
292                                                         break;
293                                                 case NP_rotate:
294                                                         RotatePiece(scr2);
295                                                         break;
296                                                 case NP_drop:
297                                                         DropPiece(scr2);
298                                                         break;
299                                                 case NP_clear:
300                                                         ClearFullLines(scr2);
301                                                         break;
302                                                 case NP_insertJunk:
303                                                 {
304                                                         netint2 data[2];
305
306                                                         memcpy(data, event.u.net.data, sizeof(data));
307                                                         InsertJunk(scr2, ntoh2(data[0]), ntoh2(data[1]));
308                                                         break;
309                                                 }
310                                                 case NP_pause:
311                                                 {
312                                                         netint2 data[1];
313
314                                                         memcpy(data, event.u.net.data, sizeof(data));
315                                                         pausedByThem = ntoh2(data[0]);
316                                                         paused = pausedByMe || pausedByThem;
317                                                         if (robotEnable)
318                                                                 RobotCmd(1, "Pause %d %d\n", pausedByMe,
319                                                                         pausedByThem);
320                                                         ShowPause(pausedByMe, pausedByThem);
321                                                         changed = 1;
322                                                         break;
323                                                 }
324                                                 default:
325                                                         break;
326                                         }
327                                         break;
328                                 case E_lostRobot:
329                                 case E_lostConn:
330                                         wonLast = 1;
331                                         goto gameOver;
332                                 default:
333                                         break;
334                         }
335                         if (paused != oldPaused) {
336                                 if (paused)
337                                         pauseTimeLeft = SetITimer(0, 0);
338                                 else
339                                         SetITimer(speed, pauseTimeLeft);
340                                 oldPaused = paused;
341                         }
342                 }
343         nextPiece:
344                 dropMode = 0;
345                 FreezePiece(scr);
346                 linesCleared = ClearFullLines(scr);
347                 if (linesCleared > 0 && spied)
348                         SendPacket(NP_clear, 0, NULL);
349                 if (game == GT_classicTwo && linesCleared > 1) {
350                         short junkLines;
351                         netint2 data[1];
352
353                         junkLines = linesCleared - (linesCleared < 4);
354                         data[0] = hton2(junkLines);
355                         SendPacket(NP_giveJunk, sizeof(data), data);
356                 }
357         }
358         wonLast = 0;
359
360 gameOver:
361         SetITimer(0, 0);
362 }
363
364 ExtFunc int main(int argc, char **argv)
365 {
366         int initConn = 0, waitConn = 0, ch, done = 0;
367         char *hostStr = NULL, *portStr = NULL;
368         MyEvent event;
369
370         standoutEnable = colorEnable = 1;
371         stepDownInterval = DEFAULT_INTERVAL;
372         MapKeys(DEFAULT_KEYS);
373         while ((ch = getopt(argc, argv, "hHRs:r:Fk:c:woDSCp:i:")) != -1)
374                 switch (ch) {
375                         case 'c':
376                                 initConn = 1;
377                                 hostStr = optarg;
378                                 break;
379                         case 'w':
380                                 waitConn = 1;
381                                 break;
382                         case 'p':
383                                 portStr = optarg;
384                                 break;
385                         case 'i':
386                                 stepDownInterval = atof(optarg) * 1e6;
387                                 break;
388                         case 's':
389                                 initSeed = atoi(optarg);
390                                 myFlags |= SCF_setSeed;
391                                 break;
392                         case 'r':
393                                 robotEnable = 1;
394                                 robotProg = optarg;
395                                 myFlags |= SCF_usingRobot;
396                                 break;
397                         case 'F':
398                                 fairRobot = 1;
399                                 myFlags |= SCF_fairRobot;
400                                 break;
401                         case 'D':
402                                 dropModeEnable = 1;
403                                 break;
404                         case 'C':
405                                 colorEnable = 0;
406                                 break;
407                         case 'S':
408                                 standoutEnable = 0;
409                                 break;
410                         case 'k':
411                                 MapKeys(optarg);
412                                 break;
413                         case 'H':
414                                 DistInfo();
415                                 exit(0);
416                         case 'R':
417                                 Rules();
418                                 exit(0);
419                         case 'h':
420                                 Usage();
421                                 exit(0);
422                         default:
423                                 Usage();
424                                 exit(1);
425                 }
426         if (optind < argc || (initConn && waitConn)) {
427                 Usage();
428                 exit(1);
429         }
430         if (fairRobot && !robotEnable)
431                 fatal("You can't use the -F option without the -r option");
432         InitUtil();
433         InitScreens();  
434         while(!done) {
435                 if (robotEnable)
436                         InitRobot(robotProg);
437                 InitNet();
438                 SRandom(time(0));
439                 if (initConn || waitConn) {
440                         game = GT_classicTwo;
441                         if(gameState != STATE_STARTING) {
442                                 gameState = STATE_WAIT_CONNECTION;
443                                 ShowDisplayInfo();
444                                 RefreshScreen();
445                         }
446                         if (initConn)
447                                 InitiateConnection(hostStr, portStr);
448                         else if (waitConn)
449                                 WaitForConnection(portStr);
450                         gameState = STATE_PLAYING;
451                         ShowDisplayInfo();
452                         RefreshScreen();
453                         {
454                                 netint4 data[2];
455                                 int major;
456                                 
457                                 data[0] = hton4(MAJOR_VERSION);
458                                 data[1] = hton4(PROTOCOL_VERSION);
459                                 SendPacket(NP_version, sizeof(data), data);
460                                 if (WaitMyEvent(&event, EM_net) != E_net)
461                                         fatal("Network negotiation failed");
462                                 memcpy(data, event.u.net.data, sizeof(data));
463                                 major = ntoh4(data[0]);
464                                 protocolVersion = ntoh4(data[1]);
465                                 if (event.u.net.type != NP_version || major < MAJOR_VERSION)
466                                         fatal("Your opponent is using an old, incompatible version\n"
467                                               "of Netris.  They should get the latest version.");
468                                 if (major > MAJOR_VERSION)
469                                         fatal("Your opponent is using an newer, incompatible version\n"
470                                               "of Netris.  Get the latest version.");
471                                 if (protocolVersion > PROTOCOL_VERSION)
472                                         protocolVersion = PROTOCOL_VERSION;
473                         }
474                         if (protocolVersion < 3 && stepDownInterval != DEFAULT_INTERVAL)
475                                 fatal("Your opponent's version of Netris predates the -i option.\n"
476                                       "For fairness, you shouldn't use the -i option either.");
477                         {
478                                 netint4 data[3];
479                                 int len;
480                                 int seed;
481                                 
482                                 if (protocolVersion >= 3)
483                                         len = sizeof(data);
484                                 else
485                                         len = sizeof(netint4[2]);
486                                 if ((myFlags & SCF_setSeed))
487                                         seed = initSeed;
488                                 else
489                                         seed = time(0);
490                                 if (waitConn)
491                                         SRandom(seed);
492                                 data[0] = hton4(myFlags);
493                                 data[1] = hton4(seed);
494                                 data[2] = hton4(stepDownInterval);
495                                 SendPacket(NP_startConn, len, data);
496                                 if (WaitMyEvent(&event, EM_net) != E_net ||
497                                     event.u.net.type != NP_startConn)
498                                         fatal("Network negotiation failed");
499                                 memcpy(data, event.u.net.data, len);
500                                 opponentFlags = ntoh4(data[0]);
501                                 seed = ntoh4(data[1]);
502                                 if (initConn) {
503                                         if ((opponentFlags & SCF_setSeed) != (myFlags & SCF_setSeed))
504                                                 fatal("If one player sets the random number seed, "
505                                                       "both must.");
506                                         if ((myFlags & SCF_setSeed) && seed != initSeed)
507                                                 fatal("Both players have set the random number seed, "
508                                                       "and they are unequal.");
509                                         if (protocolVersion >= 3 && stepDownInterval != ntoh4(data[2]))
510                                                 fatal("Your opponent is using a different step-down "
511                                                       "interval (-i).\nYou must both use the same one.");
512                                         SRandom(seed);
513                                 }
514                         }
515                         {
516                                 char *userName;
517                                 int len, i;
518
519                                 userName = getenv("LOGNAME");
520                                 if (!userName || !userName[0])
521                                         userName = getenv("USER");
522                                 if (!userName || !userName[0])
523                                         strcpy(userName, "???");
524                                 len = strlen(userName)+1;
525                                 if (len > sizeof(opponentName))
526                                         len = sizeof(opponentName);
527                                 SendPacket(NP_userName, len, userName);
528                                 if (WaitMyEvent(&event, EM_net) != E_net ||
529                                     event.u.net.type != NP_userName)
530                                         fatal("Network negotiation failed");
531                                 strncpy(opponentName, event.u.net.data,
532                                         sizeof(opponentName)-1);
533                                 opponentName[sizeof(opponentName)-1] = 0;
534                                 for (i = 0; opponentName[i]; ++i)
535                                         if (!isprint(opponentName[i]))
536                                                 opponentName[i] = '?';
537                                 for (i = 0; opponentHost[i]; ++i)
538                                         if (!isprint(opponentHost[i]))
539                                                 opponentHost[i] = '?';
540                         }
541                         OneGame(0, 1);
542                 }
543                 else {
544                         game = GT_onePlayer;
545                         OneGame(0, -1);
546                 }
547                 if (wonLast) {
548                         won++;
549                 } else {
550                         lost++;
551                         WaitMyEvent(&event, EM_net);
552                 }
553                 CloseNet();
554                 if (robotEnable) {
555                         CloseRobot();
556                 } else {
557                         gameState = STATE_WAIT_KEYPRESS;
558                         ShowDisplayInfo();
559                         RefreshScreen();
560                         while(getchar() != keyTable[KT_new])
561                                 ;
562                 }
563         }
564
565         return 0;
566 }
567
568 /*
569  * vi: ts=4 ai
570  * vim: noai si
571  */