Bila shaka! Hapa kuna mfano wa jinsi unavyoweza kuandika mchezo wa Tic Tac Toe kwa kutumia HTML na JavaScript kwa lugha ya Kiswahili:
```html
<!DOCTYPE html>
<html lang="sw">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
gap: 5px;
margin-top: 20px;
}
.cell {
width: 100px;
height: 100px;
font-size: 24px;
border: 1px solid #ccc;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Mchezo wa Tic Tac Toe</h1>
<div id="board"></div>
<p id="status"></p>
<script>
// Hali ya mchezo
let board = ['', '', '', '', '', '', '', '', ''];
let currentPlayer = 'X';
let gameActive = true;
// Elementi
const boardElement = document.getElementById('board');
const statusElement = document.getElementById('status');
// Unda ubao wa mchezo
for (let i = 0; i < 9; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.index = i;
cell.addEventListener('click', handleCellClick);
boardElement.appendChild(cell);
}
// Fungua kushughulikia bonyeza la kiini
function handleCellClick(event) {
const index = event.target.dataset.index;
// Angalia kama kiini tayari kimejazwa au mchezo umekwisha
if (board[index] !== '' || !gameActive) {
return;
}
// Sasisha ubao na angalia mshindi
board[index] = currentPlayer;
updateBoard();
const winner = checkWinner();
// Onyesha mshindi au badilisha wachezaji
if (winner) {
statusElement.textContent = `${winner} ameshinda!`;
gameActive = false;
} else if (board.every(cell => cell !== '')) {
statusElement.textContent = 'Ni sare!';
gameActive = false;
} else {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
statusElement.textContent = `Mchezaji wa Sasa: ${currentPlayer}`;
}
}
// Sasisha uwakilishi wa ubao wa mchezo
function updateBoard() {
board.forEach((value, index) => {
const cell = boardElement.children[index];
cell.textContent = value;
});
}
// Angalia mshindi
function checkWinner() {
const winPatterns = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Safu
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Staha
[0, 4, 8], [2, 4, 6] // Duara
];
for (const pattern of winPatterns) {
const [a, b, c] = pattern;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
highlightWinnerCells(pattern);
return board[a];
}
}
return null;
}
// Weka rangi ya kiini cha mshindi
function highlightWinnerCells(cells) {
for (const index of cells) {
const cell = boardElement.children[index];
cell.style.backgroundColor = '#8eff8e'; // Rangi ya kijani mwanga
}
}
</script>
</body>
</html>