xref: /original-bsd/games/trek/compkl.c (revision 03a7be21)
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 this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)compkl.c	5.2 (Berkeley) 05/05/88";
15 #endif /* not lint */
16 
17 # include	"trek.h"
18 
19 /*
20 **  compute klingon distances
21 **
22 **	The klingon list has the distances for all klingons recomputed
23 **	and sorted.  The parameter is a Boolean flag which is set if
24 **	we have just entered a new quadrant.
25 **
26 **	This routine is used every time the Enterprise or the Klingons
27 **	move.
28 */
29 
30 compkldist(f)
31 int	f;		/* set if new quadrant */
32 {
33 	register int		i, dx, dy;
34 	double			d;
35 	double			temp;
36 
37 	if (Etc.nkling == 0)
38 		return;
39 	for (i = 0; i < Etc.nkling; i++)
40 	{
41 		/* compute distance to the Klingon */
42 		dx = Ship.sectx - Etc.klingon[i].x;
43 		dy = Ship.secty - Etc.klingon[i].y;
44 		d = dx * dx + dy * dy;
45 		d = sqrt(d);
46 
47 		/* compute average of new and old distances to Klingon */
48 		if (!f)
49 		{
50 			temp = Etc.klingon[i].dist;
51 			Etc.klingon[i].avgdist = 0.5 * (temp + d);
52 		}
53 		else
54 		{
55 			/* new quadrant: average is current */
56 			Etc.klingon[i].avgdist = d;
57 		}
58 		Etc.klingon[i].dist = d;
59 	}
60 
61 	/* leave them sorted */
62 	sortkl();
63 }
64 
65 
66 /*
67 **  sort klingons
68 **
69 **	bubble sort on ascending distance
70 */
71 
72 sortkl()
73 {
74 	struct kling		t;
75 	register int		f, i, m;
76 
77 	m = Etc.nkling - 1;
78 	f = 1;
79 	while (f)
80 	{
81 		f = 0;
82 		for (i = 0; i < m; i++)
83 			if (Etc.klingon[i].dist > Etc.klingon[i+1].dist)
84 			{
85 				bmove(&Etc.klingon[i], &t, sizeof t);
86 				bmove(&Etc.klingon[i+1], &Etc.klingon[i], sizeof t);
87 				bmove(&t, &Etc.klingon[i+1], sizeof t);
88 				f = 1;
89 			}
90 	}
91 }
92