let board = [];
let px = Math.floor(Math.random() * 8);
let py = Math.floor(Math.random() * 8); 
let alt = false;
let size = 0;
let horse;
let jogadas = 1;

function preload() {
	horse = loadImage('horse.png');
}

function setup() {
	

	var h = document.createElement("h1");
	h.innerText = "Jogadas: 1/64";
	main = document.querySelector("main");
	main.appendChild(h);

	if (windowWidth < windowHeight) {
		createCanvas(windowWidth/1.5, windowWidth/1.5);
		size = windowWidth/1.5;
	} else {
		createCanvas(windowWidth/3, windowWidth/3);
		size = windowWidth/3;		
	}
	for (var x = 0; x < 8; x++) {
		board[x] = [];
		for (var y = 0; y < 8; y++) {
			board[x][y] = false;
		}
	}

	ellipseMode(CORNER);
}

function windowResized() {
	if (windowWidth < windowHeight) {
		resizeCanvas(windowWidth/1.5, windowWidth/1.5);
		size = windowWidth/1.5;
	} else {
		resizeCanvas(windowWidth/3, windowWidth/3);
		size = windowWidth/3;		
	}
}

function draw() {

	noStroke();
	
	for (var x = 0; x < 8; x++) {
		alt = !alt;
		for (var y = 0; y < 8; y++) {
			alt = !alt;
			if (board[x][y]) {
				fill(200, 10, 10);
			} else {
				if (alt) {
					fill(255);
				} else {
					fill(100);
				}
			}

			if (isPossible(x, y)) {
				fill(0, 255, 0);
			}

			rect(x*(size/8), y*(size/8), (size/8), (size/8));
		}
	}

	image(horse, px*(size/8), py*(size/8), (size/8), (size/8));

	stroke(80);
	strokeWeight(4);
	noFill();
	rect(0, 0, size, size);
}

function mouseReleased() {
	if (mouseX > 0 && mouseX < size && mouseY > 0 && mouseY < size) {

		if (isPossible(Math.floor(mouseX / (size/8)), Math.floor(mouseY / (size/8)))) {
			board[px][py] = true;
			jogadas++;
			document.querySelector("main > h1").innerText = "Jogadas: "+jogadas+"/64";
			px = Math.floor(mouseX / (size/8));
			py = Math.floor(mouseY / (size/8));
		}
	}
}

function isPossible(tx, ty) {
	if (!board[tx][ty]) {
		if (px + 1 == tx && py + 2 == ty){
			return true;
		}

		if (px + 1 == tx && py - 2 == ty){
			return true;
		}

		if (px + 2 == tx && py + 1 == ty){
			return true;
		}

		if (px + 2 == tx && py - 1 == ty){
			return true;
		}


		if (px - 1 == tx && py + 2 == ty){
			return true;
		}

		if (px - 1 == tx && py - 2 == ty){
			return true;
		}

		if (px - 2 == tx && py + 1 == ty){
			return true;
		}

		if (px - 2 == tx && py - 1 == ty){
			return true;
		}
	}
}

function drawPossible() {

}