Skip to content

Instantly share code, notes, and snippets.

@shrinktofit
Created September 30, 2020 10:39
Show Gist options
  • Save shrinktofit/3ef73975a29479856147b6760903328e to your computer and use it in GitHub Desktop.
Save shrinktofit/3ef73975a29479856147b6760903328e to your computer and use it in GitHub Desktop.
Snake in Java
class Vec2 {
public int x = 0;
public int y = 0;
public Vec2(int p_x, int p_y) {
this.x = p_x;
this.y = p_y;
}
public Vec2 copy() {
return new Vec2(this.x, this.y);
}
}
enum Direction {
up, down, left, right
}
class SnakeBodySegment {
public int length;
public Direction direction;
public SnakeBodySegment(Direction p_direction, int p_length) {
this.length = p_length;
this.direction = p_direction;
}
}
class Snake {
public Vec2 head;
public SnakeBodySegment[] body;
public Snake(Vec2 p_head, SnakeBodySegment[] p_body) {
this.head = p_head;
this.body = p_body;
}
public void print(int width, int height) {
char[][] buffers = new char[width][height];
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
buffers[i][j] = ' ';
}
}
Vec2 p = this.head.copy();
buffers[p.x][height - p.y + 1] = '*';
for (int iSegment = 0; iSegment < this.body.length; ++iSegment) {
SnakeBodySegment segment = this.body[iSegment];
for (int i = 0; i < segment.length; ++i) {
switch(segment.direction) {
case up: --p.y; break;
case down: ++p.y; break;
case left: ++p.x; break;
case right: --p.x; break;
}
buffers[p.x][height - p.y + 1] = '.';
}
}
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
System.out.print(buffers[j][i]);
}
System.out.println();
}
}
}
public class HelloWorld{
public static void main(String []args){
Snake snake = new Snake(
new Vec2(20, 20),
new SnakeBodySegment[]{
new SnakeBodySegment(Direction.up, 5),
new SnakeBodySegment(Direction.left, 8),
new SnakeBodySegment(Direction.up, 3),
new SnakeBodySegment(Direction.right, 4),
new SnakeBodySegment(Direction.up, 2),
new SnakeBodySegment(Direction.left, 9),
new SnakeBodySegment(Direction.down, 9),
new SnakeBodySegment(Direction.left, 2),
}
);
snake.print(50, 50);
System.out.println("Hello World");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment