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