Initial import.
[ogre.git] / brain.js
1 "use strict";
2
3 function randrange (lo, hi) {
4 return lo + (Math.random() * (hi - lo)) | 0;
5 }
6
7 function shuffle (seq) {
8 for (var i = seq.length - 1; i > 0; --i) {
9 var index = randrange(0, i + 1);
10 var temp = seq[i];
11 seq[i] = seq[index];
12 seq[index] = temp;
13 }
14 return seq;
15 }
16
17 var MOVEMENT = ["fore", "fore", "fore", "fore", "fore",
18 "left", "left", "left",
19 "right", "right", "right",
20 null];
21 var RAMMING = ["none", "none", "fore", "fore", "aft"];
22 var ORDER = ["nearest", "nearest", "nearest",
23 "threat", "strongest", "farthest"];
24 var BREAKER = ["clockwise", "clockwise",
25 "anti-clockwise", "anti-clockwise"];
26 var ARC = ["fore", "fore", "fore", "aft"];
27
28 var FIRING = ["spread fire, engage 1-1",
29 "spread fire, engage 1-1",
30 "spread fire, engage 1-1",
31 "focus fire, engage 2-1",
32 "focus fire, engage 2-1",
33 "concentrate all fire"];
34 var MISSILES = [0.20, 0.10, 0.05];
35
36 function drop1 (seq) {
37 return shuffle(seq.slice()).slice(1);
38 }
39
40 function Brain () {
41 var movement = drop1(MOVEMENT);
42 var ramming = drop1(RAMMING);
43 var order = drop1(ORDER);
44 var breaker = drop1(BREAKER);
45 var arc = drop1(ARC);
46 var firing = drop1(FIRING);
47 var missiles = choice(MISSILES)
48
49 this.report = function (movePoints, hasMissiles) {
50 var ram = movePoints > 1 ? choice(ramming) : null;
51 var move = [];
52 for (var i = 0; i < movePoints; ++i) {
53 do {
54 var m = choice(movement);
55 } while ((m === "left" && move.indexOf("right") >= 0)
56 || (m === "right" && move.indexOf("left") >= 0))
57 if (m)
58 move.push(m);
59 }
60
61 var launch = 0;
62 while (hasMissiles && Math.random() < Math.pow(missiles, launch + 1))
63 ++launch;
64
65 var instr = [];
66 instr.push("sensors sweeping " + choice(breaker));
67 if (ram === "aft")
68 instr.push("ram back if opportune");
69 instr.push((ram === "aft" ? "otherwise " : "")
70 + "ahead " + move.join(", "));
71 if (ram)
72 instr.push(" ramming if opportune");
73 instr.push("target " + choice(order) + ", "
74 + choice(arc) + " first");
75 instr.push(" " + choice(firing));
76 if (hasMissiles)
77 instr.push("launch missiles at howitzers and key targets");
78 if (launch) {
79 instr.push(" further expend up to " + launch + " missile(s)");
80 instr.push(" on the " + choice(order) + " vehicle target(s)");
81 }
82
83 return instr.join("\n");
84 }
85 return this;
86 }
87
88 var brain, ttl;
89 function think () {
90 if (!(brain && ttl-- > 0)) {
91 brain = new Brain();
92 ttl = Math.max(1, choice([2, 10, 18]) + randrange(-2, 3));
93 }
94 document.getElementById('report').textContent =
95 brain.report(3, true, true).replace(/\w\S*/g, function (s) {
96 return ["and", "of", "if", "at"].indexOf(s) < 0
97 ? s[0].toUpperCase() + s.slice(1)
98 : s;
99 });
100 }