package edu.compsci;

import cs1.android.*;

// Implementation of a 1D variant of the Lights Out game.
// Hit a light to toggle it and its neighbors. the goal
// is to turn off all the lights.

public class LightsOutApp extends AndroidApp
{
	// board's upper-left corner and cell size
	final int BASE_Y = 160; // 320x480 device in landscape mode
	final int LIGHT_WIDTH = 40;

	public void drawLights(String[] lights)
	{
		//canvas.clear();
		int x = LIGHT_WIDTH / 2;
		for (int i = 0; i < lights.length; ++i) {
			canvas.drawImage(x, BASE_Y, lights[i]);
			x = x + LIGHT_WIDTH;
		}
	}

	// Check if at least one light is on
	public boolean isLightOn(String[] lights)
	{
		for (int i = 0; i < lights.length; ++i) {
			if (lights[i] == "on.png") {
				return true;
			}
		}
		return false;
	}

	public void toggleLight(int i, String[] lights)
	{
		if (i < 0 || i >= lights.length) { return; }
		if (lights[i].equals("on.png"))  { lights[i] = "off.png"; }
		else                             { lights[i] = "on.png"; }
	}

	public void run() 
	{	
		canvas.setBackground("DarkKhaki");

		String[]  lights = {
				"on.png", "on.png", "on.png", "on.png",
				"on.png", "on.png", "on.png", "on.png",
				"on.png", "on.png", "on.png", "on.png"
		};

		canvas.drawText(canvas.getWidth()/2, canvas.getHeight()/8, 
				"Touch a light to toggle", 24, "white");

		while ( isLightOn(lights) ) {
			drawLights(lights);

			Touch touch = canvas.waitForTouch();
			int i = touch.getX() / LIGHT_WIDTH;

			toggleLight(i+1, lights);
			toggleLight(i,   lights);
			toggleLight(i-1, lights);
		}
		canvas.clear();
		drawLights(lights);
		canvas.drawText(canvas.getWidth()/2, canvas.getHeight()/8, 
				"Well done!", 24, "white");			
	}
}