Print Shortlink

TicTacToe using jQuery

Interacting with a bunch of developers this week gave me an idea to try out TicTacToe game using jQuery. An unformatted TicTacToe application implemented using jQuery is hosted in this URL.

The tictactoe.js file implemented using jQuery is shown below:

var currentPlayer = "X";

$().ready(function(){
	$("table td").css("width","150px").css("height","65px");
	$("#playBTN").on("click",playButtonClicked);
	$("table td").each(function(){
		$(this).on("click",function(){	play($(this)); 	});
	}); 	
});

function playButtonClicked(){
		$("#messageH2").html("");
		$(this).attr("disabled","disabled");
		currentPlayer = "X";
		$("table td").each(function(){
			$(this).text("");
		});
}
function play(cell){
	if(!isGameOver()){
		if(cell.text().trim() == "" && currentPlayer == "X")
		{
			cell.text("X");
			if(!isGameOver())
			{
				currentPlayer = "O";
				computerPlay();
			}
			else
				displayResults("X");
		}
	}
}
function displayResults(winner){
	$("#messageH2").text("Game Over. The winner is " + winner);
	$("#playBTN").removeAttr("disabled");
	currentPlayer = "X";
}
function computerPlay()
{
	//Logic can be changed for O
	$("table td").each(function(){
		if($(this).text().trim() == "" && currentPlayer == "O")
		{
			$(this).text("O");
			currentPlayer = "X";
			if(isGameOver())
				displayResults("O");
		}	
	});
}

function isGameOver()
{
	var row1Over = check("#col11,#col12,#col13");
	var row2Over = check("#col21,#col22,#col23");
	var row3Over = check("#col31,#col32,#col33");
	
	var col1Over = check("#col11,#col21,#col31");
	var col2Over = check("#col12,#col22,#col32");
	var col3Over = check("#col13,#col23,#col33");
	
	var dia1Over = check("#col11,#col22,#col33");
	var dia2Over = check("#col13,#col22,#col31");
	
	return row1Over || row2Over || row3Over || col1Over || col2Over || col3Over || dia1Over || dia2Over;
}
function check(cells)
{
	var gameOver = false;
	var valuesArr = [];
	$(cells).each(function(){
		if($(this).text().trim() != "")
			valuesArr.push($(this).text().trim());
	});
	if(valuesArr.length == 3)
	{
		if((valuesArr[0] == valuesArr[1]) && (valuesArr[1] == valuesArr[2]))
			gameOver = true;
	}
	return gameOver;
}
Page 1 of 1

One Response

  1. Vinoth

    Cool game Prabhu!! I enjoyed playing this,
    And the code looks so simple.. Great stuff!

Leave a Reply