In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

TicTacToe

When I'm bored I tend to waste my time making silly things
like TicTacToe or something.

Maybe we should see who can make the best (most efficient)
A.I. player?  Heh heh, that would be interesting.
Get Adobe Flash player
by PESakaTFM 16 Mar 2010
/**
When I'm bored I tend to waste my time making silly things
like TicTacToe or something.

Maybe we should see who can make the best (most efficient)
A.I. player?  Heh heh, that would be interesting.
**/

package
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;

	public class TicTacToe extends Sprite
	{
		private var board:Array;
		private var turn:int = 1;
		
		public function TicTacToe()
		{
			stage.addEventListener(MouseEvent.CLICK, onClick);
			
			initBoard();
		}
		
		private function onClick(event:MouseEvent):void
		{
			var i:int = mouseX/155 >> 0;
			var j:int = mouseY/155 >> 0;
			
			if(board[i][j] == 0)
			{
				board[i][j] = turn;
				if(turn == 1)
				{
					drawX(i,j);
					turn=2;
				}
				else
				{
					drawO(i,j);
					turn=1;
				}
			}
			
			var win:int = checkWin();
			if(win != 0)
			{
				trace(win);
			}
		}
		
		private function initBoard():void
		{
			board = [[0,0,0],[0,0,0],[0,0,0]];
			turn = 1;
			
			graphics.clear();
			graphics.lineStyle(6,0x0);
			for(var i:int = 1; i<=2; i++)
			{
				graphics.moveTo(155*i, 0);
				graphics.lineTo(155*i, 465);
				graphics.moveTo(0, 155*i);
				graphics.lineTo(465, 155*i);
			}
		}
		
		private function drawX(i:int, j:int):void
		{
			graphics.lineStyle(12, 0xFF0000);
			graphics.moveTo(155*i + 35, 155*j + 35);
			graphics.lineTo(155*i + 115, 155*j + 115);
			graphics.moveTo(155*i + 35, 155*j + 115);
			graphics.lineTo(155*i + 115, 155*j + 35);
		}
		
		private function drawO(i:int, j:int):void
		{
			graphics.lineStyle(12, 0x0000FF);
			graphics.drawCircle(155*i + 75, 155*j + 75, 40);
		}
		
		private function checkWin():int
		{
			for(var i:int = 0; i<3; i++)
			{
				if(board[i][0] != 0 
				&& board[i][0] == board[i][1] 
				&& board[i][0] == board[i][2])
					return board[i][0];
					
				if(board[0][i] != 0 
				&& board[0][i] == board[1][i] 
				&& board[0][i] == board[2][i])
					return board[0][i];
			}
			
			if(board[0][0] != 0 
			&& board[0][0] == board[1][1] 
			&& board[0][0] == board[2][2])
				return board[0][0];
				
			if(board[0][2] != 0 
			&& board[0][2] == board[1][1] 
			&& board[0][2] == board[2][0])
				return board[0][2];
				
			return 0;
		}
	}
}