1 /*
2  *	@(#) hiscore.c -- hiscore system for TROJKA
3  *	created:	4.iii.1992
4  *	modified: 	13.iii.1992
5  */
6 
7 #include "sys_custom.h"
8 #include "hiscore.h"
9 #include "trojka.h"
10 
11 #include <stdio.h>
12 #include <fcntl.h>
13 
14 int 	gameover(),
15 	shiftscores(),
16 	readscores(),
17 	writescores(),
18 	scorelist();
19 
20 extern struct scorefile *sfile;
21 
22 extern unsigned long
23 	score,
24 	wipes,
25 	blocks;		/* trojka */
26 
27 extern int
28 	speed;
29 
30 extern int  position;
31 
gameover()32 int gameover()
33 {
34 	struct scorefile *i, *a, *eof;
35 
36 	showscore();
37 
38 	showgameover();
39 
40 	eof = &sfile[NUMSCORES];
41 	position = NUMSCORES+1; /* initially no position in hiscore table */
42 	a = &sfile[0];
43 	while (a < eof) {
44 		if (score > a->points) {
45 			position = (a-sfile)+1;
46 			break;
47 		}
48 		a++;
49 	}
50 	/* open up score list */
51 
52 	eof--;
53 	i = eof;
54 	while(eof > a)
55 		*(i--) = *(--eof);
56 
57 	if (position < NUMSCORES) {		/* YOU ARE IN THE LIST */
58 		a->points = score;
59 		a->stage  = speed;
60 		while(getname(a->name)==0)	/* empty name not allowed */
61 			;
62 		writescores();		/* write scores to disk */
63 	}
64 }
65 
readscores()66 int readscores()
67 {
68 	int fd, old_umask;
69 	struct scorefile *eof, *i;
70 
71 	eof = &sfile[NUMSCORES];
72 
73 	for(i = sfile; i < eof; i++) {	/* Assume default scores */
74 		strcpy(i->name, STDNAME);
75 		i->points = 333;
76 		i->stage = STDLEVEL;
77 	}
78 	fd = open(SCOREFILE, O_RDONLY);
79 	if(fd == -1) {		/* if there's no highscore file -> create one */
80 		old_umask = umask(0);
81 		fd = creat(SCOREFILE, UMASK);
82 		umask(old_umask);
83 		if(fd == -1)
84 			quit_prog("Error creating scorefile");
85 		close(fd);
86 		writescores();	/* write the default scores */
87 		if((fd = open(SCOREFILE, O_RDWR)) == -1)
88 			quit_prog("Error opening scorefile");
89 	}
90 	if(read(fd,sfile, FILE_SIZE) == -1)
91 		quit_prog("Error reading scorefile");
92 	close(fd);
93 }
94 
writescores()95 int writescores()
96 {
97 	int fd;
98 
99 	sfile = &sfile[0];
100 	if((fd = open(SCOREFILE, O_WRONLY)) == -1)
101 		quit_prog("Error opening scorefile.");
102 
103 	if((write(fd, sfile, FILE_SIZE)) == -1)
104 		quit_prog("Score-file write error.");
105 
106 	if((close(fd)) == -1)
107 		quit_prog("Error closing scorefile.");
108 }
109 
110 
scorelist()111 int scorelist()
112 {		/* used for the -s option */
113 	struct scorefile *eof, *i;
114 
115 	readscores();
116 	eof = &sfile[NUMSCORES-1];
117 
118 	fprintf(stderr,"\nBest Trojka-Czars\n-----------------\n\n");
119 
120 	for(i=sfile; i<eof; i++)
121 		fprintf(stderr,"%-22s %7lu %3d\n",
122 			i->name,
123 			i->points,
124 			i->stage
125 		);
126 	fprintf(stderr,"\n\n");
127 }
128