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