Skip to content

Instantly share code, notes, and snippets.

@daopk
Created February 14, 2016 09:45
Show Gist options
  • Save daopk/8d8c03d241f75a99f993 to your computer and use it in GitHub Desktop.
Save daopk/8d8c03d241f75a99f993 to your computer and use it in GitHub Desktop.
int width = 500;
int height = 200;
int lineWidth = 10;
int lineLength = 1000;
int startX = 0;
int startY = 0;
Snake snake;
void setup() {
frameRate(60);
size(width, height);
snake = new Snake(startX, startY, lineLength);
}
void draw() {
background(0,0);
strokeWeight(lineWidth);
snake.render();
snake.update();
}
class Snake {
ArrayList points;
Point start;
int length;
public Snake(x, y, l){
points = new ArrayList();
length = l;
start = new Point(x, y);
updateListPoints();
}
void render(){
stroke(0, 0, 255);
Point o;
for (Point p : points) {
if(o != null)
line(o.x, o.y, p.x, p.y);
o = p;
}
stroke(255, 0, 0);
point(start.x, start.y);
}
void update(){
start = getNextStart();
updateListPoints();
}
private Point getNextStart() {
if(start.y == 0){
if(start.x < width) start.x++;
else start.y++;
}
if(start.x == width){
if(start.y < height) start.y++;
else start.x--;
}
if(start.y == height){
if(start.x > 0) start.x--;
else start.y--;
}
if(start.x == 0){
if(start.y > 0) start.y--;
else start.x++;
}
return start;
}
private void updateListPoints() {
int t = length;
points.clear();
points.add(start);
Point old = start;
while (t > 0) {
if(old.y == 0 && old.x != 0){
if(t < old.x){
points.add(new Point(old.x - t, 0));
t = 0;
}
else {
t -= old.x;
old = new Point(0, 0);
points.add(old);
}
}
else if(old.x == width){
if(t < old.y){
points.add(new Point(width, old.y - t));
t = 0;
}else{
t -= old.y;
old = new Point(width, 0);
points.add(old);
}
}
else if(old.y == height){
if(t < width - old.x){
points.add(new Point(old.x + t, height));
t = 0;
}
else{
t -= (width - old.x);
old = new Point(width, height);
points.add(old);
}
}
else if(old.x == 0){
if(t < height - old.y){
points.add(new Point(0, old.y + t));
t = 0;
}
else {
t -= height - old.y;
old = new Point(0, height);
points.add(old);
}
}
}
return points;
}
}
class Point {
int x,y;
Point(int x_, int y_) {
x = x_;
y = y_;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment