xref: /netbsd-src/games/tetris/scores.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
1 /*-
2  * Copyright (c) 1992, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek and Darren F. Provine.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)scores.c	8.1 (Berkeley) 5/31/93
37  */
38 
39 /*
40  * Score code for Tetris, by Darren Provine (kilroy@gboro.glassboro.edu)
41  * modified 22 January 1992, to limit the number of entries any one
42  * person has.
43  *
44  * Major whacks since then.
45  */
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <time.h>
53 #include <unistd.h>
54 
55 /*
56  * XXX - need a <termcap.h>
57  */
58 int	tputs __P((const char *, int, int (*)(int)));
59 
60 #include "pathnames.h"
61 #include "screen.h"
62 #include "scores.h"
63 #include "tetris.h"
64 
65 /*
66  * Within this code, we can hang onto one extra "high score", leaving
67  * room for our current score (whether or not it is high).
68  *
69  * We also sometimes keep tabs on the "highest" score on each level.
70  * As long as the scores are kept sorted, this is simply the first one at
71  * that level.
72  */
73 #define NUMSPOTS (MAXHISCORES + 1)
74 #define	NLEVELS (MAXLEVEL + 1)
75 
76 static time_t now;
77 static int nscores;
78 static int gotscores;
79 static struct highscore scores[NUMSPOTS];
80 
81 static int checkscores __P((struct highscore *, int));
82 static int cmpscores __P((const void *, const void *));
83 static void getscores __P((FILE **));
84 static void printem __P((int, int, struct highscore *, int, const char *));
85 static char *thisuser __P((void));
86 
87 /*
88  * Read the score file.  Can be called from savescore (before showscores)
89  * or showscores (if savescore will not be called).  If the given pointer
90  * is not NULL, sets *fpp to an open file pointer that corresponds to a
91  * read/write score file that is locked with LOCK_EX.  Otherwise, the
92  * file is locked with LOCK_SH for the read and closed before return.
93  *
94  * Note, we assume closing the stdio file releases the lock.
95  */
96 static void
97 getscores(fpp)
98 	FILE **fpp;
99 {
100 	int sd, mint, lck;
101 	char *mstr, *human;
102 	FILE *sf;
103 
104 	if (fpp != NULL) {
105 		mint = O_RDWR | O_CREAT;
106 		mstr = "r+";
107 		human = "read/write";
108 		lck = LOCK_EX;
109 	} else {
110 		mint = O_RDONLY;
111 		mstr = "r";
112 		human = "reading";
113 		lck = LOCK_SH;
114 	}
115 	sd = open(_PATH_SCOREFILE, mint, 0666);
116 	if (sd < 0) {
117 		if (fpp == NULL) {
118 			nscores = 0;
119 			return;
120 		}
121 		(void)fprintf(stderr, "tetris: cannot open %s for %s: %s\n",
122 		    _PATH_SCOREFILE, human, strerror(errno));
123 		exit(1);
124 	}
125 	if ((sf = fdopen(sd, mstr)) == NULL) {
126 		(void)fprintf(stderr, "tetris: cannot fdopen %s for %s: %s\n",
127 		    _PATH_SCOREFILE, human, strerror(errno));
128 		exit(1);
129 	}
130 
131 	/*
132 	 * Grab a lock.
133 	 */
134 	if (flock(sd, lck))
135 		(void)fprintf(stderr,
136 		    "tetris: warning: score file %s cannot be locked: %s\n",
137 		    _PATH_SCOREFILE, strerror(errno));
138 
139 	nscores = fread(scores, sizeof(scores[0]), MAXHISCORES, sf);
140 	if (ferror(sf)) {
141 		(void)fprintf(stderr, "tetris: error reading %s: %s\n",
142 		    _PATH_SCOREFILE, strerror(errno));
143 		exit(1);
144 	}
145 
146 	if (fpp)
147 		*fpp = sf;
148 	else
149 		(void)fclose(sf);
150 }
151 
152 void
153 savescore(level)
154 	int level;
155 {
156 	register struct highscore *sp;
157 	register int i;
158 	int change;
159 	FILE *sf;
160 	const char *me;
161 
162 	getscores(&sf);
163 	gotscores = 1;
164 	(void)time(&now);
165 
166 	/*
167 	 * Allow at most one score per person per level -- see if we
168 	 * can replace an existing score, or (easiest) do nothing.
169 	 * Otherwise add new score at end (there is always room).
170 	 */
171 	change = 0;
172 	me = thisuser();
173 	for (i = 0, sp = &scores[0]; i < nscores; i++, sp++) {
174 		if (sp->hs_level != level || strcmp(sp->hs_name, me) != 0)
175 			continue;
176 		if (score > sp->hs_score) {
177 			(void)printf("%s bettered %s %d score of %d!\n",
178 			    "\nYou", "your old level", level,
179 			    sp->hs_score * sp->hs_level);
180 			sp->hs_score = score;	/* new score */
181 			sp->hs_time = now;	/* and time */
182 			change = 1;
183 		} else if (score == sp->hs_score) {
184 			(void)printf("%s tied %s %d high score.\n",
185 			    "\nYou", "your old level", level);
186 			sp->hs_time = now;	/* renew it */
187 			change = 1;		/* gotta rewrite, sigh */
188 		} /* else new score < old score: do nothing */
189 		break;
190 	}
191 	if (i >= nscores) {
192 		strcpy(sp->hs_name, me);
193 		sp->hs_level = level;
194 		sp->hs_score = score;
195 		sp->hs_time = now;
196 		nscores++;
197 		change = 1;
198 	}
199 
200 	if (change) {
201 		/*
202 		 * Sort & clean the scores, then rewrite.
203 		 */
204 		nscores = checkscores(scores, nscores);
205 		rewind(sf);
206 		if (fwrite(scores, sizeof(*sp), nscores, sf) != nscores ||
207 		    fflush(sf) == EOF)
208 			(void)fprintf(stderr,
209 			    "tetris: error writing %s: %s -- %s\n",
210 			    _PATH_SCOREFILE, strerror(errno),
211 			    "high scores may be damaged");
212 	}
213 	(void)fclose(sf);	/* releases lock */
214 }
215 
216 /*
217  * Get login name, or if that fails, get something suitable.
218  * The result is always trimmed to fit in a score.
219  */
220 static char *
221 thisuser()
222 {
223 	register const char *p;
224 	register struct passwd *pw;
225 	register size_t l;
226 	static char u[sizeof(scores[0].hs_name)];
227 
228 	if (u[0])
229 		return (u);
230 	p = getlogin();
231 	if (p == NULL || *p == '\0') {
232 		pw = getpwuid(getuid());
233 		if (pw != NULL)
234 			p = pw->pw_name;
235 		else
236 			p = "  ???";
237 	}
238 	l = strlen(p);
239 	if (l >= sizeof(u))
240 		l = sizeof(u) - 1;
241 	bcopy(p, u, l);
242 	u[l] = '\0';
243 	return (u);
244 }
245 
246 /*
247  * Score comparison function for qsort.
248  *
249  * If two scores are equal, the person who had the score first is
250  * listed first in the highscore file.
251  */
252 static int
253 cmpscores(x, y)
254 	const void *x, *y;
255 {
256 	register const struct highscore *a, *b;
257 	register long l;
258 
259 	a = x;
260 	b = y;
261 	l = (long)b->hs_level * b->hs_score - (long)a->hs_level * a->hs_score;
262 	if (l < 0)
263 		return (-1);
264 	if (l > 0)
265 		return (1);
266 	if (a->hs_time < b->hs_time)
267 		return (-1);
268 	if (a->hs_time > b->hs_time)
269 		return (1);
270 	return (0);
271 }
272 
273 /*
274  * If we've added a score to the file, we need to check the file and ensure
275  * that this player has only a few entries.  The number of entries is
276  * controlled by MAXSCORES, and is to ensure that the highscore file is not
277  * monopolised by just a few people.  People who no longer have accounts are
278  * only allowed the highest score.  Scores older than EXPIRATION seconds are
279  * removed, unless they are someone's personal best.
280  * Caveat:  the highest score on each level is always kept.
281  */
282 static int
283 checkscores(hs, num)
284 	register struct highscore *hs;
285 	int num;
286 {
287 	register struct highscore *sp;
288 	register int i, j, k, numnames;
289 	int levelfound[NLEVELS];
290 	struct peruser {
291 		char *name;
292 		int times;
293 	} count[NUMSPOTS];
294 	register struct peruser *pu;
295 
296 	/*
297 	 * Sort so that highest totals come first.
298 	 *
299 	 * levelfound[i] becomes set when the first high score for that
300 	 * level is encountered.  By definition this is the highest score.
301 	 */
302 	qsort((void *)hs, nscores, sizeof(*hs), cmpscores);
303 	for (i = MINLEVEL; i < NLEVELS; i++)
304 		levelfound[i] = 0;
305 	numnames = 0;
306 	for (i = 0, sp = hs; i < num;) {
307 		/*
308 		 * This is O(n^2), but do you think we care?
309 		 */
310 		for (j = 0, pu = count; j < numnames; j++, pu++)
311 			if (strcmp(sp->hs_name, pu->name) == 0)
312 				break;
313 		if (j == numnames) {
314 			/*
315 			 * Add new user, set per-user count to 1.
316 			 */
317 			pu->name = sp->hs_name;
318 			pu->times = 1;
319 			numnames++;
320 		} else {
321 			/*
322 			 * Two ways to keep this score:
323 			 * - Not too many (per user), still has acct, &
324 			 *	score not dated; or
325 			 * - High score on this level.
326 			 */
327 			if ((pu->times < MAXSCORES &&
328 			     getpwnam(sp->hs_name) != NULL &&
329 			     sp->hs_time + EXPIRATION >= now) ||
330 			    levelfound[sp->hs_level] == 0)
331 				pu->times++;
332 			else {
333 				/*
334 				 * Delete this score, do not count it,
335 				 * do not pass go, do not collect $200.
336 				 */
337 				num--;
338 				for (k = i; k < num; k++)
339 					hs[k] = hs[k + 1];
340 				continue;
341 			}
342 		}
343 		levelfound[sp->hs_level] = 1;
344 		i++, sp++;
345 	}
346 	return (num > MAXHISCORES ? MAXHISCORES : num);
347 }
348 
349 /*
350  * Show current scores.  This must be called after savescore, if
351  * savescore is called at all, for two reasons:
352  * - Showscores munches the time field.
353  * - Even if that were not the case, a new score must be recorded
354  *   before it can be shown anyway.
355  */
356 void
357 showscores(level)
358 	int level;
359 {
360 	register struct highscore *sp;
361 	register int i, n, c;
362 	const char *me;
363 	int levelfound[NLEVELS];
364 
365 	if (!gotscores)
366 		getscores((FILE **)NULL);
367 	(void)printf("\n\t\t\t    Tetris High Scores\n");
368 
369 	/*
370 	 * If level == 0, the person has not played a game but just asked for
371 	 * the high scores; we do not need to check for printing in highlight
372 	 * mode.  If SOstr is null, we can't do highlighting anyway.
373 	 */
374 	me = level && SOstr ? thisuser() : NULL;
375 
376 	/*
377 	 * Set times to 0 except for high score on each level.
378 	 */
379 	for (i = MINLEVEL; i < NLEVELS; i++)
380 		levelfound[i] = 0;
381 	for (i = 0, sp = scores; i < nscores; i++, sp++) {
382 		if (levelfound[sp->hs_level])
383 			sp->hs_time = 0;
384 		else {
385 			sp->hs_time = 1;
386 			levelfound[sp->hs_level] = 1;
387 		}
388 	}
389 
390 	/*
391 	 * Page each screenful of scores.
392 	 */
393 	for (i = 0, sp = scores; i < nscores; sp += n) {
394 		n = 40;
395 		if (i + n > nscores)
396 			n = nscores - i;
397 		printem(level, i + 1, sp, n, me);
398 		if ((i += n) < nscores) {
399 			(void)printf("\nHit RETURN to continue.");
400 			(void)fflush(stdout);
401 			while ((c = getchar()) != '\n')
402 				if (c == EOF)
403 					break;
404 			(void)printf("\n");
405 		}
406 	}
407 }
408 
409 static void
410 printem(level, offset, hs, n, me)
411 	int level, offset;
412 	register struct highscore *hs;
413 	register int n;
414 	const char *me;
415 {
416 	register struct highscore *sp;
417 	int nrows, row, col, item, i, highlight;
418 	char buf[100];
419 #define	TITLE "Rank  Score   Name     (points/level)"
420 
421 	/*
422 	 * This makes a nice two-column sort with headers, but it's a bit
423 	 * convoluted...
424 	 */
425 	printf("%s   %s\n", TITLE, n > 1 ? TITLE : "");
426 
427 	highlight = 0;
428 	nrows = (n + 1) / 2;
429 
430 	for (row = 0; row < nrows; row++) {
431 		for (col = 0; col < 2; col++) {
432 			item = col * nrows + row;
433 			if (item >= n) {
434 				/*
435 				 * Can only occur on trailing columns.
436 				 */
437 				(void)putchar('\n');
438 				continue;
439 			}
440 			(void)printf(item + offset < 10 ? "  " : " ");
441 			sp = &hs[item];
442 			(void)sprintf(buf,
443 			    "%d%c %6d  %-11s (%d on %d)",
444 			    item + offset, sp->hs_time ? '*' : ' ',
445 			    sp->hs_score * sp->hs_level,
446 			    sp->hs_name, sp->hs_score, sp->hs_level);
447 			/*
448 			 * Highlight if appropriate.  This works because
449 			 * we only get one score per level.
450 			 */
451 			if (me != NULL &&
452 			    sp->hs_level == level &&
453 			    sp->hs_score == score &&
454 			    strcmp(sp->hs_name, me) == 0) {
455 				putpad(SOstr);
456 				highlight = 1;
457 			}
458 			(void)printf("%s", buf);
459 			if (highlight) {
460 				putpad(SEstr);
461 				highlight = 0;
462 			}
463 
464 			/* fill in spaces so column 1 lines up */
465 			if (col == 0)
466 				for (i = 40 - strlen(buf); --i >= 0;)
467 					(void)putchar(' ');
468 			else /* col == 1 */
469 				(void)putchar('\n');
470 		}
471 	}
472 }
473