xref: /original-bsd/games/trek/compkl.c (revision 7211505a)
1 /*
2  * Copyright (c) 1980 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 static char sccsid[] = "@(#)compkl.c	5.3 (Berkeley) 06/18/88";
20 #endif /* not lint */
21 
22 # include	"trek.h"
23 
24 /*
25 **  compute klingon distances
26 **
27 **	The klingon list has the distances for all klingons recomputed
28 **	and sorted.  The parameter is a Boolean flag which is set if
29 **	we have just entered a new quadrant.
30 **
31 **	This routine is used every time the Enterprise or the Klingons
32 **	move.
33 */
34 
35 compkldist(f)
36 int	f;		/* set if new quadrant */
37 {
38 	register int		i, dx, dy;
39 	double			d;
40 	double			temp;
41 
42 	if (Etc.nkling == 0)
43 		return;
44 	for (i = 0; i < Etc.nkling; i++)
45 	{
46 		/* compute distance to the Klingon */
47 		dx = Ship.sectx - Etc.klingon[i].x;
48 		dy = Ship.secty - Etc.klingon[i].y;
49 		d = dx * dx + dy * dy;
50 		d = sqrt(d);
51 
52 		/* compute average of new and old distances to Klingon */
53 		if (!f)
54 		{
55 			temp = Etc.klingon[i].dist;
56 			Etc.klingon[i].avgdist = 0.5 * (temp + d);
57 		}
58 		else
59 		{
60 			/* new quadrant: average is current */
61 			Etc.klingon[i].avgdist = d;
62 		}
63 		Etc.klingon[i].dist = d;
64 	}
65 
66 	/* leave them sorted */
67 	sortkl();
68 }
69 
70 
71 /*
72 **  sort klingons
73 **
74 **	bubble sort on ascending distance
75 */
76 
77 sortkl()
78 {
79 	struct kling		t;
80 	register int		f, i, m;
81 
82 	m = Etc.nkling - 1;
83 	f = 1;
84 	while (f)
85 	{
86 		f = 0;
87 		for (i = 0; i < m; i++)
88 			if (Etc.klingon[i].dist > Etc.klingon[i+1].dist)
89 			{
90 				bmove(&Etc.klingon[i], &t, sizeof t);
91 				bmove(&Etc.klingon[i+1], &Etc.klingon[i], sizeof t);
92 				bmove(&t, &Etc.klingon[i+1], sizeof t);
93 				f = 1;
94 			}
95 	}
96 }
97