Tic-Tac-Toe Gamepad Sample Program

' This is not a full Tic-Tac-Toe game
' This is just a gamepad so that 2 persons can play together

program "Tic-Tac-Toe Gamepad"

$Field = null
$Iteration = 1
SetLineWidth(5)

function GameSize()
	GameSize = min(GetWidth(), GetHeight())
end function

function GameCellSize()
	GameCellSize = GameSize () / 3
end function

function GameStartX()
	GameStartX = (GetWidth() - GameSize()) / 2
end function

function GameStartY()
	GameStartY = (GetHeight() - GameSize()) / 2
end function

function GameClearField()
	for i=1 to 3
		for j=1 to 3
			$Field[i][j] = null
		next
	next
end function

function GameSetCell(x, y, val)
	$Field[x][y] = val
	
	for dx = -1 to 1
		for dy = -1 to 1
			if dx <> 0 or dy <> 0
				
				n=0
				for i=-2 to 2
					x1 = x + i * dx
					y1 = y + i * dy
					if $Field[x1][y1] = val
						n=n+1
					end if
				next
				
				if n=3
					$Iteration = 9
					for i=-2 to 2
						x1 = x + i * dx
						y1 = y + i * dy
						$Field[x1][y1] = LCase(val)
					next					
				end if
				
			end if
		next
	next
	
	$Iteration = $Iteration + 1
	GameDraw ()	
end function

function GameDraw()
	ClearScreen()
	SetColor ("white")
	SetFontSize(GameSize() / 6)
	DrawLine(GameStartX() + GameCellSize(), GameStartY(), GameStartX() + GameCellSize(), GameStartY() + GameSize() + 1)
	DrawLine(GameStartX() + GameCellSize() * 2, GameStartY(), GameStartX() + GameCellSize() * 2, GameStartY() + GameSize() + 1)
	DrawLine(GameStartX(), GameStartY() + GameCellSize(), GameStartX() + GameSize() + 1, GameStartY() + GameCellSize())
	DrawLine(GameStartX(), GameStartY() + GameCellSize() * 2, GameStartX() + GameSize() + 1, GameStartY() +  + GameCellSize() * 2)
	
	for i=1 to 3
		for j=1 to 3
			
			sText = $Field[i][j]
			if sText = null
				sText = " "
			end if
			
			sTextUC = UCase(sText)
			if sText = sTextUC
				if sText = "X"
					SetColor ("yellow")
				elseif sText = "O"
					SetColor ("green")
				end if
			else
				SetColor ("red")
			end if
			
			x = GameStartX() + (i-0.5)*GameCellSize() - GetTextWidth(sTextUC) / 2
			y = GameStartY() + (j-0.5)*GameCellSize() - GetTextHeight(sTextUC) / 2				
			DrawText(Round(x), Round(y), UCase(sTextUC))
			
		next
	next
end function

function OnMouseUp(x, y)
	if $Iteration = 10
		GameClearField ()
		$Iteration = 1
		GameDraw ()
		exit function
	end if
	
	if x < GameStartX() + GameCellSize ()
		CellX = 1
	elseif x > GameStartX() + GameCellSize () * 2
		CellX = 3
	else
		CellX = 2
	end if
	
	if y < GameStartY() + GameCellSize ()
		CellY = 1
	elseif y > GameStartY() + GameCellSize () * 2
		CellY = 3
	else
		CellY = 2
	end if
	
	if $Field[CellX][CellY] <> null
		exit function
	end if
	
	if $Iteration % 2 = 1
		sText = "X"
	else
		sText = "O"
	end if
	
	GameSetCell(CellX, CellY, sText)
end function

function OnSize()
	GameDraw()
end function

GameDraw()