if(!gameField[y][x].isMine){//if a cell has no mine
for(GameObject cell : getNeighbors(gameField[y][x]))//I do not understand this part
if(cell.isMine) cell.countMineNeighbors++;//if a cell has a mine
//return the number of mines adjacent to this cell? I do not understand how this works
}
I am buiding this game for the second time and I still do not understand how this part works. I just copied the code from someone else....
Can someone please enlighten me?
package com.codegym.games.minesweeper;
//import com.codegym.engine.cell.*;
public class GameObject {
public int x;
public int y;
public boolean isMine;
public int countMineNeighbors;
public GameObject ( int x, int y, boolean isMine){
this.x = x;
this.y = y;
this.isMine = isMine;
}
}
Line 62:
for(GameObject cell : getNeighbors(gameField[y][x]))
you have to consider that getNeighbors(gamefield[y][x]) returns a List of GameObjects (as you can see by the declaration of the getNeighbors method:private List<GameObject> getNeighbors(GameObject gameObject)
The for each is
for(GameObject cell : getNeighbors(gameField[y][x]))
It means that on the first pass, you declare a new GameObject variable called cell and you set it equal to the first element of the collection(it's equivalent to
GameObject cell = listElementAtIndex(0);
) and you use the variable cell inside the cycle. In the second pass, you still use the variable cell but this time it will be equals to the second element of the collection, likeGameObject cell = listElementAtIndex(1);
and so on, until it reach the end of the collection. I hope this help you