Source:NetHack 5.0.0/src/topten.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to topten.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/topten.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	topten.c	$NHDT-Date: 1606009004 2020/11/22 01:36:44 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.74 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2012. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "dlb.h"
8. 
9. #if defined(VMS) && !defined(UPDATE_RECORD_IN_PLACE)
10. /* We don't want to rewrite the whole file, because that entails
11.    creating a new version which requires that the old one be deletable.
12.    [Write and Delete are separate permissions on VMS.  'record' should
13.    be writable but not deletable there.]  */
14. #define UPDATE_RECORD_IN_PLACE
15. #endif
16. 
17. /*
18.  * Updating in place can leave junk at the end of the file in some
19.  * circumstances (if it shrinks and the OS doesn't have a straightforward
20.  * way to truncate it).  The trailing junk is harmless and the code
21.  * which reads the scores will ignore it.
22.  */
23. #ifdef UPDATE_RECORD_IN_PLACE
24. static long final_fpos; /* [note: do not move this to the 'g' struct] */
25. #endif
26. 
27. #define done_stopprint program_state.stopprint
28. 
29. #define newttentry() (struct toptenentry *) alloc(sizeof (struct toptenentry))
30. #define dealloc_ttentry(ttent) free((genericptr_t) (ttent))
31. #ifndef NAMSZ
32. /* Changing NAMSZ can break your existing record/logfile */
33. #define NAMSZ 10
34. #endif
35. #define DTHSZ 100
36. #define ROLESZ 3
37. 
38. struct toptenentry {
39.     struct toptenentry *tt_next;
40. #ifdef UPDATE_RECORD_IN_PLACE
41.     long fpos;
42. #endif
43.     long points;
44.     int deathdnum, deathlev;
45.     int maxlvl, hp, maxhp, deaths;
46.     int ver_major, ver_minor, patchlevel;
47.     long deathdate, birthdate;
48.     int uid;
49.     char plrole[ROLESZ + 1];
50.     char plrace[ROLESZ + 1];
51.     char plgend[ROLESZ + 1];
52.     char plalign[ROLESZ + 1];
53.     char name[NAMSZ + 1];
54.     char death[DTHSZ + 1];
55. };
56. static struct toptenentry *tt_head;
57. /* size big enough to read in all the string fields at once; includes
58.    room for separating space or trailing newline plus string terminator */
59. #define SCANBUFSZ (4 * (ROLESZ + 1) + (NAMSZ + 1) + (DTHSZ + 1) + 1)
60. 
61. static struct toptenentry zerott;
62. 
63. staticfn void topten_print(const char *);
64. staticfn void topten_print_bold(const char *);
65. staticfn void outheader(void);
66. staticfn void outentry(int, struct toptenentry *, boolean);
67. staticfn void discardexcess(FILE *);
68. staticfn void readentry(FILE *, struct toptenentry *);
69. staticfn void writeentry(FILE *, struct toptenentry *);
70. #ifdef XLOGFILE
71. staticfn void writexlentry(FILE *, struct toptenentry *, int);
72. staticfn long encodexlogflags(void);
73. staticfn long encodeconduct(void);
74. staticfn long encodeachieve(boolean);
75. staticfn void add_achieveX(char *, const char *, boolean);
76. staticfn char *encode_extended_achievements(char *);
77. staticfn char *encode_extended_conducts(char *);
78. #endif
79. staticfn void free_ttlist(struct toptenentry *);
80. staticfn int classmon(char *);
81. staticfn int score_wanted(boolean, int, struct toptenentry *, int,
82.                         const char **, int);
83. #ifdef NO_SCAN_BRACK
84. staticfn void nsb_mung_line(char *);
85. staticfn void nsb_unmung_line(char *);
86. #endif
87. 
88. /* "killed by",&c ["an"] 'svk.killer.name' */
89. void
90. formatkiller(
91.     char *buf,
92.     unsigned siz,
93.     int how,
94.     boolean incl_helpless)
95. {
96.     static NEARDATA const char *const killed_by_prefix[] = {
97.         /* DIED, CHOKING, POISONING, STARVING, */
98.         "killed by ", "choked on ", "poisoned by ", "died of ",
99.         /* DROWNING, BURNING, DISSOLVED, CRUSHING, */
100.         "drowned in ", "burned by ", "dissolved in ", "crushed to death by ",
101.         /* STONING, TURNED_SLIME, GENOCIDED, */
102.         "petrified by ", "turned to slime by ", "killed by ",
103.         /* PANICKED, TRICKED, QUIT, ESCAPED, ASCENDED */
104.         "", "", "", "", ""
105.     };
106.     unsigned l;
107.     char c, *kname = svk.killer.name;
108. 
109.     buf[0] = '\0'; /* lint suppression */
110.     switch (svk.killer.format) {
111.     default:
112.         impossible("bad killer format? (%d)", svk.killer.format);
113.         FALLTHROUGH;
114.         /*FALLTHRU*/
115.     case NO_KILLER_PREFIX:
116.         break;
117.     case KILLED_BY_AN:
118.         kname = an(kname);
119.         FALLTHROUGH;
120.         /*FALLTHRU*/
121.     case KILLED_BY:
122.         (void) strncat(buf, killed_by_prefix[how], siz - 1);
123.         l = Strlen(buf);
124.         buf += l, siz -= l;
125.         break;
126.     }
127.     /* Copy kname into buf[].
128.      * Object names and named fruit have already been sanitized, but
129.      * monsters can have "called 'arbitrary text'" attached to them,
130.      * so make sure that that text can't confuse field splitting when
131.      * record, logfile, or xlogfile is re-read at some later point.
132.      */
133.     while (--siz > 0) {
134.         c = *kname++;
135.         if (!c)
136.             break;
137.         else if (c == ',')
138.             c = ';';
139.         /* 'xlogfile' doesn't really need protection for '=', but
140.            fixrecord.awk for corrupted 3.6.0 'record' does (only
141.            if using xlogfile rather than logfile to repair record) */
142.         else if (c == '=')
143.             c = '_';
144.         /* tab is not possible due to use of mungspaces() when naming;
145.            it would disrupt xlogfile parsing if it were present */
146.         else if (c == '\t')
147.             c = ' ';
148.         *buf++ = c;
149.     }
150.     *buf = '\0';
151. 
152.     if (incl_helpless && gm.multi < 0) {
153.         /* X <= siz: 'sizeof "string"' includes 1 for '\0' terminator */
154.         if (gm.multi_reason
155.             && strlen(gm.multi_reason) + sizeof ", while " <= siz)
156.             Sprintf(buf, ", while %s", gm.multi_reason);
157.         /* either gm.multi_reason wasn't specified or wouldn't fit */
158.         else if (sizeof ", while helpless" <= siz)
159.             Strcpy(buf, ", while helpless");
160.         /* else extra death info won't fit, so leave it out */
161.     }
162. }
163. 
164. staticfn void
165. topten_print(const char *x)
166. {
167.     if (gt.toptenwin == WIN_ERR)
168.         raw_print(x);
169.     else
170.         putstr(gt.toptenwin, ATR_NONE, x);
171. }
172. 
173. staticfn void
174. topten_print_bold(const char *x)
175. {
176.     if (gt.toptenwin == WIN_ERR)
177.         raw_print_bold(x);
178.     else
179.         putstr(gt.toptenwin, ATR_BOLD, x);
180. }
181. 
182. int
183. observable_depth(d_level *lev)
184. {
185. #if 0
186.     /* if we ever randomize the order of the elemental planes, we
187.        must use a constant external representation in the record file */
188.     if (In_endgame(lev)) {
189.         if (Is_astralevel(lev))
190.             return -5;
191.         else if (Is_waterlevel(lev))
192.             return -4;
193.         else if (Is_firelevel(lev))
194.             return -3;
195.         else if (Is_airlevel(lev))
196.             return -2;
197.         else if (Is_earthlevel(lev))
198.             return -1;
199.         else
200.             return 0; /* ? */
201.     } else
202. #endif
203.     return depth(lev);
204. }
205. 
206. /* throw away characters until current record has been entirely consumed */
207. staticfn void
208. discardexcess(FILE *rfile)
209. {
210.     int c;
211. 
212.     do {
213.         c = fgetc(rfile);
214.     } while (c != '\n' && c != EOF);
215. }
216. 
217. DISABLE_WARNING_FORMAT_NONLITERAL
218. 
219. staticfn void
220. readentry(FILE *rfile, struct toptenentry *tt)
221. {
222.     char inbuf[SCANBUFSZ], s1[SCANBUFSZ], s2[SCANBUFSZ], s3[SCANBUFSZ],
223.          s4[SCANBUFSZ], s5[SCANBUFSZ], s6[SCANBUFSZ];
224. 
225. #ifdef NO_SCAN_BRACK /* Version_ Pts DgnLevs_ Hp___ Died__Born id */
226.     static const char fmt[] = "%d %d %d %ld %d %d %d %d %d %d %ld %ld %d%*c";
227.     static const char fmt32[] = "%c%c %s %s%*c";
228.     static const char fmt33[] = "%s %s %s %s %s %s%*c";
229. #else
230.     static const char fmt[] = "%d.%d.%d %ld %d %d %d %d %d %d %ld %ld %d ";
231.     static const char fmt32[] = "%c%c %[^,],%[^\n]%*c";
232.     static const char fmt33[] = "%s %s %s %s %[^,],%[^\n]%*c";
233. #endif
234. 
235. #ifdef UPDATE_RECORD_IN_PLACE
236.     /* note: input below must read the record's terminating newline */
237.     final_fpos = tt->fpos = ftell(rfile);
238. #endif
239. #define TTFIELDS 13
240.     if (fscanf(rfile, fmt, &tt->ver_major, &tt->ver_minor, &tt->patchlevel,
241.                &tt->points, &tt->deathdnum, &tt->deathlev, &tt->maxlvl,
242.                &tt->hp, &tt->maxhp, &tt->deaths, &tt->deathdate,
243.                &tt->birthdate, &tt->uid) != TTFIELDS) {
244. #undef TTFIELDS
245.         tt->points = 0;
246.         discardexcess(rfile);
247.     } else {
248.         /* load remainder of record into a local buffer;
249.            this imposes an implicit length limit of SCANBUFSZ
250.            on every string field extracted from the buffer */
251.         if (!fgets(inbuf, sizeof inbuf, rfile)) {
252.             /* sscanf will fail and tt->points will be set to 0 */
253.             *inbuf = '\0';
254.         } else if (!strchr(inbuf, '\n')) {
255.             Strcpy(&inbuf[sizeof inbuf - 2], "\n");
256.             discardexcess(rfile);
257.         }
258.         /* Check for backwards compatibility */
259.         if (tt->ver_major < 3 || (tt->ver_major == 3 && tt->ver_minor < 3)) {
260.             int i;
261. 
262.             if (sscanf(inbuf, fmt32, tt->plrole, tt->plgend, s1, s2) == 4) {
263.                 tt->plrole[1] = tt->plgend[1] = '\0'; /* read via %c */
264.                 copynchars(tt->name, s1, (int) (sizeof tt->name) - 1);
265.                 copynchars(tt->death, s2, (int) (sizeof tt->death) - 1);
266.             } else
267.                 tt->points = 0;
268.             tt->plrole[1] = '\0';
269.             if ((i = str2role(tt->plrole)) >= 0)
270.                 Strcpy(tt->plrole, roles[i].filecode);
271.             Strcpy(tt->plrace, "?");
272.             Strcpy(tt->plgend, (tt->plgend[0] == 'M') ? "Mal" : "Fem");
273.             Strcpy(tt->plalign, "?");
274.         } else if (sscanf(inbuf, fmt33, s1, s2, s3, s4, s5, s6) == 6) {
275.             copynchars(tt->plrole, s1, (int) (sizeof tt->plrole) - 1);
276.             copynchars(tt->plrace, s2, (int) (sizeof tt->plrace) - 1);
277.             copynchars(tt->plgend, s3, (int) (sizeof tt->plgend) - 1);
278.             copynchars(tt->plalign, s4, (int) (sizeof tt->plalign) - 1);
279.             copynchars(tt->name, s5, (int) (sizeof tt->name) - 1);
280.             copynchars(tt->death, s6, (int) (sizeof tt->death) - 1);
281.         } else
282.             tt->points = 0;
283. #ifdef NO_SCAN_BRACK
284.         if (tt->points > 0) {
285.             nsb_unmung_line(tt->name);
286.             nsb_unmung_line(tt->death);
287.         }
288. #endif
289.     }
290. 
291.     /* check old score entries for Y2K problem and fix whenever found */
292.     if (tt->points > 0) {
293.         if (tt->birthdate < 19000000L)
294.             tt->birthdate += 19000000L;
295.         if (tt->deathdate < 19000000L)
296.             tt->deathdate += 19000000L;
297.     }
298. }
299. 
300. staticfn void
301. writeentry(FILE *rfile, struct toptenentry *tt)
302. {
303.     static const char fmt32[] = "%c%c ";        /* role,gender */
304.     static const char fmt33[] = "%s %s %s %s "; /* role,race,gndr,algn */
305. #ifndef NO_SCAN_BRACK
306.     static const char fmt0[] = "%d.%d.%d %ld %d %d %d %d %d %d %ld %ld %d ";
307.     static const char fmtX[] = "%s,%s\n";
308. #else /* NO_SCAN_BRACK */
309.     static const char fmt0[] = "%d %d %d %ld %d %d %d %d %d %d %ld %ld %d ";
310.     static const char fmtX[] = "%s %s\n";
311. 
312.     nsb_mung_line(tt->name);
313.     nsb_mung_line(tt->death);
314. #endif
315. 
316.     (void) fprintf(rfile, fmt0, tt->ver_major, tt->ver_minor, tt->patchlevel,
317.                    tt->points, tt->deathdnum, tt->deathlev, tt->maxlvl,
318.                    tt->hp, tt->maxhp, tt->deaths, tt->deathdate,
319.                    tt->birthdate, tt->uid);
320.     if (tt->ver_major < 3 || (tt->ver_major == 3 && tt->ver_minor < 3))
321.         (void) fprintf(rfile, fmt32, tt->plrole[0], tt->plgend[0]);
322.     else
323.         (void) fprintf(rfile, fmt33, tt->plrole, tt->plrace, tt->plgend,
324.                        tt->plalign);
325.     (void) fprintf(rfile, fmtX, onlyspace(tt->name) ? "_" : tt->name,
326.                    tt->death);
327. 
328. #ifdef NO_SCAN_BRACK
329.     nsb_unmung_line(tt->name);
330.     nsb_unmung_line(tt->death);
331. #endif
332. }
333. 
334. RESTORE_WARNING_FORMAT_NONLITERAL
335. 
336. #ifdef XLOGFILE
337. 
338. /* as tab is never used in eg. svp.plname or death, no need to mangle those. */
339. staticfn void
340. writexlentry(FILE *rfile, struct toptenentry *tt, int how)
341. {
342. #define Fprintf (void) fprintf
343. #define XLOG_SEP '\t' /* xlogfile field separator. */
344.     char buf[BUFSZ], tmpbuf[DTHSZ + 1];
345.     char achbuf[N_ACH * 40];
346. 
347.     Sprintf(buf, "version=%d.%d.%d", tt->ver_major, tt->ver_minor,
348.             tt->patchlevel);
349.     Sprintf(eos(buf), "%cpoints=%ld%cdeathdnum=%d%cdeathlev=%d", XLOG_SEP,
350.             tt->points, XLOG_SEP, tt->deathdnum, XLOG_SEP, tt->deathlev);
351.     Sprintf(eos(buf), "%cmaxlvl=%d%chp=%d%cmaxhp=%d", XLOG_SEP, tt->maxlvl,
352.             XLOG_SEP, tt->hp, XLOG_SEP, tt->maxhp);
353.     Sprintf(eos(buf), "%cdeaths=%d%cdeathdate=%ld%cbirthdate=%ld%cuid=%d",
354.             XLOG_SEP, tt->deaths, XLOG_SEP, tt->deathdate, XLOG_SEP,
355.             tt->birthdate, XLOG_SEP, tt->uid);
356.     Fprintf(rfile, "%s", buf);
357.     Sprintf(buf, "%crole=%s%crace=%s%cgender=%s%calign=%s", XLOG_SEP,
358.             tt->plrole, XLOG_SEP, tt->plrace, XLOG_SEP, tt->plgend, XLOG_SEP,
359.             tt->plalign);
360.     /* make a copy of death reason that doesn't include ", while helpless" */
361.     formatkiller(tmpbuf, sizeof tmpbuf, how, FALSE);
362.     Fprintf(rfile, "%s%cname=%s%cdeath=%s",
363.             buf, /* (already includes separator) */
364.             XLOG_SEP, svp.plname, XLOG_SEP, tmpbuf);
365.     if (gm.multi < 0)
366.         Fprintf(rfile, "%cwhile=%s", XLOG_SEP,
367.                 gm.multi_reason ? gm.multi_reason : "helpless");
368.     Fprintf(rfile, "%cconduct=0x%lx%cturns=%ld%cachieve=0x%lx", XLOG_SEP,
369.             encodeconduct(), XLOG_SEP, svm.moves, XLOG_SEP,
370.             encodeachieve(FALSE));
371.     Fprintf(rfile, "%cachieveX=%s", XLOG_SEP,
372.             encode_extended_achievements(achbuf));
373.     Fprintf(rfile, "%cconductX=%s", XLOG_SEP,
374.             encode_extended_conducts(buf)); /* reuse 'buf[]' */
375.     Fprintf(rfile, "%crealtime=%ld%cstarttime=%ld%cendtime=%ld", XLOG_SEP,
376.             urealtime.realtime, XLOG_SEP,
377.             timet_to_seconds(ubirthday), XLOG_SEP,
378.             timet_to_seconds(urealtime.finish_time));
379.     Fprintf(rfile, "%cgender0=%s%calign0=%s", XLOG_SEP,
380.             genders[flags.initgend].filecode, XLOG_SEP,
381.             aligns[1 - u.ualignbase[A_ORIGINAL]].filecode);
382.     Fprintf(rfile, "%cflags=0x%lx", XLOG_SEP, encodexlogflags());
383.     Fprintf(rfile, "%cgold=%ld", XLOG_SEP,
384.             money_cnt(gi.invent) + hidden_gold(TRUE));
385.     Fprintf(rfile, "%cwish_cnt=%ld", XLOG_SEP, u.uconduct.wishes);
386.     Fprintf(rfile, "%carti_wish_cnt=%ld", XLOG_SEP, u.uconduct.wisharti);
387.     Fprintf(rfile, "%cbones=%ld", XLOG_SEP, u.uroleplay.numbones);
388.     Fprintf(rfile, "%crerolls=%ld", XLOG_SEP, u.uroleplay.numrerolls);
389.     Fprintf(rfile, "\n");
390. #undef XLOG_SEP
391. }
392. 
393. staticfn long
394. encodexlogflags(void)
395. {
396.     long e = 0L;
397. 
398.     if (wizard)
399.         e |= 1L << 0;
400.     if (discover)
401.         e |= 1L << 1;
402.     if (!u.uroleplay.numbones)
403.         e |= 1L << 2;
404.     if (u.uroleplay.reroll)
405.         e |= 1L << 3;
406. 
407.     return e;
408. }
409. 
410. staticfn long
411. encodeconduct(void)
412. {
413.     long e = 0L;
414. 
415.     if (!u.uconduct.food)
416.         e |= 1L << 0;
417.     if (!u.uconduct.unvegan)
418.         e |= 1L << 1;
419.     if (!u.uconduct.unvegetarian)
420.         e |= 1L << 2;
421.     if (!u.uconduct.gnostic)
422.         e |= 1L << 3;
423.     if (!u.uconduct.weaphit)
424.         e |= 1L << 4;
425.     if (!u.uconduct.killer)
426.         e |= 1L << 5;
427.     if (!u.uconduct.literate)
428.         e |= 1L << 6;
429.     if (!u.uconduct.polypiles)
430.         e |= 1L << 7;
431.     if (!u.uconduct.polyselfs)
432.         e |= 1L << 8;
433.     if (!u.uconduct.wishes)
434.         e |= 1L << 9;
435.     if (!u.uconduct.wisharti)
436.         e |= 1L << 10;
437.     if (!num_genocides())
438.         e |= 1L << 11;
439.     /* one bit isn't really adequate for sokoban conduct:
440.        reporting "obeyed sokoban rules" is misleading if sokoban wasn't
441.        completed or at least attempted; however, suppressing that when
442.        sokoban was never entered, as we do here, risks reporting
443.        "violated sokoban rules" when no such thing occurred; this can
444.        be disambiguated in xlogfile post-processors by testing the
445.        entered-sokoban bit in the 'achieve' field */
446.     if (!u.uconduct.sokocheat && sokoban_in_play())
447.         e |= 1L << 12;
448.     if (!u.uconduct.pets)
449.         e |= 1L << 13;
450. 
451.     return e;
452. }
453. 
454. staticfn long
455. encodeachieve(
456.     boolean secondlong) /* False: handle achievements 1..31, True: 32..62 */
457. {
458.     int i, achidx, offset;
459.     long r = 0L;
460. 
461.     /*
462.      * 32: portable limit for 'long'.
463.      * Force 32 even on configurations that are using 64 bit longs.
464.      *
465.      * We use signed long and limit ourselves to 31 bits since tools
466.      * that post-process xlogfile might not be able to cope with
467.      * 'unsigned long'.
468.      */
469.     offset = secondlong ? (32 - 1) : 0;
470.     for (i = 0; u.uachieved[i]; ++i) {
471.         achidx = u.uachieved[i] - offset;
472.         if (achidx > 0 && achidx < 32) /* value 1..31 sets bit 0..30 */
473.             r |= 1L << (achidx - 1);
474.     }
475.     return r;
476. }
477. 
478. /* add the achievement or conduct comma-separated to string */
479. staticfn void
480. add_achieveX(char *buf, const char *achievement, boolean condition)
481. {
482.     if (condition) {
483.         if (buf[0] != '\0') {
484.             Strcat(buf, ",");
485.         }
486.         Strcat(buf, achievement);
487.     }
488. }
489. 
490. staticfn char *
491. encode_extended_achievements(char *buf)
492. {
493.     char rnkbuf[40];
494.     const char *achievement = NULL;
495.     int i, achidx, absidx;
496. 
497.     buf[0] = '\0';
498.     for (i = 0; u.uachieved[i]; i++) {
499.         achidx = u.uachieved[i];
500.         absidx = abs(achidx);
501.         switch (absidx) {
502.         case ACH_UWIN:
503.             achievement = "ascended";
504.             break;
505.         case ACH_ASTR:
506.             achievement = "entered_astral_plane";
507.             break;
508.         case ACH_ENDG:
509.             achievement = "entered_elemental_planes";
510.             break;
511.         case ACH_AMUL:
512.             achievement = "obtained_the_amulet_of_yendor";
513.             break;
514.         case ACH_INVK:
515.             achievement = "performed_the_invocation_ritual";
516.             break;
517.         case ACH_BOOK:
518.             achievement = "obtained_the_book_of_the_dead";
519.             break;
520.         case ACH_BELL:
521.             achievement = "obtained_the_bell_of_opening";
522.             break;
523.         case ACH_CNDL:
524.             achievement = "obtained_the_candelabrum_of_invocation";
525.             break;
526.         case ACH_HELL:
527.             achievement = "entered_gehennom";
528.             break;
529.         case ACH_MEDU:
530.             achievement = "defeated_medusa";
531.             break;
532.         case ACH_MINE_PRIZE:
533.             achievement = "obtained_the_luckstone_from_the_mines";
534.             break;
535.         case ACH_SOKO_PRIZE:
536.             achievement = "obtained_the_sokoban_prize";
537.             break;
538.         case ACH_ORCL:
539.             achievement = "consulted_the_oracle";
540.             break;
541.         case ACH_NOVL:
542.             achievement = "read_a_discworld_novel";
543.             break;
544.         case ACH_MINE:
545.             achievement = "entered_the_gnomish_mines";
546.             break;
547.         case ACH_TOWN:
548.             achievement = "entered_mine_town";
549.             break;
550.         case ACH_SHOP:
551.             achievement = "entered_a_shop";
552.             break;
553.         case ACH_TMPL:
554.             achievement = "entered_a_temple";
555.             break;
556.         case ACH_SOKO:
557.             achievement = "entered_sokoban";
558.             break;
559.         case ACH_BGRM:
560.             achievement = "entered_bigroom";
561.             break;
562.         case ACH_TUNE:
563.             achievement = "learned_castle_drawbridge_tune";
564.             break;
565.         /* rank 0 is the starting condition, not an achievement; 8 is Xp 30 */
566.         case ACH_RNK1: case ACH_RNK2: case ACH_RNK3: case ACH_RNK4:
567.         case ACH_RNK5: case ACH_RNK6: case ACH_RNK7: case ACH_RNK8:
568.             Sprintf(rnkbuf, "attained_the_rank_of_%s",
569.                     rank_of(rank_to_xlev(absidx - (ACH_RNK1 - 1)),
570.                             Role_switch, (achidx < 0) ? TRUE : FALSE));
571.             strNsubst(rnkbuf, " ", "_", 0); /* replace every ' ' with '_' */
572.             achievement = lcase(rnkbuf);
573.             break;
574.         default:
575.             continue;
576.         }
577.         add_achieveX(buf, achievement, TRUE);
578.     }
579. 
580.     return buf;
581. }
582. 
583. staticfn char *
584. encode_extended_conducts(char *buf)
585. {
586.     buf[0] = '\0';
587.     add_achieveX(buf, "foodless",     !u.uconduct.food);
588.     add_achieveX(buf, "vegan",        !u.uconduct.unvegan);
589.     add_achieveX(buf, "vegetarian",   !u.uconduct.unvegetarian);
590.     add_achieveX(buf, "atheist",      !u.uconduct.gnostic);
591.     add_achieveX(buf, "weaponless",   !u.uconduct.weaphit);
592.     add_achieveX(buf, "pacifist",     !u.uconduct.killer);
593.     add_achieveX(buf, "illiterate",   !u.uconduct.literate);
594.     add_achieveX(buf, "polyless",     !u.uconduct.polypiles);
595.     add_achieveX(buf, "polyselfless", !u.uconduct.polyselfs);
596.     add_achieveX(buf, "wishless",     !u.uconduct.wishes);
597.     add_achieveX(buf, "artiwishless", !u.uconduct.wisharti);
598.     add_achieveX(buf, "genocideless", !num_genocides());
599.     if (sokoban_in_play())
600.         add_achieveX(buf, "sokoban",  !u.uconduct.sokocheat);
601.     add_achieveX(buf, "blind",        u.uroleplay.blind);
602.     add_achieveX(buf, "deaf",         u.uroleplay.deaf);
603.     add_achieveX(buf, "nudist",       u.uroleplay.nudist);
604.     add_achieveX(buf, "pauper",       u.uroleplay.pauper);
605.     add_achieveX(buf, "bonesless",    !flags.bones);
606.     add_achieveX(buf, "petless",      !u.uconduct.pets);
607.     add_achieveX(buf, "unrerolled",   !u.uroleplay.reroll);
608. 
609.     return buf;
610. }
611. 
612. #endif /* XLOGFILE */
613. 
614. staticfn void
615. free_ttlist(struct toptenentry *tt)
616. {
617.     struct toptenentry *ttnext;
618. 
619.     while (tt->points > 0) {
620.         ttnext = tt->tt_next;
621.         dealloc_ttentry(tt);
622.         tt = ttnext;
623.     }
624.     dealloc_ttentry(tt);
625. }
626. 
627. void
628. topten(int how, time_t when)
629. {
630.     struct toptenentry *t0, *tprev;
631.     struct toptenentry *t1;
632.     FILE *rfile;
633. #ifdef LOGFILE
634.     FILE *lfile;
635. #endif
636. #ifdef XLOGFILE
637.     FILE *xlfile;
638. #endif
639.     int uid = getuid();
640.     int rank, rank0 = -1, rank1 = 0;
641.     int occ_cnt = sysopt.persmax;
642.     int flg = 0;
643.     boolean t0_used, skip_scores;
644. 
645. #ifdef UPDATE_RECORD_IN_PLACE
646.     final_fpos = 0L;
647. #endif
648.     /* If we are in the midst of a panic, cut out topten entirely.
649.      * topten uses alloc() several times, which will lead to
650.      * problems if the panic was the result of an alloc() failure.
651.      */
652.     if (program_state.panicking)
653.         return;
654. 
655.     if (iflags.toptenwin) {
656.         gt.toptenwin = create_nhwindow(NHW_TEXT);
657.     }
658. 
659. #if defined(HANGUPHANDLING)
660. #define HUP if (!program_state.done_hup)
661. #else
662. #define HUP
663. #endif
664. 
665. #ifdef TOS
666.     restore_colors(); /* make sure the screen is black on white */
667. #endif
668.     /* create a new 'topten' entry */
669.     t0_used = FALSE;
670.     t0 = newttentry();
671.     *t0 = zerott;
672.     t0->ver_major = VERSION_MAJOR;
673.     t0->ver_minor = VERSION_MINOR;
674.     t0->patchlevel = PATCHLEVEL;
675.     t0->points = u.urexp;
676.     t0->deathdnum = u.uz.dnum;
677.     /* deepest_lev_reached() is in terms of depth(), and reporting the
678.      * deepest level reached in the dungeon death occurred in doesn't
679.      * seem right, so we have to report the death level in depth() terms
680.      * as well (which also seems reasonable since that's all the player
681.      * sees on the screen anyway)
682.      */
683.     t0->deathlev = observable_depth(&u.uz);
684.     t0->maxlvl = deepest_lev_reached(TRUE);
685.     t0->hp = u.uhp;
686.     t0->maxhp = u.uhpmax;
687.     t0->deaths = u.umortality;
688.     t0->uid = uid;
689.     copynchars(t0->plrole, gu.urole.filecode, ROLESZ);
690.     copynchars(t0->plrace, gu.urace.filecode, ROLESZ);
691.     copynchars(t0->plgend, genders[flags.female].filecode, ROLESZ);
692.     copynchars(t0->plalign, aligns[1 - u.ualign.type].filecode, ROLESZ);
693.     copynchars(t0->name, svp.plname, NAMSZ);
694.     formatkiller(t0->death, sizeof t0->death, how, TRUE);
695.     t0->birthdate = yyyymmdd(ubirthday);
696.     t0->deathdate = yyyymmdd(when);
697.     t0->tt_next = 0;
698. #ifdef UPDATE_RECORD_IN_PLACE
699.     t0->fpos = -1L;
700. #endif
701. 
702. #ifdef LOGFILE /* used for debugging (who dies of what, where) */
703.     if (lock_file(LOGFILE, SCOREPREFIX, 10)) {
704.         if (!(lfile = fopen_datafile(LOGFILE, "a", SCOREPREFIX))) {
705.             HUP raw_print("Cannot open log file!");
706.         } else {
707.             writeentry(lfile, t0);
708.             (void) fclose(lfile);
709.         }
710.         unlock_file(LOGFILE);
711.     }
712. #endif /* LOGFILE */
713. #ifdef XLOGFILE
714.     if (lock_file(XLOGFILE, SCOREPREFIX, 10)) {
715.         if (!(xlfile = fopen_datafile(XLOGFILE, "a", SCOREPREFIX))) {
716.             HUP raw_print("Cannot open extended log file!");
717.         } else {
718.             writexlentry(xlfile, t0, how);
719.             (void) fclose(xlfile);
720.         }
721.         unlock_file(XLOGFILE);
722.     }
723. #endif /* XLOGFILE */
724. 
725.     if (wizard || discover) {
726.         if (how != PANICKED)
727.             HUP {
728.                 char pbuf[BUFSZ];
729. 
730.                 topten_print("");
731.                 Sprintf(pbuf,
732.              "Since you were in %s mode, the score list will not be checked.",
733.                         wizard ? "wizard" : "discover");
734.                 topten_print(pbuf);
735.             }
736.         goto showwin;
737.     }
738. 
739.     if (!lock_file(RECORD, SCOREPREFIX, 60))
740.         goto destroywin;
741. 
742. #ifdef UPDATE_RECORD_IN_PLACE
743.     rfile = fopen_datafile(RECORD, "r+", SCOREPREFIX);
744. #else
745.     rfile = fopen_datafile(RECORD, "r", SCOREPREFIX);
746. #endif
747. 
748.     if (!rfile) {
749.         HUP raw_print("Cannot open record file!");
750.         unlock_file(RECORD);
751.         goto destroywin;
752.     }
753. 
754.     HUP topten_print("");
755. 
756.     /* assure minimum number of points */
757.     if (t0->points < sysopt.pointsmin)
758.         t0->points = 0;
759. 
760.     t1 = tt_head = newttentry();
761.     tprev = 0;
762.     /* rank0: -1 undefined, 0 not_on_list, n n_th on list */
763.     for (rank = 1; ; ) {
764.         readentry(rfile, t1);
765.         if (t1->points < sysopt.pointsmin)
766.             t1->points = 0;
767.         if (rank0 < 0 && t1->points < t0->points) {
768.             rank0 = rank++;
769.             if (tprev == 0)
770.                 tt_head = t0;
771.             else
772.                 tprev->tt_next = t0;
773.             t0->tt_next = t1;
774. #ifdef UPDATE_RECORD_IN_PLACE
775.             t0->fpos = t1->fpos; /* insert here */
776. #endif
777.             t0_used = TRUE;
778.             occ_cnt--;
779.             flg++; /* ask for a rewrite */
780.         } else
781.             tprev = t1;
782. 
783.         if (t1->points == 0)
784.             break;
785.         if ((sysopt.pers_is_uid ? t1->uid == t0->uid
786.                                 : strncmp(t1->name, t0->name, NAMSZ) == 0)
787.             && !strncmp(t1->plrole, t0->plrole, ROLESZ) && --occ_cnt <= 0) {
788.             if (rank0 < 0) {
789.                 rank0 = 0;
790.                 rank1 = rank;
791.                 HUP {
792.                     char pbuf[BUFSZ];
793. 
794.                     Sprintf(pbuf,
795.                          "You didn't beat your previous score of %ld points.",
796.                             t1->points);
797.                     topten_print(pbuf);
798.                     topten_print("");
799.                 }
800.             }
801.             if (occ_cnt < 0) {
802.                 flg++;
803.                 continue;
804.             }
805.         }
806.         if (rank <= sysopt.entrymax) {
807.             t1->tt_next = newttentry();
808.             t1 = t1->tt_next;
809.             rank++;
810.         }
811.         if (rank > sysopt.entrymax) {
812.             t1->points = 0;
813.             break;
814.         }
815.     }
816.     if (flg) { /* rewrite record file */
817. #ifdef UPDATE_RECORD_IN_PLACE
818.         (void) fseek(rfile, (t0->fpos >= 0) ? t0->fpos : final_fpos, SEEK_SET);
819. #else
820.         (void) fclose(rfile);
821.         if (!(rfile = fopen_datafile(RECORD, "w", SCOREPREFIX))) {
822.             HUP raw_print("Cannot write record file");
823.             unlock_file(RECORD);
824.             free_ttlist(tt_head);
825.             goto destroywin;
826.         }
827. #endif /* UPDATE_RECORD_IN_PLACE */
828.         if (!done_stopprint)
829.             if (rank0 > 0) {
830.                 if (rank0 <= 10) {
831.                     topten_print("You made the top ten list!");
832.                 } else {
833.                     char pbuf[BUFSZ];
834. 
835.                     Sprintf(pbuf,
836.                             "You reached the %d%s place on the top %d list.",
837.                             rank0, ordin(rank0), sysopt.entrymax);
838.                     topten_print(pbuf);
839.                 }
840.                 topten_print("");
841.             }
842.     }
843.     skip_scores = !flags.end_top && !flags.end_around && !flags.end_own;
844.     if (rank0 == 0)
845.         rank0 = rank1;
846.     if (rank0 <= 0)
847.         rank0 = rank;
848.     if (!skip_scores && !done_stopprint)
849.         outheader();
850.     for (t1 = tt_head, rank = 1; t1->points != 0; t1 = t1->tt_next, ++rank) {
851.         if (flg
852. #ifdef UPDATE_RECORD_IN_PLACE
853.             && rank >= rank0
854. #endif
855.             )
856.             writeentry(rfile, t1);
857.         if (skip_scores || done_stopprint)
858.             continue;
859.         if (rank <= flags.end_top
860.             || (rank >= rank0 - flags.end_around
861.                 && rank <= rank0 + flags.end_around)
862.             || (flags.end_own && (sysopt.pers_is_uid
863.                                   ? t1->uid == t0->uid
864.                                   : !strncmp(t1->name, t0->name, NAMSZ)))) {
865.             if (rank == rank0 - flags.end_around
866.                 && rank0 > flags.end_top + flags.end_around + 1
867.                 && !flags.end_own)
868.                 topten_print("");
869. 
870.             if (rank != rank0) {
871.                 outentry(rank, t1, FALSE);
872.             } else if (!rank1) {
873.                 outentry(rank, t1, TRUE);
874.             } else {
875.                 outentry(rank, t1, TRUE);
876.                 outentry(0, t0, TRUE);
877.             }
878.         }
879.     }
880.     if (rank0 >= rank)
881.         if (!skip_scores && !done_stopprint)
882.             outentry(0, t0, TRUE);
883. #ifdef UPDATE_RECORD_IN_PLACE
884.     if (flg) {
885. #ifdef TRUNCATE_FILE
886.         /* if a reasonable way to truncate a file exists, use it */
887.         truncate_file(rfile);
888. #else
889.         /* use sentinel record rather than relying on truncation */
890.         *t1 = zerott;
891.         t1->points = 0L; /* [redundant] terminates file when read back in */
892.         t1->plrole[0] = t1->plrace[0] = t1->plgend[0] = t1->plalign[0] = '-';
893.         t1->birthdate = t1->deathdate = yyyymmdd((time_t) 0L);
894.         Strcpy(t1->name, "@");
895.         Strcpy(t1->death, "<eod>\n"); /* end of data */
896.         writeentry(rfile, t1);
897.         /* note: there might be junk (if file has shrunk due to shorter
898.            entries supplanting longer ones) after this dummy entry, but
899.            reading and/or updating will ignore it */
900.         (void) fflush(rfile);
901. #endif /* TRUNCATE_FILE */
902.     }
903. #endif /* UPDATE_RECORD_IN_PLACE */
904.     (void) fclose(rfile);
905.     unlock_file(RECORD);
906.     free_ttlist(tt_head);
907. 
908.  showwin:
909.     if (!done_stopprint) {
910.         if (iflags.toptenwin) {
911.             display_nhwindow(gt.toptenwin, TRUE);
912.         } else {
913.             /* when not a window, we need something comparable to more()
914.                but can't use it directly because we aren't dealing with
915.                the message window */
916.             ;
917.         }
918.     }
919.  destroywin:
920.     if (!t0_used)
921.         dealloc_ttentry(t0);
922.     if (iflags.toptenwin) {
923.         destroy_nhwindow(gt.toptenwin);
924.         gt.toptenwin = WIN_ERR;
925.     }
926. }
927. 
928. staticfn void
929. outheader(void)
930. {
931.     char linebuf[BUFSZ];
932.     char *bp;
933. 
934.     Strcpy(linebuf, " No  Points     Name");
935.     bp = eos(linebuf);
936.     while (bp < linebuf + COLNO - 9)
937.         *bp++ = ' ';
938.     Strcpy(bp, "Hp [max]");
939.     topten_print(linebuf);
940. }
941. 
942. DISABLE_WARNING_FORMAT_NONLITERAL
943. 
944. /* so>0: standout line; so=0: ordinary line */
945. staticfn void
946. outentry(int rank, struct toptenentry *t1, boolean so)
947. {
948.     boolean second_line = TRUE;
949.     char linebuf[BUFSZ];
950.     char *bp, hpbuf[24], linebuf3[BUFSZ];
951.     int hppos, lngr;
952. 
953.     linebuf[0] = '\0';
954.     if (rank)
955.         Sprintf(eos(linebuf), "%3d", rank);
956.     else
957.         Strcat(linebuf, "   ");
958. 
959.     Sprintf(eos(linebuf), " %10ld  %.10s", t1->points ? t1->points : u.urexp,
960.             t1->name);
961.     Sprintf(eos(linebuf), "-%s", t1->plrole);
962.     if (t1->plrace[0] != '?')
963.         Sprintf(eos(linebuf), "-%s", t1->plrace);
964.     /* Printing of gender and alignment is intentional.  It has been
965.      * part of the NetHack Geek Code, and illustrates a proper way to
966.      * specify a character from the command line.
967.      */
968.     Sprintf(eos(linebuf), "-%s", t1->plgend);
969.     if (t1->plalign[0] != '?')
970.         Sprintf(eos(linebuf), "-%s ", t1->plalign);
971.     else
972.         Strcat(linebuf, " ");
973.     if (!strncmp("escaped", t1->death, 7)) {
974.         Sprintf(eos(linebuf), "escaped the dungeon %s[max level %d]",
975.                 !strncmp(" (", t1->death + 7, 2) ? t1->death + 7 + 2 : "",
976.                 t1->maxlvl);
977.         /* fixup for closing paren in "escaped... with...Amulet)[max..." */
978.         if ((bp = strchr(linebuf, ')')) != 0)
979.             *bp = (t1->deathdnum == astral_level.dnum) ? '\0' : ' ';
980.         second_line = FALSE;
981.     } else if (!strncmp("ascended", t1->death, 8)) {
982.         Sprintf(eos(linebuf), "ascended to demigod%s-hood",
983.                 (t1->plgend[0] == 'F') ? "dess" : "");
984.         second_line = FALSE;
985.     } else {
986.         if (!strncmp(t1->death, "quit", 4)) {
987.             Strcat(linebuf, "quit");
988.             second_line = FALSE;
989.         } else if (!strncmp(t1->death, "died of st", 10)) {
990.             Strcat(linebuf, "starved to death");
991.             second_line = FALSE;
992.         } else if (!strncmp(t1->death, "choked", 6)) {
993.             Sprintf(eos(linebuf), "choked on h%s food",
994.                     (t1->plgend[0] == 'F') ? "er" : "is");
995.         } else if (!strncmp(t1->death, "poisoned", 8)) {
996.             Strcat(linebuf, "was poisoned");
997.         } else if (!strncmp(t1->death, "crushed", 7)) {
998.             Strcat(linebuf, "was crushed to death");
999.         } else if (!strncmp(t1->death, "petrified by ", 13)) {
1000.             Strcat(linebuf, "turned to stone");
1001.         } else
1002.             Strcat(linebuf, "died");
1003. 
1004.         if (t1->deathdnum == astral_level.dnum) {
1005.             const char *arg, *fmt = " on the Plane of %s";
1006. 
1007.             switch (t1->deathlev) {
1008.             case -5:
1009.                 fmt = " on the %s Plane";
1010.                 arg = "Astral";
1011.                 break;
1012.             case -4:
1013.                 arg = "Water";
1014.                 break;
1015.             case -3:
1016.                 arg = "Fire";
1017.                 break;
1018.             case -2:
1019.                 arg = "Air";
1020.                 break;
1021.             case -1:
1022.                 arg = "Earth";
1023.                 break;
1024.             default:
1025.                 arg = "Void";
1026.                 break;
1027.             }
1028.             Sprintf(eos(linebuf), fmt, arg);
1029.         } else {
1030.             Sprintf(eos(linebuf), " in %s", svd.dungeons[t1->deathdnum].dname);
1031.             if (t1->deathdnum != knox_level.dnum)
1032.                 Sprintf(eos(linebuf), " on level %d", t1->deathlev);
1033.             if (t1->deathlev != t1->maxlvl)
1034.                 Sprintf(eos(linebuf), " [max %d]", t1->maxlvl);
1035.         }
1036. 
1037.         /* kludge for "quit while already on Charon's boat" */
1038.         if (!strncmp(t1->death, "quit ", 5))
1039.             Strcat(linebuf, t1->death + 4);
1040.     }
1041.     Strcat(linebuf, ".");
1042. 
1043.     /* Quit, starved, ascended, and escaped contain no second line */
1044.     if (second_line) {
1045.         bp = eos(linebuf);
1046.         Sprintf(bp, "  %c%s.", highc(*(t1->death)), t1->death + 1);
1047.         /* fix up "Killed by Mr. Asidonhopo; the shopkeeper"; that starts
1048.            with a comma but has it changed to semi-colon to keep the comma
1049.            out of 'record'; change it back for display */
1050.         (void) strsubst(bp, "; the ", ", the ");
1051.     }
1052. 
1053.     lngr = (int) strlen(linebuf);
1054.     if (t1->hp <= 0)
1055.         hpbuf[0] = '-', hpbuf[1] = '\0';
1056.     else
1057.         Sprintf(hpbuf, "%d", t1->hp);
1058.     /* beginning of hp column after padding (not actually padded yet) */
1059.     hppos = COLNO - (int) (sizeof "  Hp [max]" - sizeof "");
1060.     while (lngr >= hppos) {
1061.         for (bp = eos(linebuf); !(*bp == ' ' && bp - linebuf < hppos); bp--)
1062.             ;
1063.         /* special case: word is too long, wrap in the middle */
1064.         if (linebuf + 15 >= bp)
1065.             bp = linebuf + hppos - 1;
1066.         /* special case: if about to wrap in the middle of maximum
1067.            dungeon depth reached, wrap in front of it instead */
1068.         if (bp > linebuf + 5 && !strncmp(bp - 5, " [max", 5))
1069.             bp -= 5;
1070.         if (*bp != ' ')
1071.             Strcpy(linebuf3, bp);
1072.         else
1073.             Strcpy(linebuf3, bp + 1);
1074.         *bp = '\0';
1075.         if (so) {
1076.             while (bp < linebuf + (COLNO - 1))
1077.                 *bp++ = ' ';
1078.             *bp = '\0';
1079.             topten_print_bold(linebuf);
1080.         } else
1081.             topten_print(linebuf);
1082.         Snprintf(linebuf, sizeof(linebuf), "%15s %s", "", linebuf3);
1083.         lngr = Strlen(linebuf);
1084.     }
1085.     /* beginning of hp column not including padding */
1086.     hppos = COLNO - 7 - (int) strlen(hpbuf);
1087.     bp = eos(linebuf);
1088. 
1089.     if (bp <= linebuf + hppos) {
1090.         /* pad any necessary blanks to the hit point entry */
1091.         while (bp < linebuf + hppos)
1092.             *bp++ = ' ';
1093.         Strcpy(bp, hpbuf);
1094.         Sprintf(eos(bp), " %s[%d]",
1095.                 (t1->maxhp < 10) ? "  " : (t1->maxhp < 100) ? " " : "",
1096.                 t1->maxhp);
1097.     }
1098. 
1099.     if (so) {
1100.         bp = eos(linebuf);
1101.         while (bp < linebuf + (COLNO - 1))
1102.             *bp++ = ' ';
1103.         *bp = '\0';
1104.         topten_print_bold(linebuf);
1105.     } else
1106.         topten_print(linebuf);
1107. }
1108. 
1109. RESTORE_WARNING_FORMAT_NONLITERAL
1110. 
1111. staticfn int
1112. score_wanted(
1113.     boolean current_ver,
1114.     int rank,
1115.     struct toptenentry *t1,
1116.     int playerct,
1117.     const char **players,
1118.     int uid)
1119. {
1120.     const char *arg, *nxt;
1121.     int i;
1122. 
1123.     if (current_ver && (t1->ver_major != VERSION_MAJOR
1124.                         || t1->ver_minor != VERSION_MINOR
1125.                         || t1->patchlevel != PATCHLEVEL))
1126.         return 0;
1127. 
1128.     if (sysopt.pers_is_uid && !playerct && t1->uid == uid)
1129.         return 1;
1130. 
1131.     /*
1132.      * FIXME:
1133.      *  This selection produces a union (OR) of criteria rather than
1134.      *  an intersection (AND).  So
1135.      *    nethack -s -u igor -p Cav -r Hum
1136.      *  will list all entries for name igor regardless of role or race
1137.      *  plus all entries for cave dwellers regardless of name or race
1138.      *  plus all entries for humans regardless of name or role.
1139.      *
1140.      *  It would be more useful if it only chose human cave dwellers
1141.      *  named igor.  That would be pretty straightforward if only one
1142.      *  instance of each of the criteria were possible, but
1143.      *    nethack -s -u igor -u ayn -p Cav -p Pri -r Hum -r Dwa
1144.      *  should list human cave dwellers named igor and human cave
1145.      *  dwellers named ayn plus dwarven cave dwellers named igor and
1146.      *  dwarven cave dwellers named ayn plus human priest[esse]s named
1147.      *  igor and human priest[esse]s named ayn (the combination of
1148.      *  dwarven priest[esse]s doesn't occur but the selection can test
1149.      *  entries without being aware of such; it just won't find any
1150.      *  matches for that).  An extra initial pass of the command line
1151.      *  to collect all criteria before testing any entry is needed to
1152.      *  accomplish this.  And we might need to drop support for
1153.      *  pre-3.3.0 entries (old elf role) depending on how the criteria
1154.      *  matching is performed.
1155.      *
1156.      *  It also ought to extended to handle
1157.      *    nethack -s -u igor-Cav-Hum
1158.      *  Alignment and gender could be useful too but no one has ever
1159.      *  clamored for them.  Presumably if they care they postprocess
1160.      *  with some custom tool.
1161.      */
1162. 
1163.     for (i = 0; i < playerct; i++) {
1164.         arg = players[i];
1165.         if (arg[0] == '-' && arg[1] == 'u' && arg[2] != '\0')
1166.             arg += 2; /* handle '-uname' */
1167. 
1168.         if (arg[0] == '-' && strchr("pru", arg[1]) && !arg[2]
1169.             && i + 1 < playerct) {
1170.             nxt = players[i + 1];
1171.             if ((arg[1] == 'p' && str2role(nxt) == str2role(t1->plrole))
1172.                 || (arg[1] == 'r' && str2race(nxt) == str2race(t1->plrace))
1173.                 /* handle '-u name' */
1174.                 || (arg[1] == 'u' && (!strcmp(nxt, "all")
1175.                                       || !strncmp(t1->name, nxt, NAMSZ))))
1176.                 return 1;
1177.             i++;
1178.         } else if (!strcmp(arg, "all")
1179.                    || !strncmp(t1->name, arg, NAMSZ)
1180.                    || (arg[0] == '-' && arg[1] == t1->plrole[0] && !arg[2])
1181.                    || (digit(arg[0]) && rank <= atoi(arg)))
1182.             return 1;
1183.     }
1184.     return 0;
1185. }
1186. 
1187. /*
1188.  * print selected parts of score list.
1189.  * argc >= 2, with argv[0] untrustworthy (directory names, et al.),
1190.  * and argv[1] starting with "-s".
1191.  * caveat: some shells might allow argv elements to be arbitrarily long.
1192.  */
1193. void
1194. prscore(int argc, char **argv)
1195. {
1196.     const char **players, *player0;
1197.     int i, playerct, rank;
1198.     struct toptenentry *t1;
1199.     FILE *rfile;
1200.     char pbuf[BUFSZ], *p;
1201.     unsigned ln;
1202.     int uid = -1;
1203.     boolean current_ver = TRUE, init_done = FALSE, match_found = FALSE;
1204. 
1205.     /* expect "-s" or "--scores"; "-s<anything> is accepted */
1206.     ln = (argc < 2) ? 0U
1207.          : ((p = strchr(argv[1], ' ')) != 0) ? (unsigned) (p - argv[1])
1208.            : Strlen(argv[1]);
1209.     if (ln < 2 || (strncmp(argv[1], "-s", 2)
1210.                    && strcmp(argv[1], "--scores"))) {
1211.         raw_printf("prscore: bad arguments (%d)", argc);
1212.         return;
1213.     }
1214. 
1215.     rfile = fopen_datafile(RECORD, "r", SCOREPREFIX);
1216.     if (!rfile) {
1217.         raw_print("Cannot open record file!");
1218.         return;
1219.     }
1220. 
1221. #ifdef AMIGA
1222.     {
1223.         extern winid amii_rawprwin;
1224. 
1225.         init_nhwindows(&argc, argv);
1226.         amii_rawprwin = create_nhwindow(NHW_TEXT);
1227.     }
1228. #endif
1229. 
1230.     /* If the score list isn't after a game, we never went through
1231.      * initialization. */
1232.     if (wiz1_level.dlevel == 0) {
1233.         dlb_init();
1234.         init_dungeons();
1235.         init_done = TRUE;
1236.     }
1237. 
1238.     /* to get here, argv[1] either starts with "-s" or is "--scores" without
1239.        trailing stuff; for "-s<anything>" treat <anything> as separate arg */
1240.     if (argv[1][1] == '-' || !argv[1][2]) {
1241.         argc--;
1242.         argv++;
1243.     } else { /* concatenated arg string; use up "-s" but keep argc,argv */
1244.         argv[1] += 2;
1245.     }
1246.     /* -v doesn't take a version number arg; it means 'all versions present
1247.        in the file' instead of the default of only the current version;
1248.        unlike -s, we don't accept "-v<anything>" for non-empty <anything> */
1249.     if (argc > 1 && !strcmp(argv[1], "-v")) {
1250.         current_ver = FALSE;
1251.         argc--;
1252.         argv++;
1253.     }
1254. 
1255.     if (argc <= 1) {
1256.         if (sysopt.pers_is_uid) {
1257.             uid = getuid();
1258.             playerct = 0;
1259.             players = (const char **) 0;
1260.         } else {
1261.             player0 = svp.plname;
1262.             if (!*player0)
1263.                 player0 = "all"; /* if no plname[], show all scores
1264.                                   * (possibly filtered by '-v') */
1265.             playerct = 1;
1266.             players = &player0;
1267.         }
1268.     } else {
1269.         playerct = --argc;
1270.         players = (const char **) ++argv;
1271.     }
1272.     raw_print("");
1273. 
1274.     t1 = tt_head = newttentry();
1275.     for (rank = 1; ; rank++) {
1276.         readentry(rfile, t1);
1277.         if (t1->points == 0)
1278.             break;
1279.         if (!match_found
1280.             && score_wanted(current_ver, rank, t1, playerct, players, uid))
1281.             match_found = TRUE;
1282.         t1->tt_next = newttentry();
1283.         t1 = t1->tt_next;
1284.     }
1285. 
1286.     (void) fclose(rfile);
1287.     if (init_done) {
1288.         free_dungeons();
1289.         dlb_cleanup();
1290.     }
1291. 
1292.     if (match_found) {
1293.         outheader();
1294.         t1 = tt_head;
1295.         for (rank = 1; t1->points != 0; rank++, t1 = t1->tt_next) {
1296.             if (score_wanted(current_ver, rank, t1, playerct, players, uid))
1297.                 (void) outentry(rank, t1, FALSE);
1298.         }
1299.     } else {
1300.         Sprintf(pbuf, "Cannot find any %sentries for ",
1301.                 current_ver ? "current " : "");
1302.         if (playerct < 1) {
1303.             Strcat(pbuf, "you");
1304.         } else {
1305.             /* minor bug: 'nethack -s -u ziggy' will say "any of"
1306.                even though the '-u' doesn't indicate multiple names */
1307.             if (playerct > 1)
1308.                 Strcat(pbuf, "any of ");
1309.             for (i = 0; i < playerct; i++) {
1310.                 /* accept '-u name' and '-uname' as well as just 'name'
1311.                    so skip '-u' for the none-found feedback */
1312.                 if (!strncmp(players[i], "-u", 2)) {
1313.                     if (!players[i][2])
1314.                         continue;
1315.                     players[i] += 2;
1316.                 }
1317.                 /* stop printing players if there are too many to fit */
1318.                 if (strlen(pbuf) + strlen(players[i]) + 2 >= BUFSZ) {
1319.                     if (strlen(pbuf) < BUFSZ - 4)
1320.                         Strcat(pbuf, "...");
1321.                     else
1322.                         Strcpy(pbuf + strlen(pbuf) - 4, "...");
1323.                     break;
1324.                 }
1325.                 Strcat(pbuf, players[i]);
1326.                 if (i < playerct - 1) {
1327.                     if (players[i][0] == '-' && strchr("pr", players[i][1])
1328.                         && players[i][2] == 0)
1329.                         Strcat(pbuf, " ");
1330.                     else
1331.                         Strcat(pbuf, ":");
1332.                 }
1333.             }
1334.         }
1335.         /* append end-of-sentence punctuation if there is room */
1336.         if (strlen(pbuf) < BUFSZ - 1)
1337.             Strcat(pbuf, ".");
1338.         raw_print(pbuf);
1339.         raw_printf("Usage: %s -s [-v] <playertypes> [maxrank] [playernames]",
1340.                    gh.hname);
1341.         raw_printf("Player types are: [-p role] [-r race]");
1342.     }
1343.     free_ttlist(tt_head);
1344. #ifdef AMIGA
1345.     {
1346.         extern winid amii_rawprwin;
1347. 
1348.         display_nhwindow(amii_rawprwin, 1);
1349.         destroy_nhwindow(amii_rawprwin);
1350.         amii_rawprwin = WIN_ERR;
1351.     }
1352. #endif
1353. }
1354. 
1355. staticfn int
1356. classmon(char *plch)
1357. {
1358.     int i;
1359. 
1360.     /* Look for this role in the role table */
1361.     for (i = 0; roles[i].name.m; i++) {
1362.         if (!strncmp(plch, roles[i].filecode, ROLESZ)) {
1363.             if (roles[i].mnum != NON_PM)
1364.                 return roles[i].mnum;
1365.             else
1366.                 return PM_HUMAN;
1367.         }
1368.     }
1369.     /* this might be from a 3.2.x score for former Elf class */
1370.     if (!strcmp(plch, "E"))
1371.         return PM_RANGER;
1372. 
1373.     impossible("What weird role is this? (%s)", plch);
1374.     return  PM_HUMAN_MUMMY;
1375. }
1376. 
1377. /*
1378.  * Get a random player name and class from the high score list,
1379.  */
1380. struct toptenentry *
1381. get_rnd_toptenentry(void)
1382. {
1383.     int rank, i;
1384.     FILE *rfile;
1385.     struct toptenentry *tt;
1386.     static struct toptenentry tt_buf;
1387. 
1388.     rfile = fopen_datafile(RECORD, "r", SCOREPREFIX);
1389.     if (!rfile) {
1390.         impossible("Cannot open record file!");
1391.         return NULL;
1392.     }
1393. 
1394.     tt = &tt_buf;
1395.     rank = rnd(sysopt.tt_oname_maxrank);
1396.  pickentry:
1397.     for (i = rank; i; i--) {
1398.         readentry(rfile, tt);
1399.         if (tt->points == 0)
1400.             break;
1401.     }
1402. 
1403.     if (tt->points == 0) {
1404.         if (rank > 1) {
1405.             rank = 1;
1406.             rewind(rfile);
1407.             goto pickentry;
1408.         }
1409.         tt = NULL;
1410.     }
1411. 
1412.     (void) fclose(rfile);
1413.     return tt;
1414. }
1415. 
1416. 
1417. /*
1418.  * Attach random player name and class from high score list
1419.  * to an object (for statues or morgue corpses).
1420.  */
1421. struct obj *
1422. tt_oname(struct obj *otmp)
1423. {
1424.     struct toptenentry *tt;
1425.     if (!otmp)
1426.         return (struct obj *) 0;
1427. 
1428.     tt = get_rnd_toptenentry();
1429. 
1430.     if (!tt)
1431.         return (struct obj *) 0;
1432. 
1433.     set_corpsenm(otmp, classmon(tt->plrole));
1434.     if (tt->plgend[0] == 'F')
1435.         otmp->spe = CORPSTAT_FEMALE;
1436.     else if (tt->plgend[0] == 'M')
1437.         otmp->spe = CORPSTAT_MALE;
1438.     otmp = oname(otmp, tt->name, ONAME_NO_FLAGS);
1439. 
1440.     return otmp;
1441. }
1442. 
1443. /* Randomly select a topten entry to mimic */
1444. int
1445. tt_doppel(struct monst *mon) {
1446.     struct toptenentry *tt = rn2(13) ? get_rnd_toptenentry() : NULL;
1447.     int ret;
1448. 
1449.     if (!tt)
1450.         ret = rn1(PM_WIZARD - PM_ARCHEOLOGIST + 1, PM_ARCHEOLOGIST);
1451.     else {
1452.         if (tt->plgend[0] == 'F')
1453.             mon->female = 1;
1454.         else if (tt->plgend[0] == 'M')
1455.             mon->female = 0;
1456.         ret = classmon(tt->plrole);
1457.         /* Only take on a name if the player can see
1458.            the doppelganger, otherwise we end up with
1459.            named monsters spoiling the fun - Kes */
1460.         if (canseemon(mon))
1461.             christen_monst(mon, tt->name);
1462.     }
1463.     return ret;
1464. }
1465. 
1466. #ifdef NO_SCAN_BRACK
1467. /* Lattice scanf isn't up to reading the scorefile.  What */
1468. /* follows deals with that; I admit it's ugly. (KL) */
1469. /* Now generally available (KL) */
1470. staticfn void
1471. nsb_mung_line(p)
1472. char *p;
1473. {
1474.     while ((p = strchr(p, ' ')) != 0)
1475.         *p = '|';
1476. }
1477. 
1478. staticfn void
1479. nsb_unmung_line(p)
1480. char *p;
1481. {
1482.     while ((p = strchr(p, '|')) != 0)
1483.         *p = ' ';
1484. }
1485. #endif /* NO_SCAN_BRACK */
1486. 
1487. /*topten.c*/