Skip to content

Commit 5780beb

Browse files
committed
adding koch examples
1 parent 32bc533 commit 5780beb

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

docs/examples.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,17 @@ Cartesian koch snowflake example
194194
:lines: 5-
195195
.. image:: ../docs/koch.jpg
196196

197+
198+
Cartesian Koch Curve
199+
---------------------------
200+
201+
Cartesian koch curve example
202+
203+
.. literalinclude:: ../examples/cartesian_koch_2.py
204+
:caption: examples/cartesian_koch_2.py
205+
:lines: 5-
206+
.. image:: ../docs/koch2.jpg
207+
197208
==================
198209
Bar Examples
199210
==================

docs/koch2.jpg

44.6 KB
Loading

examples/cartesian_koch_2.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2023 Jose D. Montoya
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
# Example adapted to use in CircuitPython and Microplot from
6+
# Heltonbiker
7+
# https://stackoverflow.com/questions/7409938/fractal-koch-curve
8+
9+
import math
10+
import board
11+
from circuitpython_uplot.plot import Plot
12+
from circuitpython_uplot.cartesian import Cartesian
13+
14+
angles = [math.radians(60 * x) for x in range(6)]
15+
sines = [math.sin(x) for x in angles]
16+
cosin = [math.cos(x) for x in angles]
17+
18+
19+
def L(angle, coords, jump):
20+
return (angle + 1) % 6
21+
22+
23+
def R(angle, coords, jump):
24+
return (angle + 4) % 6
25+
26+
27+
def F(angle, coords, jump):
28+
coords.append(
29+
(coords[-1][0] + jump * cosin[angle], coords[-1][1] + jump * sines[angle])
30+
)
31+
return angle
32+
33+
34+
decode = dict(L=L, R=R, F=F)
35+
36+
37+
def koch(steps, length=200, startPos=(0, 0)):
38+
pathcodes = "F"
39+
for i in range(steps):
40+
pathcodes = pathcodes.replace("F", "FLFRFLF")
41+
42+
jump = float(length) / (3**steps)
43+
coords = [startPos]
44+
angle = 0
45+
46+
for move in pathcodes:
47+
angle = decode[move](angle, coords, jump)
48+
49+
return coords
50+
51+
52+
TOTALWIDTH = 300
53+
display = board.DISPLAY
54+
plot = Plot(0, 0, display.width, display.height, padding=0)
55+
points = koch(5, TOTALWIDTH, (-TOTALWIDTH / 2, 0))
56+
x_coordinates, y_coordinates = zip(*points)
57+
58+
# Adding the Cartesian plot
59+
Cartesian(plot, x_coordinates, y_coordinates)
60+
display.show(plot)

0 commit comments

Comments
 (0)