scores.c 12 KB

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