-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathants.js
More file actions
169 lines (135 loc) · 3.29 KB
/
Copy pathants.js
File metadata and controls
169 lines (135 loc) · 3.29 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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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');
generateDirt();
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;
// this.speed = 1;
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];
// 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.9);
a.actions[r]();
}
// Creates white trail
if (a.x > 0 && a.x < width) {
dirt[a.x][a.y] = 0;
}
drawPixel(a.x, a.y, 'red');
}
}
function loop() {
render();
antLoop();
frames ++;
setTimeout(loop, 0);
}
function generateDirt() {
var x;
var y;
for (x = 0; x < width; x ++) {
for (y = surfaceBase; y >= 0; y --) {
dirt[x][y] = 0;
}
}
}
function drawPixel(x, y, color) {
var realX = x * zoom;
var realY = y * zoom;
ctx.fillStyle = color;
ctx.fillRect(realX, realY, zoom, zoom);
}
function clear() {
ctx.clearRect(0, 0, realWidth, realHeight);
}
function renderDirt() {
var x;
var y;
for (x = 0; x < width; x ++) {
for (y = 0; y < height; y ++) {
if (dirt[x][y]) {
drawPixel(x, y, 'black');
}
}
}
}
function render() {
clear();
renderDirt();
}
}