xref: /netbsd-src/games/worms/worms.c (revision 061aa945dd2d53589e251d0bbec99a5bdf6828eb)
1 /*	$NetBSD: worms.c,v 1.31 2023/05/12 13:29:41 kre Exp $	*/
2 
3 /*
4  * Copyright (c) 1980, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)worms.c	8.1 (Berkeley) 5/31/93";
41 #else
42 __RCSID("$NetBSD: worms.c,v 1.31 2023/05/12 13:29:41 kre Exp $");
43 #endif
44 #endif /* not lint */
45 
46 /*
47  *
48  *	 @@@        @@@    @@@@@@@@@@     @@@@@@@@@@@    @@@@@@@@@@@@
49  *	 @@@        @@@   @@@@@@@@@@@@    @@@@@@@@@@@@   @@@@@@@@@@@@@
50  *	 @@@        @@@  @@@@      @@@@   @@@@           @@@@ @@@  @@@@
51  *	 @@@   @@   @@@  @@@        @@@   @@@            @@@  @@@   @@@
52  *	 @@@  @@@@  @@@  @@@        @@@   @@@            @@@  @@@   @@@
53  *	 @@@@ @@@@ @@@@  @@@        @@@   @@@            @@@  @@@   @@@
54  *	  @@@@@@@@@@@@   @@@@      @@@@   @@@            @@@  @@@   @@@
55  *	   @@@@  @@@@     @@@@@@@@@@@@    @@@            @@@  @@@   @@@
56  *	    @@    @@       @@@@@@@@@@     @@@            @@@  @@@   @@@
57  *
58  *				 Eric P. Scott
59  *			  Caltech High Energy Physics
60  *				 October, 1980
61  *
62  */
63 #include <sys/types.h>
64 
65 #include <ctype.h>
66 #include <curses.h>
67 #include <err.h>
68 #include <limits.h>
69 #include <signal.h>
70 #include <stdbool.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <strings.h>
74 #include <term.h>
75 #include <unistd.h>
76 
77 static const struct options {
78 	int nopts;
79 	int opts[3];
80 }
81 	normal[8] = {
82 	{ 3, { 7, 0, 1 } },
83 	{ 3, { 0, 1, 2 } },
84 	{ 3, { 1, 2, 3 } },
85 	{ 3, { 2, 3, 4 } },
86 	{ 3, { 3, 4, 5 } },
87 	{ 3, { 4, 5, 6 } },
88 	{ 3, { 5, 6, 7 } },
89 	{ 3, { 6, 7, 0 } }
90 },
91 	upper[8] = {
92 	{ 1, { 1, 0, 0 } },
93 	{ 2, { 1, 2, 0 } },
94 	{ 0, { 0, 0, 0 } },
95 	{ 0, { 0, 0, 0 } },
96 	{ 0, { 0, 0, 0 } },
97 	{ 2, { 4, 5, 0 } },
98 	{ 1, { 5, 0, 0 } },
99 	{ 2, { 1, 5, 0 } }
100 },
101 	left[8] = {
102 	{ 0, { 0, 0, 0 } },
103 	{ 0, { 0, 0, 0 } },
104 	{ 0, { 0, 0, 0 } },
105 	{ 2, { 2, 3, 0 } },
106 	{ 1, { 3, 0, 0 } },
107 	{ 2, { 3, 7, 0 } },
108 	{ 1, { 7, 0, 0 } },
109 	{ 2, { 7, 0, 0 } }
110 },
111 	right[8] = {
112 	{ 1, { 7, 0, 0 } },
113 	{ 2, { 3, 7, 0 } },
114 	{ 1, { 3, 0, 0 } },
115 	{ 2, { 3, 4, 0 } },
116 	{ 0, { 0, 0, 0 } },
117 	{ 0, { 0, 0, 0 } },
118 	{ 0, { 0, 0, 0 } },
119 	{ 2, { 6, 7, 0 } }
120 },
121 	lower[8] = {
122 	{ 0, { 0, 0, 0 } },
123 	{ 2, { 0, 1, 0 } },
124 	{ 1, { 1, 0, 0 } },
125 	{ 2, { 1, 5, 0 } },
126 	{ 1, { 5, 0, 0 } },
127 	{ 2, { 5, 6, 0 } },
128 	{ 0, { 0, 0, 0 } },
129 	{ 0, { 0, 0, 0 } }
130 },
131 	upleft[8] = {
132 	{ 0, { 0, 0, 0 } },
133 	{ 0, { 0, 0, 0 } },
134 	{ 0, { 0, 0, 0 } },
135 	{ 0, { 0, 0, 0 } },
136 	{ 0, { 0, 0, 0 } },
137 	{ 1, { 3, 0, 0 } },
138 	{ 2, { 1, 3, 0 } },
139 	{ 1, { 1, 0, 0 } }
140 },
141 	upright[8] = {
142 	{ 2, { 3, 5, 0 } },
143 	{ 1, { 3, 0, 0 } },
144 	{ 0, { 0, 0, 0 } },
145 	{ 0, { 0, 0, 0 } },
146 	{ 0, { 0, 0, 0 } },
147 	{ 0, { 0, 0, 0 } },
148 	{ 0, { 0, 0, 0 } },
149 	{ 1, { 5, 0, 0 } }
150 },
151 	lowleft[8] = {
152 	{ 3, { 7, 0, 1 } },
153 	{ 0, { 0, 0, 0 } },
154 	{ 0, { 0, 0, 0 } },
155 	{ 1, { 1, 0, 0 } },
156 	{ 2, { 1, 7, 0 } },
157 	{ 1, { 7, 0, 0 } },
158 	{ 0, { 0, 0, 0 } },
159 	{ 0, { 0, 0, 0 } }
160 },
161 	lowright[8] = {
162 	{ 0, { 0, 0, 0 } },
163 	{ 1, { 7, 0, 0 } },
164 	{ 2, { 5, 7, 0 } },
165 	{ 1, { 5, 0, 0 } },
166 	{ 0, { 0, 0, 0 } },
167 	{ 0, { 0, 0, 0 } },
168 	{ 0, { 0, 0, 0 } },
169 	{ 0, { 0, 0, 0 } }
170 };
171 static const char	flavor[] = {
172 	'O', '*', '#', '$', '%', '0', 'o', '~',
173 	'+', 'x', ':', '^', '_', '&', '@', 'w'
174 };
175 static const int flavors = __arraycount(flavor);
176 static const char	eyeball[] = {
177 	'0', 'X', '@', 'S', 'X', '@', 'O', '=',
178 	'#', '*', '=', 'v', 'L', '@', 'o', 'm'
179 };
180 __CTASSERT(sizeof(flavor) == sizeof(eyeball));
181 
182 static const short	xinc[] = {
183 	1,  1,  1,  0, -1, -1, -1,  0
184 }, yinc[] = {
185 	-1,  0,  1,  1,  1,  0, -1, -1
186 };
187 static struct	worm {
188 	int orientation, head, len;
189 	short *xpos, *ypos;
190 	chtype ch, eye, attr;
191 } *worm;
192 
193 static volatile sig_atomic_t sig_caught;
194 
195 static int initclr(int**);
196 static void nomem(void) __dead;
197 static void onsig(int);
198 static int worm_length(int, int);
199 
200 int
main(int argc,char * argv[])201 main(int argc, char *argv[])
202 {
203 	int CO, LI, last, bottom, ch, number, trail;
204 	int x, y, h, n, nc;
205 	int maxlength, minlength;
206 	unsigned int seed, delay;
207 	const struct options *op;
208 	struct worm *w;
209 	short **ref;
210 	short *ip;
211 	const char *field;
212 	char *ep;
213 	unsigned long ul, up;
214 	bool argerror = false;
215 	bool docolour = false;		/* -C, use coloured worms */
216 	bool docaput = false;		/* -H, show which end of worm is head */
217 	int *ctab = NULL;
218 
219 	delay = 20000;
220 	maxlength = minlength = 16;
221 	number = 3;
222 	seed = 0;
223 	trail = ' ';
224 	field = NULL;
225 
226 	if ((ep = getenv("WORMS")) != NULL) {
227 		ul = up = 0;
228 		while ((ch = *ep++) != '\0') {
229 			switch (ch) {
230 			case 'C':
231 				docolour = !docolour;
232 				continue;
233 			case 'f':
234 				if (field)
235 					field = NULL;
236 				else
237 					field = "WORM";
238 				continue;
239 			case 'H':
240 				docaput = !docaput;
241 				continue;
242 			case 'r':
243 				minlength = 5;
244 				maxlength = 0;
245 				continue;
246 			case 't':
247 				if (trail == ' ')
248 					trail = '.';
249 				else
250 					trail = ' ';
251 				continue;
252 			case '0': case '1': case '2': case '3': case '4':
253 			case '5': case '6': case '7': case '8': case '9':
254 				if (up > 1)
255 					continue;
256 				if (ul >= 100000)	/* 1/10 second, in us */
257 					continue;
258 				ul *= 10;
259 				ul += (ch - '0');
260 				up = 1;
261 				continue;
262 			case 'm':
263 				if (up == 1 && ul <= 1000)
264 					ul *= 1000;
265 				up += 2;
266 				continue;
267 			default:
268 				continue;
269 			}
270 		}
271 		if ((up & 1) != 0)	/* up == 1 || up == 3 */
272 			delay = ul;
273 	}
274 
275 	while ((ch = getopt(argc, argv, "Cd:fHl:n:rS:t")) != -1) {
276 		switch(ch) {
277 		case 'C':
278 			docolour = !docolour;
279 			continue;
280 		case 'd':
281 			ul = strtoul(optarg, &ep, 10);
282 			if (ep != optarg) {
283 				while (isspace(*(unsigned char *)ep))
284 					ep++;
285 			}
286 			if (ep == optarg ||
287 			    (*ep != '\0' &&
288 				( ep[1] == '\0' ? (*ep != 'm' && *ep != 'u') :
289 				( strcasecmp(ep, "ms") != 0 &&
290 				  strcasecmp(ep, "us") != 0 )) )) {
291 				    errx(1, "-d: invalid delay (%s)", optarg);
292 			}
293 			/*
294 			 * if ul >= INT_MAX/1000 we don't need the *1000,
295 			 * as even without that it will exceed the limit
296 			 * just below and be treated as an error.
297 			 * (This does assume >=32 bit int, but so does POSIX)
298 			 */
299 			if (*ep != 'u' && ul < INT_MAX / 1000)
300 				ul *= 1000;  /* ms -> us */
301 			if (ul > 1000*1000) {
302 				errx(1,
303 				   "-d: delay (%s) out of range [0 - 1000]",
304 				   optarg);
305 			}
306 			delay = (unsigned int)ul;
307 			continue;
308 		case 'f':
309 			if (field == NULL)
310 				field = "WORM";
311 			else
312 				field = NULL;
313 			continue;
314 		case 'H':
315 			docaput = !docaput;
316 			continue;
317 		case 'l':
318 			up = ul = strtoul(optarg, &ep, 10);
319 			if (ep != optarg) {
320 				while (isspace(*(unsigned char *)ep))
321 					ep++;
322 				if (*ep == '-')
323 					up = strtoul(++ep, &ep, 10);
324 			}
325 			if (ep == optarg || *ep != '\0' ||
326 			    ul < 2 || up < ul || up > 1024) {
327 				errx(1, "-l: invalid length (%s) [%d - %d].",
328 				     optarg, 2, 1024);
329 			}
330 			minlength = (int)ul;
331 			maxlength = (int)up;
332 			continue;
333 		case 'n':
334 			ul = strtoul(optarg, &ep, 10);
335 			if (ep == optarg || *ep != '\0' ||
336 			    ul < 1 || ul > INT_MAX / 10 ) {
337 				errx(1, "-n: invalid number of worms (%s).",
338 				    optarg);
339 			}
340 			/* upper bound is further limited later */
341 			number = (int)ul;
342 			continue;
343 		case 'r':
344 			minlength = 5;
345 			maxlength = 0;
346 			continue;
347 		case 'S':
348 			ul = strtoul(optarg, &ep, 0);
349 			if (ep == optarg || *ep != '\0' ||
350 			    ul > UINT_MAX ) {
351 				errx(1, "-S: invalid seed (%s).", optarg);
352 			}
353 			seed = (unsigned int)ul;
354 			continue;
355 		case 't':
356 			if (trail == ' ')
357 				trail = '.';
358 			else
359 				trail = ' ';
360 			continue;
361 		case '?':
362 		default:
363 			argerror = true;
364 			break;
365 		}
366 		break;
367 	}
368 
369 	if (argerror || argc > optind)
370 		errx(1,
371 		    "Usage: worms [-CfHrt] [-d delay] [-l length] [-n number]");
372 		/* -S omitted deliberately, not useful often enough */
373 
374 	if (!initscr())
375 		errx(1, "couldn't initialize screen");
376 	curs_set(0);
377 	nc = docolour ? initclr(&ctab) : 0;
378 	CO = COLS;
379 	LI = LINES;
380 
381 	if (CO == 0 || LI == 0) {
382 		endwin();
383 		errx(1, "screen must be a rectangle, not (%dx%d)", CO, LI);
384 	}
385 
386 	/*
387 	 * The "sizeof(short *)" noise is to abslutely guarantee
388 	 * that a LI * CO * sizeof(short *) cannot overflow an int
389 	 */
390 	if (CO >= (int)(INT_MAX / (2 * sizeof(short *)) / LI)) {
391 		endwin();
392 		errx(1, "screen (%dx%d) too large for worms", CO, LI);
393 	}
394 
395 	/* now known that LI*CO cannot overflow an int => also not a long */
396 
397 	if (LI < 3 || CO < 3 || LI * CO < 40) {
398 		/*
399 		 * The placement algorithm is too weak for dimensions < 3.
400 		 * Need at least 40 spaces so we can have (n > 1) worms
401 		 * of a reasonable length, and still leave empty space.
402 		 */
403 		endwin();
404 		errx(1, "screen (%dx%d) too small for worms", CO, LI);
405 	}
406 
407 	if (maxlength == 0)
408 		maxlength = minlength + (CO * LI / 40);
409 
410 	ul = (unsigned long)CO * LI;
411 	if ((unsigned long)maxlength > ul / 20) {
412 		endwin();
413 		errx(1, "-l: worms too long (%d) for screen; max: %lu",
414 		    maxlength, ul / 20);
415 	}
416 
417 	ul /= maxlength * 3;	/* no more than 33% arena occupancy */
418 
419 	if ((unsigned long)(unsigned)number > ul && maxlength > minlength) {
420 		maxlength = CO * LI / 3 / number;
421 		if (maxlength < minlength)
422 			maxlength = minlength;
423 		ul = (CO * LI) / ((minlength + maxlength)/2 * 3);;
424 	}
425 
426 	if ((unsigned long)(unsigned)number > ul) {
427 		endwin();
428 		errx(1, "-n: too many worms (%d) max: %lu", number, ul);
429 	}
430 	if (!(worm = calloc((size_t)number, sizeof(struct worm))))
431 		nomem();
432 
433 	srandom(seed ? seed : arc4random());
434 
435 	last = CO - 1;
436 	bottom = LI - 1;
437 
438 	if (!(ip = calloc(LI * CO, sizeof(short))))
439 		nomem();
440 	if (!(ref = malloc((size_t)LI * sizeof(short *))))
441 		nomem();
442 	for (n = 0; n < LI; ++n) {
443 		ref[n] = ip;
444 		ip += CO;
445 	}
446 
447 	for (n = number, w = &worm[0]; --n >= 0; w++) {
448 		int i;
449 
450 		w->orientation = w->head = 0;
451 		w->len = worm_length(minlength, maxlength);
452 		w->attr = nc ? ctab[n % nc] : 0;
453 		i = (nc && number > flavors ? n / nc : n) % flavors;
454 		w->ch = flavor[i];
455 		w->eye = eyeball[i];
456 
457 		if (!(ip = malloc((size_t)(w->len * sizeof(short)))))
458 			nomem();
459 		w->xpos = ip;
460 		for (x = w->len; --x >= 0;)
461 			*ip++ = -1;
462 		if (!(ip = malloc((size_t)(w->len * sizeof(short)))))
463 			nomem();
464 		w->ypos = ip;
465 		for (y = w->len; --y >= 0;)
466 			*ip++ = -1;
467 	}
468 	free(ctab);		/* not needed any more */
469 
470 	(void)signal(SIGHUP, onsig);
471 	(void)signal(SIGINT, onsig);
472 	(void)signal(SIGQUIT, onsig);
473 	(void)signal(SIGTERM, onsig);
474 	(void)signal(SIGTSTP, onsig);
475 	(void)signal(SIGWINCH, onsig);
476 
477 	if (field) {
478 		const char *p = field;
479 
480 		for (y = LI; --y >= 0;) {
481 			for (x = CO; --x >= 0;) {
482 				addch(*p++);
483 				if (!*p)
484 					p = field;
485 			}
486 		}
487 	}
488 
489 	for (;;) {
490 		refresh();
491 		if (sig_caught) {
492 			endwin();
493 			exit(0);
494 		}
495 		if (delay) {
496 			if (delay % 1000000 != 0)
497 				usleep(delay % 1000000);
498 			if (delay >= 1000000)
499 				sleep(delay / 1000000);
500 		}
501 		for (n = 0, w = &worm[0]; n < number; n++, w++) {
502 			chtype c = docaput ? w->eye : w->ch;
503 
504 			if ((x = w->xpos[h = w->head]) < 0) {
505 				mvaddch(y = w->ypos[h] = bottom,
506 					x = w->xpos[h] = 0, c | w->attr);
507 				ref[y][x]++;
508 			} else
509 				y = w->ypos[h];
510 			if (++h == w->len)
511 				h = 0;
512 			if (w->xpos[w->head = h] >= 0) {
513 				int x1, y1;
514 
515 				x1 = w->xpos[h];
516 				y1 = w->ypos[h];
517 				if (--ref[y1][x1] == 0)
518 					mvaddch(y1, x1, trail);
519 			}
520 
521 			op = &(!x
522 				? (!y
523 				    ? upleft
524 				    : (y == bottom ? lowleft : left))
525 				: (x == last
526 				    ? (!y ? upright
527 					  : (y == bottom ? lowright : right))
528 				    : (!y ? upper
529 					  : (y == bottom ? lower : normal)))
530 			      )[w->orientation];
531 
532 			switch (op->nopts) {
533 			case 0:
534 				endwin();
535 				abort();
536 				/* NOTREACHED */
537 			case 1:
538 				w->orientation = op->opts[0];
539 				break;
540 			default:
541 				w->orientation =
542 				    op->opts[(int)random() % op->nopts];
543 			}
544 			mvaddch(y += yinc[w->orientation],
545 				x += xinc[w->orientation],
546 				c | w->attr);
547 			ref[w->ypos[h] = y][w->xpos[h] = x]++;
548 			if (docaput && w->len > 1) {
549 				int prev = (h ? h : w->len) - 1;
550 
551 				mvaddch(w->ypos[prev], w->xpos[prev],
552 					w->ch | w->attr);
553 			}
554 		}
555 	}
556 }
557 
558 static int
initclr(int ** ctab)559 initclr(int** ctab)
560 {
561 	int *ip, clr[] = {
562 		COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
563 		COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
564 	}, attr[] = {
565 		A_NORMAL, A_BOLD, A_DIM
566 	};
567 	int nattr = __arraycount(attr);
568 	int nclr = __arraycount(clr);
569 	int nc = 0;
570 
571 	/* terminfo first */
572 	char* s;
573 	bool canbold = (s = tigetstr("bold")) != (char* )-1 && s != NULL;
574 	bool candim  = (s = tigetstr("dim")) != (char* )-1 && s != NULL;
575 
576 #ifdef DO_TERMCAP
577 	/* termcap if terminfo fails */
578 	canbold = canbold || (s = tgetstr("md", NULL)) != NULL;
579 	candim  = candim  || (s = tgetstr("mh", NULL)) != NULL;
580 #endif
581 
582 	if (has_colors() == FALSE)
583 		return 0;
584 	use_default_colors();
585 	if (start_color() == ERR)
586 		return 0;
587 	if ((*ctab = calloc(COLOR_PAIRS, sizeof(int))) == NULL)
588 		nomem();
589 	ip = *ctab;
590 
591 	for (int i = 0; i < nattr; i++) {
592 		if (!canbold && attr[i] == A_BOLD)
593 			continue;
594 		if (!candim && attr[i] == A_DIM)
595 			continue;
596 
597 		for (int j = 0; j < nclr; j++) {
598 			if (clr[j] == COLOR_BLACK && attr[i] != A_BOLD)
599 				continue;	/* invisible */
600 			if (nc + 1 >= COLOR_PAIRS)
601 				break;
602 			if (init_pair(nc + 1, clr[j], -1) == ERR)
603 				break;
604 			*ip++ = COLOR_PAIR(nc + 1) | attr[i];
605 			nc++;
606 		}
607 	}
608 
609 	return nc;
610 }
611 
612 static int
worm_length(int low,int high)613 worm_length(int low, int high)
614 {
615 	if (low >= high)
616 		return low;
617 
618 	return low + (random() % (high - low + 1));
619 }
620 
621 static void
onsig(int signo __unused)622 onsig(int signo __unused)
623 {
624 	sig_caught = 1;
625 }
626 
627 /* This is never called before curses is initialised */
628 static void
nomem(void)629 nomem(void)
630 {
631 	endwin();
632 	errx(1, "not enough memory.");
633 }
634