본문 바로가기
JavaScript

[JavaScript] 틱택토(Tic-Tac-Toe) 게임 만들기

by teamnova 2024. 9. 9.
728x90

안녕하세요.

오늘은 자바스크립트로 간단한 틱택토 게임 예제를 만들어보겠습니다.

 

index.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>틱택토 게임</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="game-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>
    <script src="script.js"></script>
</body>
</html>

 

style.css
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}

h1 {
    margin-bottom: 20px;
}

#game-board {
    display: grid;
    grid-template-columns: repeat(3, 100px);
    grid-template-rows: repeat(3, 100px);
    gap: 10px;
}

.cell {
    width: 100px;
    height: 100px;
    background-color: white;
    border: 2px solid #000;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 2rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.cell:hover {
    background-color: #e0e0e0;
}

 

script.js
const cells = document.querySelectorAll('[data-cell]');
let isCircleTurn = false;

cells.forEach(cell => {
    cell.addEventListener('click', handleClick, { once: true });
});

function handleClick(e) {
    const cell = e.target;
    if (!isCircleTurn) {
        placeMark(cell, 'O'); // 플레이어는 항상 O
        if (checkWin('O')) {
            setTimeout(() => alert('승리!'), 100);
            return;
        }
        if (isBoardFull()) {
            setTimeout(() => alert('무승부!'), 100);
            return;
        }
        isCircleTurn = true;
        setTimeout(computerTurn, 500); // 컴퓨터 턴을 약간의 딜레이 후 실행
    }
}

function computerTurn() {
    const emptyCells = [...cells].filter(cell => cell.textContent === '');
    const randomIndex = Math.floor(Math.random() * emptyCells.length);
    const randomCell = emptyCells[randomIndex];
    
    placeMark(randomCell, 'X'); // 컴퓨터는 항상 X
    if (checkWin('X')) {
        setTimeout(() => alert('패배!'), 100);
        return;
    }
    if (isBoardFull()) {
        setTimeout(() => alert('무승부!'), 100);
        return;
    }
    isCircleTurn = false;
}

function placeMark(cell, currentClass) {
    cell.textContent = currentClass;
}

function checkWin(currentClass) {
    const winCombinations = [
        [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 winCombinations.some(combination => {
        return combination.every(index => {
            return cells[index].textContent === currentClass;
        });
    });
}

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