import java.util.*;
public class LightsOutGame {

	public static void displayGrid(Grid grid, boolean[][] lightArray) 
	{
		// updates grid display based on data in game array
		grid.setLineColor(new Color(255,255,255));
		for (int i = 0; i < grid.getNumRows(); i++) {
			for (int j = 0; j < grid.getNumCols(); j++) {
				grid.setColor(new Location(i,j), getColor(lightArray[i][j]));
			}
		}	
	}
	
	public static Color getColor(boolean isOn) {
		if (isOn)
			return new Color(255,255,0);
		else
			return new Color(0,0,0);
	}
	
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		int size;
		do {
			System.out.println("Input the size of the game board (5 or more): ");
			size = scan.nextInt();
		} while (size < 5);
		
		Grid display = new Grid(size, size);
		display.setTitle("Lights Out");
		
		// Two-dimensional array to hold 
		boolean[][] game = new boolean[size][size];
		boolean gameOver = false;
		
		generateNewGame(game);
		displayGrid(display, game);

		while (!gameOver) {
			Grid.pause(50);
			Location loc = display.checkLastLocationClicked();
			if (loc != null) {
				int row = loc.getRow();
				int col = loc.getCol();
				toggleLights(game, row, col);
				gameOver = checkGameForWin(game);
			}
			displayGrid(display,game);
		}
		
		System.out.println("YOU WIN!");
		for (int i = 0; i < size; i++) {
			toggleAllLights(game);
			displayGrid(display,game);
			Grid.pause(100);
			toggleAllLights(game);
			displayGrid(display,game);
			Grid.pause(100);
		}
	
	}
	
	public static void generateNewGame(boolean[][] game) {
		for (int row = 0; row < game.length; row++) {
			for (int col = 0; col < game.length; col++) {
				int randNum = (int)(Math.random()*2);
				if (randNum == 1)
					game[row][col] = true;
				else
					game[row][col] = false;
			}
		}
	}

	public static void toggleLights(boolean[][] game, int row, int col) {
		game[row][col] = !game[row][col];
		if (row > 0)
			game[row-1][col] = !game[row-1][col];
		if (col > 0)
			game[row][col-1] = !game[row][col-1];
		if (row < game.length-1)
			game[row+1][col] = !game[row+1][col];
		if (col < game.length-1)
			game[row][col+1] = !game[row][col+1];
	}
	
	public static void toggleAllLights(boolean[][] game) {
		for (int row = 0; row < game.length; row++) {
			for (int col = 0; col < game.length; col++) {
				game[row][col] = !game[row][col];
			}
		}
	}
	
	public static boolean checkGameForWin(boolean[][] game) {
		for (int row = 0; row < game.length; row++) {
			for (int col = 0; col < game.length; col++) {
				if (game[row][col] == true)
					return false;
			}
		}
		return true;
	}
	
}

