author Angelo Gladding
name Turtle Graphics
published 2025-06-11T13:19:35.114815-07:00
type entry
updated 2025-07-29T18:36:03.019992-07:00
url /turtle, /logo, /2025/06/11/nq
visibility public
Content
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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | I was introduced to computer programming in 3rd grade (1992) with [wp:Logo]. [wp:Turtle_graphics] <canvas id=canvas></canvas> <div id=controls> <div> <label class=bounding><textarea id=code>setcolor red setwidth 4 repeat 6 [ forward 60 right 60 ] penup forward 100 pendown setcolor blue repeat 36 [forward 5 right 10]</textarea></label> <div id=autocomplete></div> </div> <div> <div style=margin-bottom:.5em><label>Speed: <input style=height:.25em type=range id=speed min=1 max=1000 value=500></label></div> <div><button onclick=run()>Run</button> <button onclick=togglePause() id=pauseBtn>Pause</button></div> <div><button onclick=exportImage()>Export</button> <button onclick="alert('work in progress')">Post</button></div> </div> </div> <hr> Mention or reply with your creation using the `featured` and `code` microformat properties. <style> canvas { border: .15em solid #586e75; height: 40em; width: 100%; } #controls { display: flex; gap: .5em; } #controls > div { flex: 1; } textarea { font-family: "Ubuntu Mono", monospace; height: 20em; } #autocomplete { background: #f0f0f0; border: 1px solid #aaa; font-family: monospace; font-size: 14px; display: none; z-index: 10; max-height: 120px; overflow-y: auto; width: 150px; } #autocomplete div { padding: 2px 6px; cursor: pointer; } #autocomplete .selected { background: #007acc; color: white; } </style> <script> const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d') let x, y, angle let penDown = true let strokeColor = 'blue' let strokeWidth = 2 let commandQueue = [] let currentStep = 0 let paused = false function getDelay() { const speed = +document.getElementById('speed').value const max = +document.getElementById('speed').max return Math.round(200 * (1 - speed / max)) } function isInstant() { const speed = +document.getElementById('speed').value const max = +document.getElementById('speed').max return speed >= max } function forward(dist) { const rad = angle * Math.PI / 180 const nx = x + Math.cos(rad) * dist const ny = y + Math.sin(rad) * dist if (penDown) { ctx.beginPath() ctx.moveTo(x, y) ctx.lineTo(nx, ny) ctx.strokeStyle = strokeColor ctx.lineWidth = strokeWidth ctx.stroke() } x = nx y = ny drawTurtle() } function right(deg) { angle += deg; drawTurtle() } function left(deg) { angle -= deg; drawTurtle() } function runLine(cmd, arg) { if (cmd === 'forward') forward(arg) else if (cmd === 'right') right(arg) else if (cmd === 'left') left(arg) else if (cmd === 'penup') penDown = false else if (cmd === 'pendown') penDown = true else if (cmd === 'setcolor') strokeColor = arg else if (cmd === 'setwidth') strokeWidth = arg } function drawTurtle() { ctx.clearRect(0, 0, canvas.width, canvas.height) redrawLines() const rad = angle * Math.PI / 180 const size = 6 ctx.beginPath() ctx.moveTo(x + Math.cos(rad) * size, y + Math.sin(rad) * size) ctx.lineTo(x + Math.cos(rad + Math.PI * 0.75) * size, y + Math.sin(rad + Math.PI * 0.75) * size) ctx.lineTo(x + Math.cos(rad - Math.PI * 0.75) * size, y + Math.sin(rad - Math.PI * 0.75) * size) ctx.closePath() ctx.fillStyle = 'green' ctx.fill() } let segmentHistory = [] function redrawLines() { ctx.save() for (let seg of segmentHistory) { ctx.strokeStyle = seg.color ctx.lineWidth = seg.width ctx.beginPath() ctx.moveTo(seg.from[0], seg.from[1]) ctx.lineTo(seg.to[0], seg.to[1]) ctx.stroke() } ctx.restore() } function recordLine(x1, y1, x2, y2) { if (penDown) { segmentHistory.push({ from: [x1, y1], to: [x2, y2], color: strokeColor, width: strokeWidth }) } } function animateForward(dist, done) { if (isInstant()) { const x0 = x, y0 = y forward(dist) recordLine(x0, y0, x, y) return done() } const steps = Math.max(1, Math.floor(Math.abs(dist) / 2)) let count = 0 const dx = Math.cos(angle * Math.PI / 180) * (dist / steps) const dy = Math.sin(angle * Math.PI / 180) * (dist / steps) let lastX = x, lastY = y function moveStep() { if (paused) return if (count++ >= steps) { recordLine(lastX, lastY, x, y) return done() } const nx = x + dx const ny = y + dy recordLine(x, y, nx, ny) x = nx y = ny drawTurtle() const delay = getDelay() setTimeout(() => requestAnimationFrame(moveStep), delay) } moveStep() } function step() { if (paused) return if (currentStep >= commandQueue.length) return const [cmd, arg] = commandQueue[currentStep++] if (cmd === 'forward') { if (isInstant()) { const x0 = x, y0 = y forward(arg) recordLine(x0, y0, x, y) requestAnimationFrame(step) } else { animateForward(arg, () => { const delay = getDelay() setTimeout(() => requestAnimationFrame(step), delay) }) } } else { runLine(cmd, arg) const delay = getDelay() if (isInstant() || delay <= 0) { requestAnimationFrame(step) } else { setTimeout(() => requestAnimationFrame(step), delay) } } } function run() { ctx.clearRect(0, 0, canvas.width, canvas.height) x = 200 y = 200 angle = 0 penDown = true strokeColor = 'blue' strokeWidth = 2 commandQueue = [] currentStep = 0 paused = false segmentHistory = [] document.getElementById('pauseBtn').innerText = 'Pause' const code = document.getElementById('code').value const tokens = tokenize(code) const commands = parseTokens(tokens) commandQueue.push(...commands) requestAnimationFrame(step) } function togglePause() { paused = !paused document.getElementById('pauseBtn').innerText = paused ? 'Resume' : 'Pause' if (!paused) requestAnimationFrame(step) } function exportImage() { const link = document.createElement('a') link.download = 'turtle.png' link.href = canvas.toDataURL() link.click() } function tokenize(code) { return code .replace(/\[/g, ' [ ') .replace(/\]/g, ' ] ') .trim() .split(/\s+/) } function parseTokens(tokens) { const result = [] let i = 0 function parseBlock() { const block = [] while (i < tokens.length) { const token = tokens[i++] if (token === ']') break if (token === 'repeat') { const times = parseInt(tokens[i++]) if (tokens[i++] !== '[') throw new Error('Expected [') const inner = parseBlock() for (let t = 0; t < times; t++) { block.push(...inner) } } else { const cmd = token let arg = null if (cmd === 'penup' || cmd === 'pendown') { // no argument } else if (cmd === 'setcolor') { arg = tokens[i++] } else { arg = parseFloat(tokens[i++]) } block.push([cmd, arg]) } } return block } while (i < tokens.length) { const token = tokens[i++] if (token === 'repeat') { const times = parseInt(tokens[i++]) if (tokens[i++] !== '[') throw new Error('Expected [') const inner = parseBlock() for (let t = 0; t < times; t++) { result.push(...inner) } } else { const cmd = token let arg = null if (cmd === 'penup' || cmd === 'pendown') { // no argument } else if (cmd === 'setcolor') { arg = tokens[i++] } else { arg = parseFloat(tokens[i++]) } result.push([cmd, arg]) } } return result } const textarea = document.getElementById('code') const acBox = document.getElementById('autocomplete') const keywords = ["forward", "left", "right", "penup", "pendown", "setcolor", "setwidth", "repeat"] const colors = ["red", "blue", "green", "black", "orange", "purple", "yellow", "gray"] let acList = [] let acIndex = -1 textarea.addEventListener('input', showAutocomplete) textarea.addEventListener('keydown', handleAutocompleteKeys) function showAutocomplete() { const pos = textarea.selectionStart const text = textarea.value.slice(0, pos) const match = text.match(/(\w+)$$/) if (!match) return hideAutocomplete() const prefix = match[1].toLowerCase() acList = [...keywords, ...colors].filter(w => w.startsWith(prefix)) if (!acList.length) return hideAutocomplete() acBox.innerHTML = acList.map((w, i) => `<div class="$${i === 0 ? 'selected' : ''}">$${w}</div>` ).join('') acBox.style.display = 'block' acIndex = 0 } function hideAutocomplete() { acBox.style.display = 'none' acList = [] } function handleAutocompleteKeys(e) { if (acBox.style.display !== 'block') return if (e.key === 'ArrowDown') { e.preventDefault() acIndex = (acIndex + 1) % acList.length updateHighlight() } else if (e.key === 'ArrowUp') { e.preventDefault() acIndex = (acIndex - 1 + acList.length) % acList.length updateHighlight() } else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault() insertCompletion(acList[acIndex]) } else if (e.key === 'Escape') { hideAutocomplete() } } function updateHighlight() { const children = acBox.querySelectorAll('div') children.forEach((el, i) => { el.className = i === acIndex ? 'selected' : '' }) } function insertCompletion(word) { const pos = textarea.selectionStart const text = textarea.value const before = text.slice(0, pos) const after = text.slice(pos) const match = before.match(/(\w+)$$/) if (!match) return const start = pos - match[1].length textarea.value = before.slice(0, start) + word + after textarea.selectionStart = textarea.selectionEnd = start + word.length hideAutocomplete() textarea.focus() } </script> |