Home > Mobile >  Create arraylist of availableCoordinates
Create arraylist of availableCoordinates

Time:06-02

I am currently making a snake game and I don't want the apple to spawn inside my snake. I tried to fix this by doing this:


    ArrayList<Coordinate> availableCoordinates = new ArrayList<>();

    public void Coordinates() {


        for (int i = 0; i < numberOfSquaresY; i  ) {
            for (int j = 0; j < numberOfSquaresX; j  ) {
                availableCoordinates.add(new Coordinate(j*squareSize, i*squareSize, snake.get(0).color));
            }
        }

        for(int i = 0; i < availableCoordinates.size()-1; i  ) {
            for (int j = 0; j < snake.size() - 1; j  ) {
                if (availableCoordinates.get(i).xPos == snake.get(j).xPos && availableCoordinates.get(i).yPos == snake.get(j).yPos){
                    availableCoordinates.remove(i);
                }
            }
        }

    }

However only 1 value is getting removed even though it should be 3 that are getting removed, and I don't know why.

CodePudding user response:

You iterate over availableCoordinates and inside this loop you remove items from it. So after you removed an element the following elements get a new index. The loop index is incremented anyways so you jump over an element after removing.

I would not add all coordinates to the list and then remove the used ones. While filling your availableCoordinates check if this field is free:

for (int i = 0; i < numberOfSquaresY; i  ) {
    for (int j = 0; j < numberOfSquaresX; j  ) {
        Coordinate c = new Coordinate(j*squareSize, i*squareSize, snake.get(0).color);
        if (!snake.contains(c)) {
            availableCoordinates.add(c);
        }
    }
}

assuming that Coordinate#equals only checks xPos and yPos.

CodePudding user response:

Use removeIf() to remove from the list.

import java.util.ArrayList;
import java.util.List;

public class RemoveItemsFromListIfPresentInAnotherList {
    public static void main(String[] args) {
        List<Coordinate> availableCoords = new ArrayList<>();
        List<Coordinate> snakeCoords = new ArrayList<>();
        
        //..

        for (Coordinate snakeCoordinate : snakeCoords) {
            availableCoords.removeIf(availableCoord ->
                    (snakeCoordinate.getX() == availableCoord.getX() && snakeCoordinate.getY() == availableCoord.getY()));
        }
    }
}

class Coordinate {
    private int x;
    private int y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}
  • Related