Tic Tac Toe Game HTML

This is a simple Tic Tac Toe game using HTML, CSS and JavaScript.

HTML Code

<!DOCTYPE html>
<html>
  <head>
    <title>Tic Tac Toe Game</title>
    <style>
      /* Add your CSS code here */
    </style>
  </head>
  <body>
    <h1>Tic Tac Toe Game</h1>
    <table>
    	<tr>
    		<td id='0'></td>
    		<td id='1'></td>
    		<td id='2'></td>
    	</tr>
    	<tr>
    		<td id='3'></td>
    		<td id='4'></td>
    		<td id='5'></td>
    	</tr>
    	<tr>
    		<td id='6'></td>
    		<td id='7'></td>
    		<td id='8'></td>
    	</tr>
    </table>
    <div id='result'></div>
    <script>
        // Add your JavaScript code here
    </script>
  </body>
</html>

CSS Code

table {
	border-collapse: collapse;
}

td {
	border: 1px solid black;
	height: 50px;
	width: 50px;
	text-align: center;
	font-size: 30px;
	cursor: pointer;
}

#result {
	font-size: 20px;
	font-weight: bold;
	margin-top: 10px;
}

JavaScript Code

var turn = 1;
var board = ['', '', '', '', '', '', '', '', ''];

function mark(id) {
	var cell = document.getElementById(id);
	if (cell.innerHTML == '') {
		if (turn == 1) {
			cell.innerHTML = 'X';
			board[id] = 'X';
			turn = 2;
		} else {
			cell.innerHTML = 'O';
			board[id] = 'O';
			turn = 1;
		}
		checkResult();
	}
}

function checkResult() {
	if (board[0] != '' && board[0] == board[1] && board[1] == board[2]) {
		showResult(board[0]);
	} else if (board[3] != '' && board[3] == board[4] && board[4] == board[5]) {
		showResult(board[3]);
	} else if (board[6] != '' && board[6] == board[7] && board[7] == board[8]) {
		showResult(board[6]);
	} else if (board[0] != '' && board[0] == board[3] && board[3] == board[6]) {
		showResult(board[0]);
	} else if (board[1] != '' && board[1] == board[4] && board[4] == board[7]) {
		showResult(board[1]);
	} else if (board[2] != '' && board[2] == board[5] && board[5] == board[8]) {
		showResult(board[2]);
	} else if (board[0] != '' && board[0] == board[4] && board[4] == board[8]) {
		showResult(board[0]);
	} else if (board[2] != '' && board[2] == board[4] && board[4] == board[6]) {
		showResult(board[2]);
	} else if (board.indexOf('') == -1) {
		showResult('draw');
	}
}

function showResult(result) {
	var resultDiv = document.getElementById('result');
	if (result == 'draw') {
		resultDiv.innerHTML = 'It's a draw!';
	} else {
		resultDiv.innerHTML = 'Player ' + result + ' wins!';
	}
	resetBoard();
}

function resetBoard() {
	turn = 1;
	board = ['', '', '', '', '', '', '', '', ''];
	for (var i = 0; i < 9; i++) {
		document.getElementById(i).innerHTML = '';
	}
}

To play the game, simply open the HTML file in your web browser. Click on any cell to mark it with either 'X' or 'O'. The game will automatically determine the winner or if it's a draw. To start a new game, simply refresh the page.

Enjoy playing!

Tic Tac Toe Game HTML, CSS & JavaScript - Simple & Playable

原文地址: https://www.cveoy.top/t/topic/lnk6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录