xref: /netbsd-src/games/tetris/tetris.c (revision d92552c3ea104e1b0b9116663d6c92428934d388)
1 /*	$NetBSD: tetris.c,v 1.34 2023/07/01 10:51:35 nia Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Torek and Darren F. Provine.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)tetris.c	8.1 (Berkeley) 5/31/93
35  */
36 
37 #include <sys/cdefs.h>
38 #ifndef lint
39 __COPYRIGHT("@(#) Copyright (c) 1992, 1993\
40  The Regents of the University of California.  All rights reserved.");
41 #endif /* not lint */
42 
43 /*
44  * Tetris (or however it is spelled).
45  */
46 
47 #include <sys/time.h>
48 
49 #include <err.h>
50 #include <fcntl.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include "input.h"
58 #include "scores.h"
59 #include "screen.h"
60 #include "tetris.h"
61 
62 cell	board[B_SIZE];		/* 1 => occupied, 0 => empty */
63 
64 int	Rows, Cols;		/* current screen size */
65 int	Offset;			/* used to center board & shapes */
66 
67 static const struct shape *curshape;
68 const struct shape *nextshape;
69 
70 long	fallrate;		/* less than 1 million; smaller => faster */
71 
72 int	score;			/* the obvious thing */
73 gid_t	gid, egid;
74 
75 char	key_msg[100];
76 int	showpreview;
77 int	nocolor;
78 
79 static void elide(void);
80 static void setup_board(void);
81 static void onintr(int) __dead;
82 static void usage(void) __dead;
83 
84 /*
85  * Set up the initial board.  The bottom display row is completely set,
86  * along with another (hidden) row underneath that.  Also, the left and
87  * right edges are set.
88  */
89 static void
setup_board(void)90 setup_board(void)
91 {
92 	int i;
93 	cell *p;
94 
95 	p = board;
96 	for (i = B_SIZE; i; i--)
97 		*p++ = (i <= (2 * B_COLS) || (i % B_COLS) < 2) ? 7 : 0;
98 }
99 
100 /*
101  * Elide any full active rows.
102  */
103 static void
elide(void)104 elide(void)
105 {
106 	int i, j, base;
107 	cell *p;
108 
109 	for (i = A_FIRST; i < A_LAST; i++) {
110 		base = i * B_COLS + 1;
111 		p = &board[base];
112 		for (j = B_COLS - 2; *p++ != 0;) {
113 			if (--j <= 0) {
114 				/* this row is to be elided */
115 				memset(&board[base], 0, B_COLS - 2);
116 				scr_update();
117 				tsleep();
118 				while (--base != 0)
119 					board[base + B_COLS] = board[base];
120 				/* don't forget to clear 0th row */
121 				memset(&board[1], 0, B_COLS - 2);
122 				scr_update();
123 				tsleep();
124 				break;
125 			}
126 		}
127 	}
128 }
129 
130 int
main(int argc,char * argv[])131 main(int argc, char *argv[])
132 {
133 	int pos, c;
134 	const char *keys;
135 	int level = 2;
136 #define NUMKEYS 7
137 	char key_write[NUMKEYS][10];
138 	char *nocolor_env;
139 	int ch, i, j;
140 	int fd;
141 
142 	gid = getgid();
143 	egid = getegid();
144 	setegid(gid);
145 
146 	fd = open("/dev/null", O_RDONLY);
147 	if (fd < 3)
148 		exit(1);
149 	close(fd);
150 
151 	keys = "jkl pqn";
152 
153 	while ((ch = getopt(argc, argv, "bk:l:ps")) != -1)
154 		switch(ch) {
155 		case 'b':
156 			nocolor = 1;
157 			break;
158 		case 'k':
159 			if (strlen(keys = optarg) != NUMKEYS)
160 				usage();
161 			break;
162 		case 'l':
163 			level = atoi(optarg);
164 			if (level < MINLEVEL || level > MAXLEVEL) {
165 				errx(1, "level must be from %d to %d",
166 				     MINLEVEL, MAXLEVEL);
167 			}
168 			break;
169 		case 'p':
170 			showpreview = 1;
171 			break;
172 		case 's':
173 			showscores(0);
174 			exit(0);
175 		case '?':
176 		default:
177 			usage();
178 		}
179 
180 	argc -= optind;
181 	argv += optind;
182 
183 	if (argc)
184 		usage();
185 
186 	nocolor_env = getenv("NO_COLOR");
187 
188 	if (nocolor_env != NULL && nocolor_env[0] != '\0')
189 		nocolor = 1;
190 
191 	fallrate = 1000000 / level;
192 
193 	for (i = 0; i <= (NUMKEYS-1); i++) {
194 		for (j = i+1; j <= (NUMKEYS-1); j++) {
195 			if (keys[i] == keys[j]) {
196 				errx(1, "duplicate command keys specified.");
197 			}
198 		}
199 		if (keys[i] == ' ')
200 			strcpy(key_write[i], "<space>");
201 		else {
202 			key_write[i][0] = keys[i];
203 			key_write[i][1] = '\0';
204 		}
205 	}
206 
207 	snprintf(key_msg, sizeof(key_msg),
208 "%s - left  %s - rotate  %s - right  %s - drop  %s - pause  %s - quit  %s - down",
209 		key_write[0], key_write[1], key_write[2], key_write[3],
210 		key_write[4], key_write[5], key_write[6]);
211 
212 	(void)signal(SIGINT, onintr);
213 	scr_init();
214 	setup_board();
215 
216 	scr_set();
217 
218 	pos = A_FIRST*B_COLS + (B_COLS/2)-1;
219 	nextshape = randshape();
220 	curshape = randshape();
221 
222 	scr_msg(key_msg, 1);
223 
224 	for (;;) {
225 		place(curshape, pos, 1);
226 		scr_update();
227 		place(curshape, pos, 0);
228 		c = tgetchar();
229 		if (c < 0) {
230 			/*
231 			 * Timeout.  Move down if possible.
232 			 */
233 			if (fits_in(curshape, pos + B_COLS)) {
234 				pos += B_COLS;
235 				continue;
236 			}
237 
238 			/*
239 			 * Put up the current shape `permanently',
240 			 * bump score, and elide any full rows.
241 			 */
242 			place(curshape, pos, 1);
243 			score++;
244 			elide();
245 
246 			/*
247 			 * Choose a new shape.  If it does not fit,
248 			 * the game is over.
249 			 */
250 			curshape = nextshape;
251 			nextshape = randshape();
252 			pos = A_FIRST*B_COLS + (B_COLS/2)-1;
253 			if (!fits_in(curshape, pos))
254 				break;
255 			continue;
256 		}
257 
258 		/*
259 		 * Handle command keys.
260 		 */
261 		if (c == keys[5]) {
262 			/* quit */
263 			break;
264 		}
265 		if (c == keys[4]) {
266 			static char msg[] =
267 			    "paused - press RETURN to continue";
268 
269 			place(curshape, pos, 1);
270 			do {
271 				scr_update();
272 				scr_msg(key_msg, 0);
273 				scr_msg(msg, 1);
274 				(void) fflush(stdout);
275 			} while (rwait(NULL) == -1);
276 			scr_msg(msg, 0);
277 			scr_msg(key_msg, 1);
278 			place(curshape, pos, 0);
279 			continue;
280 		}
281 		if (c == keys[0]) {
282 			/* move left */
283 			if (fits_in(curshape, pos - 1))
284 				pos--;
285 			continue;
286 		}
287 		if (c == keys[1]) {
288 			/* turn */
289 			const struct shape *new = &shapes[curshape->rot];
290 
291 			if (fits_in(new, pos))
292 				curshape = new;
293 			continue;
294 		}
295 		if (c == keys[2]) {
296 			/* move right */
297 			if (fits_in(curshape, pos + 1))
298 				pos++;
299 			continue;
300 		}
301 		if (c == keys[3]) {
302 			/* move to bottom */
303 			while (fits_in(curshape, pos + B_COLS)) {
304 				pos += B_COLS;
305 				score++;
306 			}
307 			continue;
308 		}
309 		if (c == keys[6]) {
310 			/* move down */
311 			if (fits_in(curshape, pos + B_COLS)) {
312 				pos += B_COLS;
313 				score++;
314 			}
315 			continue;
316 		}
317 		if (c == '\f') {
318 			scr_clear();
319 			scr_msg(key_msg, 1);
320 		}
321 	}
322 
323 	scr_clear();
324 	scr_end();
325 
326 	(void)printf("Your score:  %d point%s  x  level %d  =  %d\n",
327 	    score, score == 1 ? "" : "s", level, score * level);
328 	savescore(level);
329 
330 	printf("\nHit RETURN to see high scores, ^C to skip.\n");
331 
332 	while ((i = getchar()) != '\n')
333 		if (i == EOF)
334 			break;
335 
336 	showscores(level);
337 
338 	exit(0);
339 }
340 
341 static void
onintr(int signo __unused)342 onintr(int signo __unused)
343 {
344 	scr_clear();
345 	scr_end();
346 	exit(0);
347 }
348 
349 static void
usage(void)350 usage(void)
351 {
352 	(void)fprintf(stderr, "usage: %s [-bps] [-k keys] [-l level]\n",
353 	    getprogname());
354 	exit(1);
355 }
356