-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
269 lines (235 loc) · 9.34 KB
/
index.html
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<title>Virtual Ants</title>
<meta name="description" content="Langton's Ant Playground" />
<script src="chroma.min.js"></script>
<link rel="stylesheet" href="mvp.css" />
<style>
/* Remove top/left whitespace */
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
font-family: monospace;
}
/* Dropdowns (https://stackoverflow.com/a/31474567) */
.dropdowns {
padding-left: 30px;
}
.dropdown {
position: relative;
width: 150px;
}
.dropdown select {
width: 100%;
height: 36px;
}
.dropdown>* {
box-sizing: border-box;
height: 1.5em;
}
.dropdown input {
position: absolute;
width: calc(100% - 26px);
height: 36px;
}
/* Intro text */
.intro {
padding-bottom: 15px;
padding-top: 0;
padding-left: 15px;
font-size: 16px;
}
</style>
</head>
<body>
<p class="intro">
<!-- Don't tell anyone I used non-breaking spaces for padding here -->
Langton's Ant (w/ multi-color).
<br />
Read my blog post <a href="https://healeycodes.com/virtual-ants/">Virtual Ants</a>,
<br />
or <a href="https://github.com/healeycodes/virtual-ants">view the repository</a>.
<br />
Play with rules/ant chance below:
</p>
<!-- https://stackoverflow.com/a/31474567 -->
<div class="dropdowns">
<div class="dropdown">
<input id="rules" type="text" value="RRLRR"
oninput="this.setAttribute('value', this.value); langtonAntCanvas()" />
<select
onchange="this.previousElementSibling.value=this.value; this.previousElementSibling.focus(); this.previousElementSibling.dispatchEvent(new Event('input', {bubbles:true}));"">
<option value=" RL">RL (Langton's Ant)</option>
<option value="RRLRLRR">RRLRLRR (Triangle)</option>
<option selected value="RRLRR">RRLRR (Square)</option>
<option value="RLLLRRRLLLLR">RLLLRRRLLLLR (Spiral in a square)</option>
<option value="RLLR">RLLR (Symmetrical mandala)</option>
<option value="RRLLRRRLRRRR">RRLLRRRLRRRR (Growing 3D-like solid)</option>
</select>
</div>
<div class="dropdown">
<input id="antChance" type="text" value="Single Ant"
oninput="this.setAttribute('value', this.value); langtonAntCanvas()" />
<select
onchange="this.previousElementSibling.value=this.value; this.previousElementSibling.focus(); this.previousElementSibling.dispatchEvent(new Event('input', {bubbles:true}));">
<option selected value="Single Ant">Single Ant</option>
<option value=".01">.01%</option>
<option value=".03">.03%</option>
<option value=".06">.06%</option>
<option value=".09">.09%</option>
<option value=".2">.2%</option>
</select>
</div>
</div>
<canvas />
<script>
// https://github.com/healeycodes/virtual-ants
// Resources:
// - https://en.wikipedia.org/wiki/Langton%27s_ant
// - https://mitpress.mit.edu/9780262561273/the-computational-beauty-of-nature/
// Random color palette given a length
// using colorbrewer2 as a source
function randomColorPalette(len) {
const palettes = Object.keys(chroma.brewer)
const randomBrewer =
chroma.brewer[palettes[Math.floor(Math.random() * palettes.length)]];
return chroma
.scale(randomBrewer)
.mode("lch")
.colors(len);
}
function round2even(num) {
return 2 * Math.floor(num / 2)
}
// Rotate direction clockwise or anti-clockwise
function rotateDirection(clockwise, dir) {
if (clockwise === true) {
return {
'u': 'r',
'r': 'd',
'd': 'l',
'l': 'u'
}[dir]
} else if (clockwise === false) {
return {
'u': 'l',
'l': 'd',
'd': 'r',
'r': 'u'
}[dir]
}
}
// Create a Langton Ant simulation
function langtonAntCanvas() {
// Grid unit size (also defines the draw size)
const UNITS = 4
// Fetch rules and antChance from DOM
const rules = document.querySelector('#rules').value
let antChance = document.querySelector('#antChance').value
// Allow the single ant branch for non-numerical values like 'Single Ant'
if (isNaN(Number(antChance))) {
antChance = -1
} else {
// Otherwise, turn into a float percentage
antChance / 100
}
// Clear up existing canvases, and create a new one
document.querySelectorAll('canvas').forEach(canvas => canvas.remove())
const canvas = document.createElement('canvas')
document.body.append(canvas)
// Size the canvas
const canvasWidth = round2even(window.innerWidth)
const canvasHeight = round2even(window.innerHeight - canvas.offsetHeight)
canvas.width = canvasWidth
canvas.height = canvasHeight
const ctx = canvas.getContext('2d');
// Generate palette (and take rule length into account)
const palette = randomColorPalette(rules.length)
const colors = rules.trim().toLowerCase().split('').map((x, i) => {
return [x, palette[i]]
})
const boardXY = [] // 2D array of rule indexes
for (let i = 0; i < canvasWidth; i++) {
boardXY.push((new Array(canvasHeight).fill(0)))
}
const ants = [] // 2D array of X, Y, direction
if (antChance === -1) {
// Create a single ant in the center
ants.push([
(canvasWidth / 2) - ((canvasWidth / 2) % UNITS),
(canvasHeight / 2) - ((canvasHeight / 2) % UNITS),
'u'
])
} else {
// Randomly place ants given the ant chance
for (let x = 0; x < canvasWidth; x += UNITS) {
for (let y = 0; y < canvasHeight; y += UNITS) {
if (Math.random() < antChance / 100) {
ants.push([x, y, 'u'])
}
}
}
}
// Move each ant to their next state,
// draw the result of their action as we go
function step() {
for (let i = 0; i < ants.length; i++) {
let x = ants[i][0]
let y = ants[i][1]
let dir = ants[i][2]
// The cell's state informs this ant's next move
let colorsIndex = boardXY[x][y]
const turnDir = colors[colorsIndex][0]
if (turnDir === 'r') {
dir = rotateDirection(true, dir)
} else if (turnDir === 'l') {
dir = rotateDirection(false, dir)
}
// Increment the cell's state
boardXY[x][y] = colorsIndex + 1 < colors.length ?
colorsIndex + 1 : 0
ctx.fillStyle = colors[colorsIndex][1]
ctx.fillRect(x, y, UNITS, UNITS);
// Move forward one unit
if (dir === 'u') {
y -= UNITS
} else if (dir === 'r') {
x += UNITS
} else if (dir === 'd') {
y += UNITS
} else if (dir === 'l') {
x -= UNITS
}
// Wrap around edges by clamping
if (x >= canvasWidth) {
x = 0
} else if (x < 0) {
x = (canvasWidth - 1) - ((canvasWidth - 1) % UNITS)
}
if (y >= canvasHeight) {
y = 0
} else if (y < 0) {
y = (canvasHeight - 1) - ((canvasHeight - 1) % UNITS)
}
// Update this ant's state
ants[i] = [x, y, dir]
}
requestAnimationFrame(step)
}
// Start!
step()
}
addEventListener('DOMContentLoaded', (_) => langtonAntCanvas());
</script>
</body>
</html>