/*
Game.cpp
By Dan Ricart
Contains functions for the main game class for the eight queens demo
*/

#include <stdio.h>
#include "Game.h"

Game::Game()
{
}

Game::~Game()
{
}

//set up a new game and clear the board
void Game::NewGame()
{
	int i, j;
	numqueens=0;
	for (i=0; i<8; i++)
	{
		for (j=0; j<8; j++)
		{
			board[i][j] = 0;
		}
	}
}

//check to see if another queen is in this row
int Game::CheckRow(int row)
{
	int i;
	for (i=0; i<8; i++)
	{
		if (board[row][i]==1)
			return(1);
	}
	return(0);
}

//check to see if another queen is in this column
int Game::CheckColumn(int col)
{
	int i;
	for (i=0; i<8; i++)
	{
		if (board[i][col]==1)
			return(1);
	}
	return(0);
}

//check to see if another queen is diagonally from the current spot
int Game::CheckDiagonal(int col, int row)
{
	int i, loopnum;

	int sx, sz;
	//go up to the right first

	//use the smaller of the two numbers
	if (col<=row)
	{
		sx=0;
		sz=row-col; //move down however many rows
		loopnum=8-sz;
	}
	else
	{
		sx=col-row;
		sz=0;
		loopnum=8-sx;
	}

	for (i=0; i<loopnum; i++)
	{
		if (board[sz][sx]==1)
			return(1);

		sx++;
		sz++;
	}

	//now find the bottom right corner

	int n1, n2;
	n1 = col+row;
	n2 = row-(7-col);

	if ((n1>=0) && (n1<=7))
	{
		sx = n1;
		sz = 0;
		loopnum = n1+1;
	}
	else
	{
		sx = 7;
		sz = n2;
		loopnum = 8-n2;
	}

	for (i=0; i<loopnum; i++)
	{
		if (board[sz][sx]==1)
			return(1);

		sx--;
		sz++;
	}

	return(0);

}

int Game::PlaceQueen(int x, int y)
{
	//first check to see if anything is on this space
	//if yes, remove it
	if (board[y][x]==1)
	{
		board[y][x]=0;
		numqueens--;
		return(0);
	}


	//next check for queens in positions that would block our move
	if ((CheckRow(y)==0) && (CheckColumn(x)==0) && (CheckDiagonal(x,y)==0))
	{
		//no interferring queens found so place the queen
		board[y][x]=1;
		numqueens++;
	}


	//if there are 8 queens, the game is over
	if (numqueens==8)
		return(1);

	return(0);
}

//check for a queen at this spot
int Game::CheckForQueen(int x, int y)
{
	if (board[y][x]==1)
		return(1);
	
	return(0);
}

//check to see if the game is over
int Game::GameStatus()
{
	if (numqueens==8)
		return(1);
	
	return(0);
}