# The scripts in this tutorial implement the famous minesweeper game
# STEP 2

class(minesweepermain,widget)
{
	constructor()
	{
		$$->$setCaption("KVIrc's Minesweeper (0.1.0)");

		$$->%rows = 10
		$$->%cols = 10
		$$->%mines = 10

		$$->%layout = $new(layout,$this)

		for(%i = 0;%i < $$->%rows;%i++)
		{
			for(%j = 0;%j < $$->%cols;%j++)
			{
				$$->%label{%i,%j}=$new(label,$this,"%i_%j")
				$$->%label{%i,%j}->%row = %i
				$$->%label{%i,%j}->%col = %j
				$$->%layout->$addWidget($$->%label{%i,%j},%i,%j)
			}
		}

		$$->$newGame()
	}

	newGame()
	{
		for(%i = 0;%i < $$->%rows;%i++)
		{
			for(%j = 0;%j < $$->%cols;%j++)
			{
				%l = $$->%label{%i,%j}
				%l->$setFrameStyle(Raised,WinPanel);
				%l->%bIsMine = 0
				%l->%numMines = 0
				%l->%bIsDiscovered = 0
				%l->$setText("")
			}
		}
		# Here we drop the mines around: it is a bit complex problem:
		# We want to have a fixed number of mines placed randomly in our grid
		# 
		# So .. for each mine that we have to place...
		for(%i = 0;%i < $$->%mines;%i++)
		{
			# Choose a random position for this mine
			%row = $rand($($$->%rows - 1))
			%col = $rand($($$->%cols - 1))
			# Ensure that we're not placing this mine over an existing one
			while($$->%label{%row,%col}->%bIsMine != 0)
			{
				# If there was already a mine, then choose the position again
				%row = $rand($($$->%rows - 1))
				%col = $rand($($$->%cols - 1))
			} 
			# Ok.. this is a mine then
			$$->%label{%row,%col}->%bIsMine = 1

			# increase the mine count for the adiacent cells: this is again a bit complex thingie
			if(%row > 0)
			{
				# There is a row over our mine: the cells above must have their mine count updated
				# The cell just above us
				$$->%label{$(%row - 1),%col}->%numMines++
				# The cell above on the left (if exists)
				if(%col > 0)$$->%label{$(%row - 1),$(%col - 1)}->%numMines++
				# The cell above on the right (if exists)
				if(%col < ($$->%cols - 1))$$->%label{$(%row - 1),$(%col + 1)}->%numMines++
			}
			if(%row < ($$->%rows - 1))
			{
				# There is a row below our mine: the cells below must have their mine count updated
				# The cell just below us
				$$->%label{$(%row + 1),%col}->%numMines++
				# The cell below on the left (if exists)
				if(%col > 0)$$->%label{$(%row + 1),$(%col - 1)}->%numMines++
				# The cell below on the right (if exists)
				if(%col < ($$->%cols - 1))$$->%label{$(%row + 1),$(%col + 1)}->%numMines++
			}
			# Now the cell on the left side (if exists)
			if(%col > 0)$$->%label{%row,$(%col - 1)}->%numMines++
			# And on the right side (if exists)
			if(%col < ($$->%cols - 1))$$->%label{%row,$(%col + 1)}->%numMines++
		}
	}
}

%m = $new(minesweepermain)
%m->$show()
