Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Snake;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Point;
- import java.util.ArrayList;
- public class Snakes {
- public static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, SCALE = 10;
- public Snake snake;
- public int direction = DOWN, score = 0, tailLength = 5;
- public ArrayList<Point> snakeParts = new ArrayList<Point>();
- public int playerNumber, x, y;
- public Point head;
- public Cherry cherry;
- public boolean over = false;
- public Snakes(Snake snake, int playerNumber, int x, int y) {
- this.head = new Point(x, y);
- this.x = x;
- this.y = y;
- this.playerNumber = playerNumber;
- for (int i = 0; i < tailLength; i++)
- snakeParts.add(new Point(head.x, head.y));
- }
- public void render(Graphics g) {
- String string = "Score: " + score + ", Length: " + tailLength;
- if (playerNumber == 1)
- g.setColor(Color.RED);
- else
- g.setColor(Color.YELLOW);
- Move(direction);
- for (Point point : this.snakeParts) {
- g.fillRect(point.x * Snake.SCALE, point.y * Snake.SCALE, Snake.SCALE, Snake.SCALE);
- }
- g.fillRect(this.head.x * Snake.SCALE, this.head.y * Snake.SCALE, Snake.SCALE, Snake.SCALE);
- g.setFont(new Font("Arial", 1, 15));
- if(playerNumber == 1) {
- g.drawString(string, 0, 10);
- }
- else
- g.drawString(string, 660, 10);
- }
- public void Move(int moveDirection) {
- // this.direction = moveDirection;
- snakeParts.add(new Point(head.x, head.y));
- if (snakeParts.size() > tailLength)
- snakeParts.remove(0);
- switch (moveDirection) {
- case (UP):
- if (this.direction != DOWN) {
- if (head.y - 1 >= 0 && NoTailAt(head.x, head.y - 1)) {
- head = new Point(head.x, head.y - 1);
- this.direction = moveDirection;
- } else
- over = true;
- }
- break;
- case (DOWN):
- if (this.direction != UP) {
- if (head.y + 1 < 67 && NoTailAt(head.x, head.y + 1)) {
- head = new Point(head.x, head.y + 1);
- this.direction = moveDirection;
- } else
- over = true;
- }
- break;
- case (LEFT):
- if (this.direction != RIGHT) {
- if (head.x - 1 >= 0 && NoTailAt(head.x - 1, head.y)) {
- head = new Point(head.x - 1, head.y);
- this.direction = moveDirection;
- } else
- over = true;
- }
- break;
- case (RIGHT):
- if (this.direction != LEFT) {
- if (head.x + 1 < 80 && NoTailAt(head.x + 1, head.y)) {
- head = new Point(head.x + 1, head.y);
- this.direction = moveDirection;
- } else
- over = true;
- }
- break;
- }
- }
- public boolean NoTailAt(int x, int y) {
- for (Point point : snakeParts) {
- if (point.equals(new Point(x, y)))
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement