For me, this bloc of code fullfill the conditions number 4 and 5:
if (checkCollision(newHead))
isAlive = false;
else
{
snakeParts.add(0, newHead);
if (checkCollision(apple))
apple.isAlive = false;
else
removeTail();
}
So what's wrong there?package com.codegym.games.snake;
import com.codegym.engine.cell.*;
import java.util.ArrayList;
import java.util.List;
public class Snake extends GameObject{
public static boolean isAlive = true;
private final static String HEAD_SIGN = isAlive ? "š¾" : "ā ļø";
private final static String BODY_SIGN = isAlive ? "ā" : "š©";
private int maxParts = 3;
private List<GameObject> snakeParts = new ArrayList<>();
private Direction direction = Direction.LEFT;
public Snake(int x, int y) {
super(x, y);
for (int i = 0; i < maxParts; i++)
snakeParts.add(new GameObject(x + i, y));
}
public void draw(Game game) {
Color color = isAlive ? Color.BLUE : Color.RED;
for (int i = 0; i < snakeParts.size(); i++) {
GameObject part = snakeParts.get(i);
String sign = (i != 0) ? BODY_SIGN : HEAD_SIGN;
game.setCellValueEx(part.x, part.y, Color.NONE, sign, color, 75);
}
}
public void move(Apple apple) {
GameObject newHead = createNewHead();
if (newHead.x >= SnakeGame.WIDTH
|| newHead.x < 0
|| newHead.y >= SnakeGame.HEIGHT
|| newHead.y < 0){
isAlive = false;
return;
}
if (checkCollision(newHead))
isAlive = false;
else
{
snakeParts.add(0, newHead);
if (checkCollision(apple))
apple.isAlive = false;
else
removeTail();
}
}
public GameObject createNewHead() {
GameObject oldHead = snakeParts.get(0);
if (direction == Direction.LEFT) {
return new GameObject(oldHead.x - 1, oldHead.y);
} else if (direction == Direction.RIGHT) {
return new GameObject(oldHead.x + 1, oldHead.y);
} else if (direction == Direction.UP) {
return new GameObject(oldHead.x, oldHead.y - 1);
} else {
return new GameObject(oldHead.x, oldHead.y + 1);
}
}
public void removeTail() {
snakeParts.remove(snakeParts.size() - 1);
}
public void setDirection(Direction direction) {
Direction sDirection = getDirection();
switch(direction)
{
case LEFT:
if (sDirection != Direction.RIGHT)
this.direction = direction;
break;
case RIGHT:
if (sDirection != Direction.LEFT)
this.direction = direction;
break;
case UP:
if (sDirection != Direction.DOWN)
this.direction = direction;
break;
case DOWN:
if (sDirection != Direction.UP)
this.direction = direction;
break;
}
}
public boolean checkCollision(GameObject object)
{
for(GameObject part : snakeParts)
{
if (isAtSamePos(part, object))
return (true);
}
return (false);
}
public Direction getDirection()
{
return (this.direction);
}
private boolean isAtSamePos(GameObject item1, GameObject item2)
{
return (item1.x == item2.x && item1.y == item2.y);
}
}