xref: /original-bsd/games/trek/compkl.c (revision 7a8f01dc)
1 /*
2  * Copyright (c) 1980 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)compkl.c	5.4 (Berkeley) 06/01/90";
10 #endif /* not lint */
11 
12 # include	"trek.h"
13 
14 /*
15 **  compute klingon distances
16 **
17 **	The klingon list has the distances for all klingons recomputed
18 **	and sorted.  The parameter is a Boolean flag which is set if
19 **	we have just entered a new quadrant.
20 **
21 **	This routine is used every time the Enterprise or the Klingons
22 **	move.
23 */
24 
25 compkldist(f)
26 int	f;		/* set if new quadrant */
27 {
28 	register int		i, dx, dy;
29 	double			d;
30 	double			temp;
31 
32 	if (Etc.nkling == 0)
33 		return;
34 	for (i = 0; i < Etc.nkling; i++)
35 	{
36 		/* compute distance to the Klingon */
37 		dx = Ship.sectx - Etc.klingon[i].x;
38 		dy = Ship.secty - Etc.klingon[i].y;
39 		d = dx * dx + dy * dy;
40 		d = sqrt(d);
41 
42 		/* compute average of new and old distances to Klingon */
43 		if (!f)
44 		{
45 			temp = Etc.klingon[i].dist;
46 			Etc.klingon[i].avgdist = 0.5 * (temp + d);
47 		}
48 		else
49 		{
50 			/* new quadrant: average is current */
51 			Etc.klingon[i].avgdist = d;
52 		}
53 		Etc.klingon[i].dist = d;
54 	}
55 
56 	/* leave them sorted */
57 	sortkl();
58 }
59 
60 
61 /*
62 **  sort klingons
63 **
64 **	bubble sort on ascending distance
65 */
66 
67 sortkl()
68 {
69 	struct kling		t;
70 	register int		f, i, m;
71 
72 	m = Etc.nkling - 1;
73 	f = 1;
74 	while (f)
75 	{
76 		f = 0;
77 		for (i = 0; i < m; i++)
78 			if (Etc.klingon[i].dist > Etc.klingon[i+1].dist)
79 			{
80 				bmove(&Etc.klingon[i], &t, sizeof t);
81 				bmove(&Etc.klingon[i+1], &Etc.klingon[i], sizeof t);
82 				bmove(&t, &Etc.klingon[i+1], sizeof t);
83 				f = 1;
84 			}
85 	}
86 }
87