Tic-Tac-Toe

عمل لعبة XO باستخدام javascript و html و css

تُعدّ كتابة أكواد الألعاب من المجالات الشيقة والممتعة في عالم البرمجة، حيث تسمح للمبرمجين بتحويل أفكارهم الإبداعية إلى تطبيقات تفاعلية تجذب المستخدمين. ولعبة XO (Tic-Tac-Toe) من الألعاب البسيطة والممتعة التي تُعدّ خيارًا مثاليًا للمبتدئين لتعلم أساسيات كتابة أكواد الألعاب.

عمل لعبة XO باستخدام javascript و html و css

ملف index.html

  • في ملف HTML، نقوم بإنشاء الهيكل الأساسي للصفحة. نضع اللوحة لعبة “X و O” في <div> مع id="board".
  • كل خلية في اللوحة ممثلة بوحدة <div> مع class="cell" و data-cell كخاصية تحديد.
  • لدينا أيضًا عنصر <div> لعرض رسالة اللعبة (<div id="message" class="message"></div>)
  • وزر إعادة اللعب (<button id="restartButton" class="restart-button">Play Again</button>).
				
					<!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="styles.css">
</head>
<body>
    <div id="board" class="board">
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
    </div>
    <div id="message" class="message"></div>
    <button id="restartButton" class="restart-button">Play Again</button>

    <script src="script.js"></script>
</body>
</html>

				
			

ملف styles.css

  • نقوم بتصميم الطاولة والخلايا ورسالة اللعبة وزر إعادة اللعب باستخدام CSS.
  • نستخدم القواعد لتحديد تصميم العناصر، مثل حجم الخلايا وتنسيقات النص وأنماط الألوان وغيرها.
				
					/* styles.css */
.board {
    display: grid;
    grid-template-columns: repeat(3, 100px);
    grid-template-rows: repeat(3, 100px);
    gap: 5px;
    width: 315px;
    margin: 50px auto;
}

.cell {
    width: 100px;
    height: 100px;
    background-color: #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    cursor: pointer;
}

.message {
    text-align: center;
    font-size: 24px;
    margin-top: 20px;
    padding: 10px;
    border-radius: 5px;
    background-color: #f0f0f0;
    color: #333;
    box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
}

.restart-button {
    display: block;
    margin: 20px auto;
    padding: 10px 20px;
    font-size: 18px;
    background-color: #4caf50;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.restart-button:hover {
    background-color: #45a049;
}

				
			

ملف script.js

تحديد المتغيرات

				
					const board = document.getElementById('board');
const message = document.getElementById('message');
const cells = document.querySelectorAll('[data-cell]');
const restartButton = document.getElementById('restartButton');
let currentPlayer = 'X';
let gameActive = true;

				
			
  • نقوم بتحديد المتغيرات اللازمة للوصول إلى عناصر HTML مثل اللوحة (board) ورسالة اللعبة (message) والخلايا (cells) وزر إعادة اللعب (restartButton).
  • نعرف المتغيرات الأخرى مثل currentPlayer لتتبع اللاعب الحالي و gameActive لمعرفة ما إذا كانت اللعبة ما زالت قيد التشغيل.

معالجة نقرات الخلايا

				
					cells.forEach(cell => {
    cell.addEventListener('click', handleCellClick);
});

				
			
  • نقوم باستخدام forEach لتحديد كل خلية ونضيف مستمع لحدث النقر (click) لكل خلية. عند النقر على الخلية، سيتم تشغيل الدالة handleCellClick.

التحقق من النقرات وتحديث الحالة

				
					function handleCellClick(e) {
    const cell = e.target;
    if (!gameActive || cell.textContent !== '') return;

    cell.textContent = currentPlayer;
    if (checkWin() || checkDraw()) {
        endGame();
        return;
    }
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}

				
			
  • في الدالة handleCellClick، نحصل على الخلية التي تم النقر عليها ونتحقق من أن اللعبة قيد التشغيل وأن الخلية غير ممتلئة بالفعل.
  • نقوم بوضع علامة اللاعب الحالي في الخلية المحددة ونحدد اللاعب التالي.
  • بعد كل نقرة، نتحقق من اكتمال اللعبة (checkWin أو checkDraw) وننهي اللعبة إذا كانت قد انتهت.

تحديد الفائز أو التعادل

				
					function checkWin() {
    // تحقق من الفوز بالنظر إلى الشروط الفائزة
    // إرجاع true إذا كان هناك فائز وإلا فإن القيمة المُرجعة هي false
}

function checkDraw() {
    // تحقق من التعادل بالنظر إلى حالة الخلايا
    // إرجاع true إذا كانت اللعبة تعادلت وإلا فإن القيمة المُرجعة هي false
}

				
			
  • تحقق الدالتان checkWin و checkDraw من وجود فائز أو تعادل بناءً على حالة الخلايا.
  • تُرجع true إذا كان هناك فائز أو تعادل، وإلا فإنها ترجع false.

نهاية اللعبة وإعادة اللعب

				
					function endGame() {
    gameActive = false;
    message.textContent = checkWin() ? `Player ${currentPlayer} wins!` : 'Draw!';
}

function restartGame() {
    // إعادة تعيين اللوحة وبدء اللعبة من جديد
}

				
			
  • في الدالة endGame، نقوم بتعيين متغير gameActive إلى false ونعرض رسالة الفوز أو التعادل.
  • في الدالة restartGame، نقوم بإعادة تعيين اللوحة وبدء اللعبة من جديد بوضع خلايا جديدة فارغة وتحديث اللاعب الحالي إلى “X”.

الشكل النهائي لملف جافاسكريبت

				
					// tictactoe.js
document.addEventListener('DOMContentLoaded', function () {
    const board = document.getElementById('board');
    const message = document.getElementById('message');
    const cells = document.querySelectorAll('[data-cell]');
    const restartButton = document.getElementById('restartButton');
    let currentPlayer = 'X';
    let gameActive = true;

    cells.forEach(cell => {
        cell.addEventListener('click', handleCellClick);
    });

    restartButton.addEventListener('click', restartGame);

    function handleCellClick(e) {
        const cell = e.target;
        if (!gameActive || cell.textContent !== '') return;

        cell.textContent = currentPlayer;
        if (checkWin() || checkDraw()) {
            endGame();
            return;
        }
        currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
    }

    function checkWin() {
        const winningConditions = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ];

        return winningConditions.some(combination => {
            return combination.every(index => {
                return cells[index].textContent === currentPlayer;
            });
        });
    }

    function checkDraw() {
        return [...cells].every(cell => {
            return cell.textContent !== '';
        });
    }

    function endGame() {
        gameActive = false;
        message.textContent = checkWin() ? `Player ${currentPlayer} wins!` : 'Draw!';
    }

    function restartGame() {
        cells.forEach(cell => {
            cell.textContent = '';
        });
        currentPlayer = 'X';
        gameActive = true;
        message.textContent = '';
    }
});

				
			
عمل لعبةXO (Tic-Tac-Toe) باستخدام javascript و html و css
Result

موارد إضافية:

Scroll to Top