|
| 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