xref: /openbsd/games/quiz/quiz.c (revision 3cab2bb3)
1 /*	$OpenBSD: quiz.c,v 1.30 2018/08/24 11:14:49 mestre Exp $	*/
2 /*	$NetBSD: quiz.c,v 1.9 1995/04/22 10:16:58 cgd Exp $	*/
3 
4 /*-
5  * Copyright (c) 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Jim R. Oldroyd at The Instruction Set and Keith Gabryelski at
10  * Commodore Business Machines.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <ctype.h>
38 #include <err.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #include "pathnames.h"
45 #include "quiz.h"
46 
47 static QE qlist;
48 static int catone, cattwo, tflag;
49 static u_int qsize;
50 
51 char	*appdstr(char *, const char *, size_t);
52 void	 downcase(char *);
53 void	 get_cats(char *, char *);
54 void	 get_file(const char *);
55 const char	*next_cat(const char *);
56 void	 quiz(void);
57 void	 score(u_int, u_int, u_int);
58 void	 show_index(void);
59 __dead void	usage(void);
60 
61 int
62 main(int argc, char *argv[])
63 {
64 	int ch;
65 	const char *indexfile;
66 
67 	if (pledge("stdio rpath proc exec", NULL) == -1)
68 		err(1, "pledge");
69 
70 	indexfile = _PATH_QUIZIDX;
71 	while ((ch = getopt(argc, argv, "hi:t")) != -1)
72 		switch(ch) {
73 		case 'i':
74 			indexfile = optarg;
75 			break;
76 		case 't':
77 			tflag = 1;
78 			break;
79 		case 'h':
80 		default:
81 			usage();
82 		}
83 	argc -= optind;
84 	argv += optind;
85 
86 	switch(argc) {
87 	case 0:
88 		get_file(indexfile);
89 		show_index();
90 		break;
91 	case 2:
92 		if (pledge("stdio rpath", NULL) == -1)
93 			err(1, "pledge");
94 		get_file(indexfile);
95 		get_cats(argv[0], argv[1]);
96 
97 		if (pledge("stdio", NULL) == -1)
98 			err(1, "pledge");
99 
100 		quiz();
101 		break;
102 	default:
103 		usage();
104 	}
105 	return 0;
106 }
107 
108 void
109 get_file(const char *file)
110 {
111 	FILE *fp;
112 	QE *qp;
113 	size_t len;
114 	char *lp;
115 
116 	if ((fp = fopen(file, "r")) == NULL)
117 		err(1, "%s", file);
118 
119 	/*
120 	 * XXX
121 	 * Should really free up space from any earlier read list
122 	 * but there are no reverse pointers to do so with.
123 	 */
124 	qp = &qlist;
125 	qsize = 0;
126 	while ((lp = fgetln(fp, &len)) != NULL) {
127 		if (lp[len - 1] == '\n')
128 			--len;
129 		if (qp->q_text && qp->q_text[0] != '\0' &&
130 		    qp->q_text[strlen(qp->q_text) - 1] == '\\')
131 			qp->q_text = appdstr(qp->q_text, lp, len);
132 		else {
133 			if ((qp->q_next = malloc(sizeof(QE))) == NULL)
134 				errx(1, "malloc");
135 			qp = qp->q_next;
136 			if ((qp->q_text = malloc(len + 1)) == NULL)
137 				errx(1, "malloc");
138 			/* lp may not be zero-terminated; cannot use strlcpy */
139 			strncpy(qp->q_text, lp, len);
140 			qp->q_text[len] = '\0';
141 			qp->q_asked = qp->q_answered = FALSE;
142 			qp->q_next = NULL;
143 			++qsize;
144 		}
145 	}
146 	(void)fclose(fp);
147 }
148 
149 void
150 show_index(void)
151 {
152 	QE *qp;
153 	const char *p, *s;
154 	FILE *pf;
155 	const char *pager;
156 
157 	if (!isatty(1))
158 		pager = "/bin/cat";
159 	else if (!(pager = getenv("PAGER")) || (*pager == 0))
160 			pager = _PATH_PAGER;
161 	if ((pf = popen(pager, "w")) == NULL)
162 		err(1, "%s", pager);
163 	(void)fprintf(pf, "Subjects:\n\n");
164 	for (qp = qlist.q_next; qp; qp = qp->q_next) {
165 		for (s = next_cat(qp->q_text); s; s = next_cat(s)) {
166 			if (!rxp_compile(s))
167 				errx(1, "%s", rxperr);
168 			if ((p = rxp_expand()))
169 				(void)fprintf(pf, "%s ", p);
170 		}
171 		(void)fprintf(pf, "\n");
172 	}
173 	(void)fprintf(pf, "\n%s\n%s\n%s\n",
174 "For example, \"quiz victim killer\" prints a victim's name and you reply",
175 "with the killer, and \"quiz killer victim\" works the other way around.",
176 "Type an empty line to get the correct answer.");
177 	(void)pclose(pf);
178 }
179 
180 void
181 get_cats(char *cat1, char *cat2)
182 {
183 	QE *qp;
184 	int i;
185 	const char *s;
186 
187 	downcase(cat1);
188 	downcase(cat2);
189 	for (qp = qlist.q_next; qp; qp = qp->q_next) {
190 		s = next_cat(qp->q_text);
191 		catone = cattwo = i = 0;
192 		while (s) {
193 			if (!rxp_compile(s))
194 				errx(1, "%s", rxperr);
195 			i++;
196 			if (rxp_match(cat1))
197 				catone = i;
198 			if (rxp_match(cat2))
199 				cattwo = i;
200 			s = next_cat(s);
201 		}
202 		if (catone && cattwo && catone != cattwo) {
203 			if (!rxp_compile(qp->q_text))
204 				errx(1, "%s", rxperr);
205 			get_file(rxp_expand());
206 			return;
207 		}
208 	}
209 	errx(1, "invalid categories");
210 }
211 
212 void
213 quiz(void)
214 {
215 	QE *qp;
216 	int i;
217 	size_t len;
218 	u_int guesses, rights, wrongs;
219 	int next;
220 	char *answer, *t, question[LINE_SZ];
221 	const char *s;
222 
223 	guesses = rights = wrongs = 0;
224 	for (;;) {
225 		if (qsize == 0)
226 			break;
227 		next = arc4random_uniform(qsize);
228 		qp = qlist.q_next;
229 		for (i = 0; i < next; i++)
230 			qp = qp->q_next;
231 		while (qp && qp->q_answered)
232 			qp = qp->q_next;
233 		if (!qp) {
234 			qsize = next;
235 			continue;
236 		}
237 		if (tflag && arc4random_uniform(100) > 20) {
238 			/* repeat questions in tutorial mode */
239 			while (qp && (!qp->q_asked || qp->q_answered))
240 				qp = qp->q_next;
241 			if (!qp)
242 				continue;
243 		}
244 		s = qp->q_text;
245 		for (i = 0; i < catone - 1; i++)
246 			s = next_cat(s);
247 		if (!rxp_compile(s))
248 			errx(1, "%s", rxperr);
249 		t = rxp_expand();
250 		if (!t || *t == '\0') {
251 			qp->q_answered = TRUE;
252 			continue;
253 		}
254 		(void)strlcpy(question, t, sizeof question);
255 		s = qp->q_text;
256 		for (i = 0; i < cattwo - 1; i++)
257 			s = next_cat(s);
258 		if (s == NULL)
259 			errx(1, "too few fields in data file, line \"%s\"",
260 			    qp->q_text);
261 		if (!rxp_compile(s))
262 			errx(1, "%s", rxperr);
263 		t = rxp_expand();
264 		if (!t || *t == '\0') {
265 			qp->q_answered = TRUE;
266 			continue;
267 		}
268 		qp->q_asked = TRUE;
269 		(void)printf("%s?\n", question);
270 		for (;; ++guesses) {
271 			if ((answer = fgetln(stdin, &len)) == NULL ||
272 			    answer[len - 1] != '\n') {
273 				score(rights, wrongs, guesses);
274 				exit(0);
275 			}
276 			answer[len - 1] = '\0';
277 			downcase(answer);
278 			if (rxp_match(answer)) {
279 				(void)printf("Right!\n");
280 				++rights;
281 				qp->q_answered = TRUE;
282 				break;
283 			}
284 			if (*answer == '\0') {
285 				(void)printf("%s\n", t);
286 				++wrongs;
287 				if (!tflag)
288 					qp->q_answered = TRUE;
289 				break;
290 			}
291 			(void)printf("What?\n");
292 		}
293 	}
294 	score(rights, wrongs, guesses);
295 }
296 
297 const char *
298 next_cat(const char *s)
299 {
300 	int esc;
301 
302 	if (s == NULL)
303 		return (NULL);
304 	esc = 0;
305 	for (;;)
306 		switch (*s++) {
307 		case '\0':
308 			return (NULL);
309 		case '\\':
310 			esc = 1;
311 			break;
312 		case ':':
313 			if (!esc)
314 				return (s);
315 		default:
316 			esc = 0;
317 			break;
318 		}
319 }
320 
321 char *
322 appdstr(char *s, const char *tp, size_t len)
323 {
324 	char *mp;
325 	const char *sp;
326 	int ch;
327 	char *m;
328 
329 	if ((m = malloc(strlen(s) + len + 1)) == NULL)
330 		errx(1, "malloc");
331 	for (mp = m, sp = s; (*mp++ = *sp++) != '\0'; )
332 		;
333 	--mp;
334 	if (*(mp - 1) == '\\')
335 		--mp;
336 
337 	while ((ch = *mp++ = *tp++) && ch != '\n')
338 		;
339 	if (*(mp - 2) == '\\')
340 		mp--;
341 	*mp = '\0';
342 
343 	free(s);
344 	return (m);
345 }
346 
347 void
348 score(u_int r, u_int w, u_int g)
349 {
350 	(void)printf("Rights %d, wrongs %d,", r, w);
351 	if (g)
352 		(void)printf(" extra guesses %d,", g);
353 	(void)printf(" score %d%%\n", (r + w + g) ? r * 100 / (r + w + g) : 0);
354 }
355 
356 void
357 downcase(char *p)
358 {
359 	int ch;
360 
361 	for (; (ch = *p) != '\0'; ++p)
362 		if (isascii(ch) && isupper(ch))
363 			*p = tolower(ch);
364 }
365 
366 void
367 usage(void)
368 {
369 	(void)fprintf(stderr,
370 	    "usage: %s [-t] [-i file] category1 category2\n", getprogname());
371 	exit(1);
372 }
373