Last active
May 3, 2020 08:00
-
-
Save sasaki-shigeo/aa42938ab9c58cd813ea to your computer and use it in GitHub Desktop.
Turtle Graphics class in Processing / Processingによるタートルグラフィックスクラス(簡易版)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Turtle { | |
float x = 0; | |
float y = 0; | |
float dir = 0; | |
boolean pen_down = false; | |
int weight = 1; | |
color pen_color = #000000; | |
Turtle(float x, float y, float dir) { | |
this.x = x; | |
this.y = y; | |
this.dir = dir; | |
} | |
Turtle(float x, float y) { | |
this(x, y, 0); | |
} | |
Turtle() { | |
this(0, 0, 0); | |
} | |
void pen_down() { | |
pen_down = true; | |
} | |
void pen_up() { | |
pen_down = false; | |
} | |
void setColor(color col) { | |
pen_color = col; | |
} | |
void weight(int w) { | |
weight = w; | |
} | |
void turn(float theta) { | |
dir += theta; | |
} | |
void forward(float len) { | |
float end_x = x + len * cos(dir); | |
float end_y = y + len * sin(dir); | |
if (pen_down) { | |
strokeWeight(weight); | |
stroke(pen_color); | |
line(x, y, end_x, end_y); | |
} | |
x = end_x; | |
y = end_y; | |
} | |
void koch(float len, int n) { | |
if (n == 0) { | |
forward(len); | |
} | |
else { | |
koch(len/3, n-1); | |
turn(radians(-60)); | |
koch(len/3, n-1); | |
turn(radians(120)); | |
koch(len/3, n-1); | |
turn(radians(-60)); | |
koch(len/3, n-1); | |
} | |
} | |
void c_curve(float len, int n) { | |
if (n == 0) { | |
forward(len); | |
} | |
else { | |
turn(radians(-45)); | |
c_curve(len / sqrt(2), n - 1); | |
turn(radians(90)); | |
c_curve(len / sqrt(2), n - 1); | |
turn(radians(-45)); | |
} | |
} | |
void dragon(float len, int n) { | |
if (n == 0) { | |
turn(radians(45)); | |
forward(len/sqrt(2)); | |
turn(radians(-90)); | |
forward(len/sqrt(2)); | |
turn(radians(45)); | |
} | |
else { | |
pen_up(); | |
turn(radians(45)); | |
forward(len/sqrt(2)); | |
turn(radians(-180)); | |
pen_down(); | |
dragon(len/sqrt(2), n-1); | |
pen_up(); | |
turn(radians(-180)); | |
forward(len/sqrt(2)); | |
turn(radians(-90)); | |
pen_down(); | |
dragon(len/sqrt(2), n-1); | |
turn(radians(45)); | |
} | |
} | |
} | |
void setup() { | |
size(500, 500); | |
Turtle t1 = new Turtle(150, 300, 0); | |
t1.pen_down(); | |
t1.dragon(220, 10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment