forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_2_predators.js
More file actions
69 lines (65 loc) · 2.59 KB
/
07_2_predators.js
File metadata and controls
69 lines (65 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function SmartPlantEater() {
this.energy = 30;
this.direction = "e";
}
SmartPlantEater.prototype.act = function(view) {
var space = view.find(" ");
if (this.energy > 90 && space)
return {type: "reproduce", direction: space};
var plants = view.findAll("*");
if (plants.length > 1)
return {type: "eat", direction: randomElement(plants)};
if (view.look(this.direction) != " " && space)
this.direction = space;
return {type: "move", direction: this.direction};
};
function Tiger() {
this.energy = 100;
this.direction = "w";
// Used to track the amount of prey seen per turn in the last six turns
this.preySeen = [];
}
Tiger.prototype.act = function(view) {
// Average number of prey seen per turn
var seenPerTurn = this.preySeen.reduce(function(a, b) {
return a + b;
}, 0) / this.preySeen.length;
var prey = view.findAll("O");
this.preySeen.push(prey.length);
// Drop the first element from the array when it is longer than 6
if (this.preySeen.length > 6)
this.preySeen.shift();
// Only eat if the predator saw more than ¼ prey animal per turn
if (prey.length && seenPerTurn > 0.25)
return {type: "eat", direction: randomElement(prey)};
var space = view.find(" ");
if (this.energy > 400 && space)
return {type: "reproduce", direction: space};
if (view.look(this.direction) != " " && space)
this.direction = space;
return {type: "move", direction: this.direction};
};
animateWorld(new LifelikeWorld(
["####################################################",
"# #### **** ###",
"# * @ ## ######## OO ##",
"# * ## O O **** *#",
"# ##* ########## *#",
"# ##*** * **** **#",
"#* ** # * *** ######### **#",
"#* ** # * # * **#",
"# ## # O # *** ######",
"#* @ # # * O # #",
"#* # ###### ** #",
"### **** *** ** #",
"# O @ O #",
"# * ## ## ## ## ### * #",
"# ** # * ##### O #",
"## ** O O # # *** *** ### ** #",
"### # ***** ****#",
"####################################################"],
{"#": Wall,
"@": Tiger,
"O": SmartPlantEater, // from previous exercise
"*": Plant}
));