Okay, this is a substantial project! Here's a breakdown of the code, along with explanations, and a focus on making it visually appealing and configurable. I'll provide the HTML, CSS, and JavaScript. I'll also include explanations of the key concepts.
Important Considerations:
- CSS-Only Visuals: We'll use CSS for the board, pieces, and overall styling. This is where the "stunning" part comes in.
- JavaScript Logic: JavaScript will handle the game logic (player turns, AI moves, win detection, etc.).
- AI Difficulty: I'll implement a basic AI that makes random valid moves. You can expand on this to create more intelligent AI (Minimax, etc.).
- Configurable Settings: We'll add options to change the player symbols (X/O or other characters), board colors, and potentially AI difficulty.
- Responsiveness: The game will be responsive to different screen sizes.
1. HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic-Tac-Toe</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Tic-Tac-Toe</h1>
<div class="settings">
<label for="playerSymbol">Player Symbol:</label>
<input type="text" id="playerSymbol" value="X" maxlength="1">
<label for="aiSymbol">AI Symbol:</label>
<input type="text" id="aiSymbol" value="O" maxlength="1">
<label for="boardColor">Board Color:</label>
<input type="color" id="boardColor" value="#f0f0f0">
</div>
<div id="board">
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<div id="message"></div>
<button id="resetButton">Reset Game</button>
</div>
<script src="script.js"></script>
</body>
</html>
Explanation:
container: The main wrapper for the game.
settings: Holds the configuration options.
playerSymbol, aiSymbol: Input fields for the player and AI symbols.
boardColor: Color picker for the board background.
board: The Tic-Tac-Toe grid. Each cell has a data-index attribute to identify its position.
message: Displays game messages (e.g., "Player X's turn", "AI wins!", "Draw").
resetButton: Resets the game.
script.js: The JavaScript file containing the game logic.
2. CSS (style.css)
body {
font-family: sans-serif;
background-color: #eee;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
width: 400px;
}
.settings {
margin-bottom: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
.settings label {
margin-bottom: 5px;
}
.settings input {
padding: 5px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 5px;
margin: 0 auto;
background-color: #f0f0f0; /* Default board color */
padding: 10px;
border-radius: 5px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
border: 2px solid #ccc;
border-radius: 5px;
font-size: 4em;
text-align: center;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
.cell:hover {
background-color: #eee;
}
#message {
margin-top: 20px;
font-weight: bold;
}
#resetButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
#resetButton:hover {
background-color: #3e8e41;
}
/* Responsive Design */
@media (max-width: 600px) {
.container {
width: 90%;
}
#board {
grid-template-columns: repeat(3, 80px);
}
.cell {
width: 80px;
height: 80px;
font-size: 3em;
}
}
Explanation:
- Basic Styling: Sets up the overall look and feel.
container: Styles the main game container.
board: Creates the grid layout for the Tic-Tac-Toe board using CSS Grid.
cell: Styles each cell of the board. The cursor: pointer makes the cells clickable.
message: Styles the message area.
resetButton: Styles the reset button.
- Responsive Design: The
@media query adjusts the layout for smaller screens.
3. JavaScript (script.js)
const board = document.getElementById('board');
const cells = document.querySelectorAll('.cell');
const message = document.getElementById('message');
const resetButton = document.getElementById('resetButton');
const playerSymbolInput = document.getElementById('playerSymbol');
const aiSymbolInput = document.getElementById('aiSymbol');
const boardColorInput = document.getElementById('boardColor');
let currentPlayer = 'X';
let aiPlayer = 'O';
let boardState = ['', '', '', '', '', '', '', '', ''];
let gameActive = true;
// Function to update the board color
function updateBoardColor() {
const color = boardColorInput.value;
board.style.backgroundColor = color;
}
// Event listener for board color changes
boardColorInput.addEventListener('input', updateBoardColor);
// Function to handle cell clicks
function cellClicked(event) {
const index = event.target.dataset.index;
if (boardState[index] === '' && gameActive) {
boardState[index] = currentPlayer;
event.target.textContent = currentPlayer;
if (checkWin()) {
message.textContent = `Player ${currentPlayer} wins!`;
gameActive = false;
} else if (checkDraw()) {
message.textContent = 'It\'s a draw!';
gameActive = false;
} else {
currentPlayer = aiPlayer;
aiMove();
}
}
}
// AI Move Function (Random)
function aiMove() {
const availableCells = boardState.reduce((acc, val, index) => {
if (val === '') {
acc.push(index);
}
return acc;
}, []);
if (availableCells.length > 0) {
const randomIndex = Math.floor(Math.random() * availableCells.length);
const index = availableCells[randomIndex];
boardState[index] = aiPlayer;
cells[index].textContent = aiPlayer;
if (checkWin()) {
message.textContent = `Player ${aiPlayer} wins!`;
gameActive = false;
} else if (checkDraw()) {
message.textContent = 'It\'s a draw!';
gameActive = false;
} else {
currentPlayer = 'X';
}
}
}
// Win Check Function
function checkWin() {
const winConditions = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
[0, 4, 8], [2, 4, 6] // Diagonals
];
for (const condition of winConditions) {
const [a, b, c] = condition;
if (boardState[a] !== '' && boardState[a] === boardState[b] && boardState[b] === boardState[c]) {
return true;
}
}
return false;
}
// Draw Check Function
function checkDraw() {
return !boardState.includes('');
}
// Reset Game Function
function resetGame() {
boardState = ['', '', '', '', '', '', '', '', ''];
currentPlayer = 'X';
aiPlayer = 'O';
gameActive = true;
message.textContent = '';
cells.forEach(cell => {
cell.textContent = '';
});
}
// Event Listeners
cells.forEach(cell => {
cell.addEventListener('click', cellClicked);
});
resetButton.addEventListener('click', resetGame);
// Update player and AI symbols
playerSymbolInput.addEventListener('input', () => {
currentPlayer = playerSymbolInput.value;
});
aiSymbolInput.addEventListener('input', () => {
aiPlayer = aiSymbolInput.value;
});
Explanation:
- Variables: Stores the game state (board, current player, etc.).
cellClicked(): Handles clicks on the board cells. It updates the board state, displays the player's symbol, checks for a win or draw, and switches to the AI's turn.
aiMove(): Implements the AI's move (currently random).
checkWin(): Checks if the current player has won.
checkDraw(): Checks if the game is a draw.
resetGame(): Resets the game to its initial state.
- Event Listeners: Attaches event listeners to the cells and the reset button.
- Symbol and Color Updates: Event listeners update the player and AI symbols and board color when the input fields change.
How to Run:
- Save the HTML as
index.html.
- Save the CSS as
style.css.
- Save the JavaScript as
script.js.
- Open
index.html in your web browser.
Key Improvements and Further Development:
- AI Improvement: Implement a more sophisticated AI algorithm (Minimax is a common choice).
- Difficulty Levels: Add options to control the AI's difficulty.
- Custom Symbols: Allow players to choose any character as their symbol.
- Animations: Add animations for moves and win/draw conditions.
- Sound Effects: Add sound effects for clicks, wins, and draws.
- Accessibility: Make the game accessible to users with disabilities.
- More Styling: Experiment with different CSS properties to create a more visually appealing design. Consider using gradients, shadows, and custom fonts.
- Local Storage: Save game settings (symbols, colors) to local storage so they persist between sessions.
This provides a solid foundation for a stunning and configurable Tic-Tac-Toe game. Let me know if you'd like help with any of the improvements or have specific questions about the code.