forked from MatthewRayfield/ants
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathants.js
139 lines (109 loc) · 2.74 KB
/
ants.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
function AntFarm() {
// Settings
var width = 200;
var height = 150;
var zoom = 2;
var surfaceBase = 10;
var antCount = 10;
var can;
var ctx;
var dirt = [];
var ants = [];
var fpsBox;
var frames = 0;
var realWidth = width * zoom;
var realHeight = height * zoom;
window.onload = init;
function init() {
var x;
var y;
for (x = 0; x < width; x ++) {
dirt[x] = [];
for (y = 0; y < height; y ++) {
dirt[x][y] = 1;
}
}
can = document.createElement('canvas');
can.width = realWidth;
can.height = realHeight;
document.body.appendChild(can);
fpsBox = document.createElement('div');
document.body.appendChild(fpsBox);
ctx = can.getContext('2d');
ctx.fillRect(0,0,realWidth, realHeight);
initAnts();
loop();
showFps();
}
function showFps() {
fpsBox.innerHTML = frames;
frames = 0;
setTimeout(showFps, 1000);
}
function Ant(){
this.x = Math.floor(Math.random()*width);
this.y = 0;
var thisAnt = this;
this.actions = [
function left() {
thisAnt.x --;
},
function right() {
thisAnt.x ++;
},
function up() {
thisAnt.y --;
},
function down() {
thisAnt.y ++;
}
];
}
function initAnts() {
var i;
for (i = 0; i < antCount; i++) {
ants[i] = new Ant();
}
}
function antLoop() {
var i;
var l = ants.length;
var x;
var y;
var al;
var r;
var a;
for (i = 0; i < l; i++) {
a = ants[i];
x = a.x;
y = a.y;
// Check if dirt is not under ant
if (!dirt[a.x] || !dirt[a.x][a.y+1]) {
a.y ++;
}
else {
al = a.actions.length;
// Cause more left to right
r = Math.floor(Math.random()*al*0.85);
a.actions[r]();
}
// Creates white trail
if (a.x > 0 && a.x < width) {
dirt[a.x][a.y] = 0;
}
drawPixel(x,y, 'white');
drawPixel(a.x, a.y, 'red');
}
}
function loop() {
antLoop();
frames ++;
setTimeout(loop, 0);
}
function drawPixel(x, y, color) {
var realX = x * zoom;
var realY = y * zoom;
ctx.fillStyle = color;
ctx.fillRect(realX, realY, zoom, zoom);
}
}