import se.lth.cs.pt.dots.events.DotWindow;
import se.lth.cs.pt.dots.Color;
import se.lth.cs.pt.dots.events.GameEvent;
import se.lth.cs.pt.io.Keyboard;
import java.util.*;
class Snake {
public static void main(String[] args) {
new Snake().run();
}
DotWindow w;
Runner runner;
List<int[]> tail = new LinkedList<int[]>();
int tailLength;
void run() {
setup();
int tickCount = 0;
dance: while (true) {
GameEvent event = w.getNextEvent();
switch (event.getKind()) {
case GameEvent.TICK:
tickCount++;
if(tickCount%10==0) {
tailLength++;
}
System.out.println("TICK");
manageTail(runner.getPos());
runner.forward();
if (youHitSomething()) {
paintRed(runner.getPos());
break dance;
}
paintRed(runner.getPos());
break;
case GameEvent.KEY_PRESSED:
switch (event.getKey()) {
case 'a':
System.out.println("VÄNSTER");
runner.turnLeft();
break;
case 'd':
System.out.println("HÖGER");
runner.turnRight();
break;
}
}
}
}
void manageTail(int[] input) {
tail.addFirst(input);
paintBlue(tail.get(0));
paintWhite(tail.getLast());
tail.removeLast();
}
void paintTail() {
for (int[] coordinate : tail) {
paintBlue(coordinate);
}
//paintWhite(tail.get(tailLength-1));
}
boolean youHitSomething() {
if (!w.getDot(runner.getPos()[0], runner.getPos()[1]).equals(Color.WHITE)) {
return true;
}
return false;
}
void paintRed(int[] input) {
w.setDot(input[0], input[1], Color.RED);
}
void paintBlue(int[] input) {
w.setDot(input[0], input[1], Color.BLUE);
}
void paintWhite(int[] input) {
w.setDot(input[0], input[1], Color.WHITE);
}
void setup() {
int size = Keyboard.nextInt("Ange storlek! ");
int speed = 100;
w = new DotWindow(size, size, 10);
w.setAutoUpdate(false);
for (int k = 0; k<size; k++) {
w.setDot(k, 0, Color.BLACK);
w.setDot(k, size-1, Color.BLACK);
w.setDot(0, k, Color.BLACK);
w.setDot(size-1, k, Color.BLACK);
}
runner = new Runner(size);
w.setDot(runner.getX(), runner.getY(), Color.RED);
w.timeStep(speed);
w.checkKeys(true, false, false);
w.update();
w.setAutoUpdate(true);
}
}
class Runner {
private int xPos;
private int yPos;
private int direction;
private int[] coordinates = new int[2];
public Runner (int size) {
xPos = size/2;
yPos = size/2;
direction = 1;
updateCoordinates();
}
public int getX () {
return xPos;
}
public int getY () {
return yPos;
}
public int[] getPos() {
return coordinates;
}
public void turnRight () {
if (direction==1) {
direction=4;
} else {
direction--;
}
}
public void turnLeft () {
if (direction==4) {
direction=1;
} else {
direction++;
}
}
public void forward () {
switch (direction) {
case 1:
xPos++;
break;
case 2:
yPos--;
break;
case 3:
xPos--;
break;
case 4:
yPos++;
break;
}
updateCoordinates();
}
private void updateCoordinates() {
coordinates[0] = xPos;
coordinates[1] = yPos;
}
}