Gra w Kółko i Krzyżyk
Gra w Kółko i Krzyżyk napisana w JavaScript
Kółko i Krzyżyk to klasyczna gra logiczna, która od pokoleń dostarcza rozrywki i wyzwań intelektualnych zarówno dzieciom, jak i dorosłym. Proste zasady, szybka rozgrywka i możliwość gry w dowolnym miejscu sprawiają, że jest to jedna z najbardziej popularnych gier na świecie.
W grze dwóch graczy rywalizuje ze sobą, próbując jako pierwsi ułożyć linię trzech swoich symboli (kółek lub krzyżyków) na planszy 3×3. Kluczem do zwycięstwa jest nie tylko atak, ale i umiejętna obrona, by zablokować przeciwnika.
Dlaczego warto zagrać?
- 🧠 Trening dla umysłu – rozwija umiejętność planowania i logicznego myślenia.
- 🎮 Prosta rozgrywka – nie wymaga specjalnego przygotowania ani skomplikowanego sprzętu.
- 🤖 Tryb z AI – w wersji cyfrowej możesz zmierzyć się z inteligentnym przeciwnikiem, który uczy się Twoich strategii.
Czy potrafisz pokonać przeciwnika lub sztuczną inteligencję? Podejmij wyzwanie i udowodnij, że jesteś mistrzem strategii! 😎
Struktura projektu
- HTML: Plansza gry i przyciski.
- CSS: Prosty styl planszy.
- JavaScript: Obsługa logiki gry i AI.
Kod Gry:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <!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> <style> body { font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; margin: 0; background-color: #f4f4f4; } .board { display: grid; grid-template-columns: repeat(3, 100px); grid-gap: 5px; } .cell { width: 100px; height: 100px; display: flex; align-items: center; justify-content: center; background: #fff; border: 1px solid #ddd; font-size: 2rem; cursor: pointer; } .cell.taken { cursor: not-allowed; } .status { margin: 20px; font-size: 1.2rem; } .buttons { margin-top: 10px; } button { margin: 5px; padding: 10px 20px; font-size: 1rem; cursor: pointer; } </style> </head> <body> <h1>Tic-Tac-Toe</h1> <div class="status">Your turn: X</div> <div class="board"></div> <div class="buttons"> <button onclick="startGame('player')">Two Players</button> <button onclick="startGame('ai')">Play vs AI</button> </div> <script src="script.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | const boardElement = document.querySelector('.board'); const statusElement = document.querySelector('.status'); let board = []; let currentPlayer = 'X'; let gameMode = 'player'; // 'player' or 'ai' let isGameOver = false; // Initialize the game function startGame(mode) { board = Array(9).fill(null); currentPlayer = 'X'; gameMode = mode; isGameOver = false; statusElement.textContent = "Twoja kolej: X"; renderBoard(); } // Render the board function renderBoard() { boardElement.innerHTML = ''; board.forEach((cell, index) => { const cellElement = document.createElement('div'); cellElement.className = `cell ${cell ? 'taken' : ''}`; cellElement.textContent = cell || ''; cellElement.addEventListener('click', () => handleMove(index)); boardElement.appendChild(cellElement); }); } // Handle a player's move function handleMove(index) { if (board[index] || isGameOver) return; board[index] = currentPlayer; if (checkWinner(currentPlayer)) { statusElement.textContent = `${currentPlayer} zwyciężył!`; isGameOver = true; } else if (board.every(cell => cell)) { statusElement.textContent = "Uzyskano Remis!"; isGameOver = true; } else { currentPlayer = currentPlayer === 'X' ? 'O' : 'X'; statusElement.textContent = `Twoja kolej: ${currentPlayer}`; if (gameMode === 'ai' && currentPlayer === 'O') aiMove(); } renderBoard(); } // Check for a winner function checkWinner(player) { const winningCombos = [ [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 ]; return winningCombos.some(combo => combo.every(index => board[index] === player) ); } // AI move logic // AI move logic with Minimax function aiMove() { let bestMove = null; let bestScore = -Infinity; for (let i = 0; i < board.length; i++) { if (!board[i]) { board[i] = 'O'; // Simulate AI move let score = minimax(board, 0, false); // Evaluate the move board[i] = null; // Undo the move if (score > bestScore) { bestScore = score; bestMove = i; } } } board[bestMove] = 'O'; if (checkWinner('O')) { statusElement.textContent = "O wygrało!"; isGameOver = true; } else if (board.every(cell => cell)) { statusElement.textContent = "Uzyskano Remis!"; isGameOver = true; } else { currentPlayer = 'X'; statusElement.textContent = `Twoja kolej: ${currentPlayer}`; } renderBoard(); } // Minimax algorithm function minimax(board, depth, isMaximizing) { if (checkWinner('O')) return 10 - depth; // Favor quicker wins if (checkWinner('X')) return depth - 10; // Favor delaying opponent wins if (board.every(cell => cell)) return 0; // Draw if (isMaximizing) { let maxEval = -Infinity; for (let i = 0; i < board.length; i++) { if (!board[i]) { board[i] = 'O'; let eval = minimax(board, depth + 1, false); board[i] = null; maxEval = Math.max(maxEval, eval); } } return maxEval; } else { let minEval = Infinity; for (let i = 0; i < board.length; i++) { if (!board[i]) { board[i] = 'X'; let eval = minimax(board, depth + 1, true); board[i] = null; minEval = Math.min(minEval, eval); } } return minEval; } } // Start with an empty game startGame('player'); |
Jak działa AI?
- AI próbuje najpierw znaleźć ruch, który da mu wygraną.
- Jeśli nie znajdzie takiego ruchu, próbuje zablokować wygraną przeciwnika.
- W przeciwnym razie wybiera losowy dostępny ruch.
Rozbudowane AI z Minimax
Wprowadźmy następujące usprawnienia:
- Algorytm Minimax: AI analizuje każdy możliwy ruch i jego konsekwencje.
- Ocena planszy: AI ocenia planszę, przypisując wartości:
- +10, jeśli AI (O) wygrywa.
- -10, jeśli gracz (X) wygrywa.
- 0, jeśli wynik jest remisowy.
- Rekursja: Algorytm sprawdza każdą możliwą kombinację ruchów.
Funkcje Gry
- Tryb Dla Dwóch Graczy: Gracze na zmianę wykonują ruchy.
- Tryb Z AI: Gracz gra przeciwko prostemu AI.
- Sprawdzanie Wygranej: Gra automatycznie kończy się, gdy jeden z graczy wygra lub gdy zabraknie miejsca na planszy.


