var moveDeltas=[ // all the deltas for possible knight moves
	coord(1, 2),
	coord(2, 1),
	coord(-1, 2),
	coord(-2, 1),
	coord(1, -2),
	coord(2, -1),
	coord(-1, -2),
	coord(-2, -1)
];

function gameOver(map,piece){
	for(i in moveDeltas){
		var dest=coord(piece.x+moveDeltas[i].x,
				piece.y+moveDeltas[i].y);
		if(legalp(piece,dest,map))return false;
	}
	return true;
}

function inbounds(x,y){
	return (x>=0 && x<8 && y>=0 && y<8);
}

function wallp(map,c){
	if(!inbounds(c.x,c.y))return true;
	return map.spaces[c.x][c.y]=='black';
}

function setup(window){
	var spaces=0;
	var knight=new Piece('red');
	window.map=new Map(8,8);
	window.map.place(knight,0,0);
	window.map.onclick=function(x,y){
		if(legalp(knight,coord(x,y),window.map)){
			window.map.spaces[knight.x][knight.y]='black';
			spaces++;
			knight.move(x,y);
			if(gameOver(window.map,knight)){
				print("--G A M E  --  O V E R--")
				print("You got a score of "+spaces+" spaces.");
				print("Click on the piece to play again!");
				knight.onclick=function(){setup(window);};
			}
		}
	}
}

function delta(a,b){
	return Math.abs(a-b);
}

function unitVector(coordA,coordB){
	return {
		x:(coordA.x<coordB.x?1:
			coordA.x>coordB.x?-1:
			0),
		y:(coordA.y<coordB.y?1:
			coordA.y>coordB.y?-1:
			0)
	};
}

function coord(x,y){
	return {x:x,y:y};
}

function not(b){return !b;}

function legalp(piece,dest,map){
	if(wallp(map,piece) || wallp(map,dest))return false;

	var unit=unitVector(piece,dest);
	
	if(delta(piece.x,dest.x)==1 && delta(piece.y,dest.y)==2){
		return !(wallp(map,coord(piece.x,piece.y+unit.y)) &&
			wallp(map,coord(piece.x+unit.x,piece.y+unit.y)));
	} else if(delta(piece.x,dest.x)==2 && delta(piece.y,dest.y)==1){
		return not(
			wallp(map,coord(piece.x+unit.x,piece.y)) &&
			wallp(map,coord(piece.x+unit.x,piece.y+unit.y)));
	} else return false;
}


setup(Window)

print("The red piece moves like a knight.");
print("Click to move it. Anywhere it moves away from becomes a wall.");
print("Try to cover as much of the board in walls as you can!");