<?php
session_start();

// 게임 초기화
if (!isset($_SESSION['board']) || isset($_GET['reset'])) {
    $_SESSION['board'] = array_fill(0, 15, array_fill(0, 15, 0));
    $_SESSION['current_player'] = 1; // 1: 흑돌(사용자), 2: 백돌(컴퓨터)
    $_SESSION['game_over'] = false;
    $_SESSION['winner'] = 0;
    $_SESSION['vs_computer'] = isset($_GET['vs_computer']) ? (bool)$_GET['vs_computer'] : (isset($_SESSION['vs_computer']) ? $_SESSION['vs_computer'] : true);
    $_SESSION['difficulty'] = isset($_GET['difficulty']) ? intval($_GET['difficulty']) : (isset($_SESSION['difficulty']) ? $_SESSION['difficulty'] : 1);
}

// 컴퓨터 모드 전환
if (isset($_GET['vs_computer'])) {
    $_SESSION['vs_computer'] = $_GET['vs_computer'] == '1';
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// 난이도 변경
if (isset($_GET['difficulty'])) {
    $_SESSION['difficulty'] = intval($_GET['difficulty']);
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// 승리 확인 함수
function checkWin($row, $col, $player, $board) {
    $directions = [
        [0, 1], // 가로
        [1, 0], // 세로
        [1, 1], // 대각선 ↘
        [1, -1] // 대각선 ↗
    ];

    foreach ($directions as $dir) {
        $count = 1;
        
        // 정방향 확인
        for ($i = 1; $i <= 4; $i++) {
            $new_row = $row + $dir[0] * $i;
            $new_col = $col + $dir[1] * $i;
            
            if ($new_row < 0 || $new_row >= 15 || $new_col < 0 || $new_col >= 15 || $board[$new_row][$new_col] != $player) {
                break;
            }
            $count++;
        }
        
        // 역방향 확인
        for ($i = 1; $i <= 4; $i++) {
            $new_row = $row - $dir[0] * $i;
            $new_col = $col - $dir[1] * $i;
            
            if ($new_row < 0 || $new_row >= 15 || $new_col < 0 || $new_col >= 15 || $board[$new_row][$new_col] != $player) {
                break;
            }
            $count++;
        }
        
        if ($count >= 5) {
            return true;
        }
    }
    
    return false;
}

// 쉬운 난이도 이동 찾기 (랜덤 + 기본 방어)
function findEasyMove($board, $empty_cells) {
    // 상대방(사용자)이 4개 연속으로 놓은 경우 방어
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                // 가상으로 이 위치에 상대방 돌을 놓아봄
                $board[$i][$j] = 1;
                if (checkWin($i, $j, 1, $board)) {
                    // 상대방이 여기에 놓으면 이길 수 있으므로 방어
                    $board[$i][$j] = 0; // 가상 돌 제거
                    return [$i, $j];
                }
                $board[$i][$j] = 0; // 가상 돌 제거
            }
        }
    }
    
    // 방어할 곳이 없으면 랜덤하게 놓기
    $random_index = array_rand($empty_cells);
    return $empty_cells[$random_index];
}

// 4-in-a-row 찾기
function findFourInARow($board, $player) {
    $directions = [
        [0, 1], // 가로
        [1, 0], // 세로
        [1, 1], // 대각선 ↘
        [1, -1] // 대각선 ↗
    ];
    
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == $player) {
                foreach ($directions as $dir) {
                    $count = 1;
                    
                    // 한쪽 방향 확인
                    for ($k = 1; $k <= 3; $k++) {
                        $new_i = $i + $dir[0] * $k;
                        $new_j = $j + $dir[1] * $k;
                        
                        if ($new_i < 0 || $new_i >= 15 || $new_j < 0 || $new_j >= 15 || $board[$new_i][$new_j] != $player) {
                            break;
                        }
                        $count++;
                    }
                    
                    // 양쪽 끝 확인
                    if ($count >= 4) {
                        // 한쪽 끝 확인
                        $next_i = $i + $dir[0] * 4;
                        $next_j = $j + $dir[1] * 4;
                        if ($next_i >= 0 && $next_i < 15 && $next_j >= 0 && $next_j < 15 && $board[$next_i][$next_j] == 0) {
                            return [$next_i, $next_j];
                        }
                        
                        // 다른 쪽 끝 확인
                        $prev_i = $i - $dir[0];
                        $prev_j = $j - $dir[1];
                        if ($prev_i >= 0 && $prev_i < 15 && $prev_j >= 0 && $prev_j < 15 && $board[$prev_i][$prev_j] == 0) {
                            return [$prev_i, $prev_j];
                        }
                    }
                }
            }
        }
    }
    
    return null;
}

// 3-in-a-row 찾기
function findThreeInARow($board, $player) {
    $directions = [
        [0, 1], // 가로
        [1, 0], // 세로
        [1, 1], // 대각선 ↘
        [1, -1] // 대각선 ↗
    ];
    
    $candidates = [];
    
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == $player) {
                foreach ($directions as $dir) {
                    // 3-in-a-row 확인
                    $count = 1;
                    for ($k = 1; $k <= 2; $k++) {
                        $new_i = $i + $dir[0] * $k;
                        $new_j = $j + $dir[1] * $k;
                        
                        if ($new_i < 0 || $new_i >= 15 || $new_j < 0 || $new_j >= 15 || $board[$new_i][$new_j] != $player) {
                            break;
                        }
                        $count++;
                    }
                    
                    if ($count == 3) {
                        // 양쪽 끝이 비어있는지 확인
                        $next_i = $i + $dir[0] * 3;
                        $next_j = $j + $dir[1] * 3;
                        if ($next_i >= 0 && $next_i < 15 && $next_j >= 0 && $next_j < 15 && $board[$next_i][$next_j] == 0) {
                            $candidates[] = [$next_i, $next_j];
                        }
                        
                        $prev_i = $i - $dir[0];
                        $prev_j = $j - $dir[1];
                        if ($prev_i >= 0 && $prev_i < 15 && $prev_j >= 0 && $prev_j < 15 && $board[$prev_i][$prev_j] == 0) {
                            $candidates[] = [$prev_i, $prev_j];
                        }
                    }
                }
            }
        }
    }
    
    if (!empty($candidates)) {
        // 랜덤하게 하나 선택
        return $candidates[array_rand($candidates)];
    }
    
    return null;
}

// 전략적 위치 찾기
function findStrategicMove($board) {
    $center = 7;
    $scores = [];
    
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                $score = 0;
                
                // 중앙에 가까울수록 점수 추가
                $distance_from_center = max(abs($i - $center), abs($j - $center));
                $score += (10 - $distance_from_center);
                
                // 주변 돌에 따른 점수 추가
                for ($di = -1; $di <= 1; $di++) {
                    for ($dj = -1; $dj <= 1; $dj++) {
                        if ($di == 0 && $dj == 0) continue;
                        
                        $ni = $i + $di;
                        $nj = $j + $dj;
                        
                        if ($ni >= 0 && $ni < 15 && $nj >= 0 && $nj < 15) {
                            if ($board[$ni][$nj] == 2) { // 자기 돌 주변에 두면 좋음
                                $score += 2;
                            } else if ($board[$ni][$nj] == 1) { // 상대 돌 주변도 고려
                                $score += 1;
                            }
                        }
                    }
                }
                
                $scores[] = [
                    'row' => $i,
                    'col' => $j,
                    'score' => $score
                ];
            }
        }
    }
    
    // 점수 기준으로 정렬
    usort($scores, function($a, $b) {
        return $b['score'] - $a['score'];
    });
    
    // 상위 3개 중에서 랜덤하게 선택 (약간의 변동성 추가)
    $top_scores = array_slice($scores, 0, min(3, count($scores)));
    $chosen = $top_scores[array_rand($top_scores)];
    
    return [$chosen['row'], $chosen['col']];
}

// 중간 난이도 이동 찾기 (방어 + 기본 공격)
function findSmartMove($board) {
    // 1. 컴퓨터가 한 수 두어 이길 수 있는 위치 찾기 (공격)
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                $board[$i][$j] = 2; // 컴퓨터(백돌)
                if (checkWin($i, $j, 2, $board)) {
                    $board[$i][$j] = 0; // 가상 돌 제거
                    return [$i, $j]; // 이길 수 있는 위치 발견
                }
                $board[$i][$j] = 0; // 가상 돌 제거
            }
        }
    }
    
    // 2. 상대방이 한 수 두어 이길 수 있는 위치 찾기 (방어)
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                $board[$i][$j] = 1; // 사용자(흑돌)
                if (checkWin($i, $j, 1, $board)) {
                    $board[$i][$j] = 0; // 가상 돌 제거
                    return [$i, $j]; // 방어해야 할 위치 발견
                }
                $board[$i][$j] = 0; // 가상 돌 제거
            }
        }
    }
    
    // 3. 기본 전략: 중앙 근처에 두기 시도
    $center = 7;
    $potential_moves = [];
    
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                // 중앙에서의 거리를 계산 (맨해튼 거리)
                $distance = abs($i - $center) + abs($j - $center);
                $potential_moves[] = [
                    'row' => $i,
                    'col' => $j,
                    'score' => 15 - $distance // 중앙에 가까울수록 점수가 높음
                ];
            }
        }
    }
    
    // 점수 기준으로 정렬
    usort($potential_moves, function($a, $b) {
        return $b['score'] - $a['score'];
    });
    
    // 조금의 랜덤성 추가 (상위 5개 중에서 선택)
    $top_moves = array_slice($potential_moves, 0, min(5, count($potential_moves)));
    $chosen = $top_moves[array_rand($top_moves)];
    
    return [$chosen['row'], $chosen['col']];
}

// 어려운 난이도 이동 찾기 (미니맥스와 유사한 접근법)
function findBestMove($board) {
    $best_score = -1000;
    $best_move = null;
    
    // 1. 컴퓨터가 이길 수 있는 수 찾기
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                $board[$i][$j] = 2;
                if (checkWin($i, $j, 2, $board)) {
                    $board[$i][$j] = 0;
                    return [$i, $j];
                }
                $board[$i][$j] = 0;
            }
        }
    }
    
    // 2. 상대방의 승리 차단
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                $board[$i][$j] = 1;
                if (checkWin($i, $j, 1, $board)) {
                    $board[$i][$j] = 0;
                    return [$i, $j];
                }
                $board[$i][$j] = 0;
            }
        }
    }
    
    // 3. 컴퓨터의 4-in-a-row 만들기 (공격적인 이동)
    $offensive_move = findFourInARow($board, 2);
    if ($offensive_move) {
        return $offensive_move;
    }
    
    // 4. 상대방의 4-in-a-row 차단 (방어적인 이동)
    $defensive_move = findFourInARow($board, 1);
    if ($defensive_move) {
        return $defensive_move;
    }
    
    // 5. 컴퓨터의 3-in-a-row 만들기
    $offensive_move = findThreeInARow($board, 2);
    if ($offensive_move) {
        return $offensive_move;
    }
    
    // 6. 상대방의 3-in-a-row 차단
    $defensive_move = findThreeInARow($board, 1);
    if ($defensive_move) {
        return $defensive_move;
    }
    
    // 7. 전략적 위치에 배치 (기존 돌 근처, 중앙 선호)
    return findStrategicMove($board);
}

// 컴퓨터 돌 놓기
function computerMove(&$board, $difficulty) {
    // 빈 셀 찾기
    $empty_cells = [];
    for ($i = 0; $i < 15; $i++) {
        for ($j = 0; $j < 15; $j++) {
            if ($board[$i][$j] == 0) {
                $empty_cells[] = [$i, $j];
            }
        }
    }
    
    if (empty($empty_cells)) {
        return; // 더 이상 놓을 곳이 없음
    }
    
    $move = null;
    
    // 난이도에 따른 AI 로직
    switch ($difficulty) {
        case 3: // 어려움: 최적의 수 찾기
            $move = findBestMove($board);
            break;
            
        case 2: // 보통: 방어 + 약간의 공격
            $move = findSmartMove($board);
            break;
            
        case 1: // 쉬움: 랜덤 + 기본 방어
            $move = findEasyMove($board, $empty_cells);
            break;
            
        default: // 매우 쉬움: 완전 랜덤
            $random_index = array_rand($empty_cells);
            $move = $empty_cells[$random_index];
    }
    
    if ($move) {
        $row = $move[0];
        $col = $move[1];
        
        // 컴퓨터 돌 놓기
        $board[$row][$col] = 2;
        
        // 승리 확인
        if (checkWin($row, $col, 2, $board)) {
            $_SESSION['game_over'] = true;
            $_SESSION['winner'] = 2;
        } else {
            // 다시 사용자 차례로
            $_SESSION['current_player'] = 1;
        }
    }
}

// 돌 놓기 (사용자)
if (isset($_GET['row']) && isset($_GET['col']) && !$_SESSION['game_over']) {
    $row = intval($_GET['row']);
    $col = intval($_GET['col']);

    // 유효한 위치이고 비어있는 경우 (사용자 턴일 때만)
    if ($_SESSION['current_player'] == 1 && $row >= 0 && $row < 15 && $col >= 0 && $col < 15 && $_SESSION['board'][$row][$col] == 0) {
        // 사용자 돌 놓기
        $_SESSION['board'][$row][$col] = $_SESSION['current_player'];
        
        // 승리 확인
        if (checkWin($row, $col, $_SESSION['current_player'], $_SESSION['board'])) {
            $_SESSION['game_over'] = true;
            $_SESSION['winner'] = $_SESSION['current_player'];
        } else {
            // 컴퓨터 차례로 전환
            $_SESSION['current_player'] = 2;
            
            // 컴퓨터 모드일 경우 컴퓨터 턴 실행
            if ($_SESSION['vs_computer'] && !$_SESSION['game_over']) {
                computerMove($_SESSION['board'], $_SESSION['difficulty']);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP 오목 게임 - 컴퓨터 대전</title>
    <style>
        body {
            font-family: 'Malgun Gothic', sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f5f5f5;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .game-info {
            margin-bottom: 15px;
            text-align: center;
        }
        .board {
            background-color: #e9bb5e;
            border: 2px solid #000;
            padding: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            margin-bottom: 20px;
        }
        .row {
            display: flex;
        }
        .cell {
            width: 30px;
            height: 30px;
            border: 1px solid #000;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            background-color: transparent;
        }
        .cell::before {
            content: "";
            position: absolute;
            width: 100%;
            height: 1px;
            background-color: #000;
            z-index: 1;
        }
        .cell::after {
            content: "";
            position: absolute;
            width: 1px;
            height: 100%;
            background-color: #000;
            z-index: 1;
        }
        .stone {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            z-index: 2;
        }
        .black {
            background-color: #000;
            box-shadow: 0 0 2px 1px rgba(255, 255, 255, 0.5);
        }
        .white {
            background-color: #fff;
            box-shadow: 0 0 2px 1px rgba(0, 0, 0, 0.5);
        }
        .status {
            margin-top: 5px;
            margin-bottom: 15px;
            font-size: 18px;
            font-weight: bold;
            text-align: center;
        }
        .thinking {
            color: #555;
            font-style: italic;
            margin-top: 5px;
            display: none;
        }
        .controls {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }
        .controls a, .controls button {
            display: inline-block;
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }
        .controls a:hover, .controls button:hover {
            background-color: #45a049;
        }
        .mode-selection {
            margin: 15px 0;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 5px;
            text-align: center;
        }
        .mode-button {
            margin: 0 5px;
            padding: 5px 10px;
            border: 1px solid #999;
            border-radius: 3px;
            background-color: #eee;
            cursor: pointer;
        }
        .mode-button.active {
            background-color: #4CAF50;
            color: white;
            border-color: #4CAF50;
        }
        .difficulty-selection {
            margin: 10px 0;
        }
        .difficulty-button {
            margin: 0 5px;
            padding: 5px 10px;
            border: 1px solid #999;
            border-radius: 3px;
            background-color: #eee;
            cursor: pointer;
        }
        .difficulty-button.active {
            background-color: #2196F3;
            color: white;
            border-color: #2196F3;
        }
    </style>
</head>
<body>
    <h1>PHP 오목 게임</h1>
    
    <div class="mode-selection">
        <strong>게임 모드:</strong>
        <a href="?vs_computer=1" class="mode-button <?php echo $_SESSION['vs_computer'] ? 'active' : ''; ?>">컴퓨터 대전</a>
        <a href="?vs_computer=0" class="mode-button <?php echo !$_SESSION['vs_computer'] ? 'active' : ''; ?>">2인 플레이</a>
    </div>
    
    <?php if ($_SESSION['vs_computer']): ?>
    <div class="difficulty-selection">
        <strong>난이도:</strong>
        <a href="?difficulty=0" class="difficulty-button <?php echo $_SESSION['difficulty'] == 0 ? 'active' : ''; ?>">매우 쉬움</a>
        <a href="?difficulty=1" class="difficulty-button <?php echo $_SESSION['difficulty'] == 1 ? 'active' : ''; ?>">쉬움</a>
        <a href="?difficulty=2" class="difficulty-button <?php echo $_SESSION['difficulty'] == 2 ? 'active' : ''; ?>">보통</a>
        <a href="?difficulty=3" class="difficulty-button <?php echo $_SESSION['difficulty'] == 3 ? 'active' : ''; ?>">어려움</a>
    </div>
    <?php endif; ?>
    
    <div class="game-info">
        <?php if ($_SESSION['vs_computer']): ?>
            <p>모드: <strong>컴퓨터 대전</strong> (당신: 흑돌, 컴퓨터: 백돌)</p>
            <p>난이도: <strong>
                <?php 
                    switch($_SESSION['difficulty']) {
                        case 0: echo "매우 쉬움"; break;
                        case 1: echo "쉬움"; break;
                        case 2: echo "보통"; break;
                        case 3: echo "어려움"; break;
                    }
                ?>
            </strong></p>
        <?php else: ?>
            <p>모드: <strong>2인 플레이</strong> (흑돌 먼저)</p>
        <?php endif; ?>
    </div>
    
    <div class="status">
        <?php if ($_SESSION['game_over']): ?>
            <?php if ($_SESSION['vs_computer']): ?>
                <?php echo $_SESSION['winner'] == 1 ? '🎉 당신이 승리했습니다! 🎉' : '컴퓨터가 승리했습니다.'; ?>
            <?php else: ?>
                <?php echo $_SESSION['winner'] == 1 ? '흑돌' : '백돌'; ?> 승리!
            <?php endif; ?>
        <?php else: ?>
            <?php if ($_SESSION['vs_computer'] && $_SESSION['current_player'] == 2): ?>
                컴퓨터가 생각 중...
            <?php else: ?>
                현재 차례: <?php echo $_SESSION['current_player'] == 1 ? '흑돌' : '백돌'; ?>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <div class="board">
        <?php for ($i = 0; $i < 15; $i++): ?>
            <div class="row">
                <?php for ($j = 0; $j < 15; $j++): ?>
                    <div class="cell">
                        <?php if ($_SESSION['board'][$i][$j] != 0): ?>
                            <div class="stone <?php echo $_SESSION['board'][$i][$j] == 1 ? 'black' : 'white'; ?>"></div>
                        <?php elseif (!$_SESSION['game_over'] && (!$_SESSION['vs_computer'] || $_SESSION['current_player'] == 1)): ?>
                            <a href="?row=<?php echo $i; ?>&col=<?php echo $j; ?>" style="display: block; width: 100%; height: 100%;"></a>
                        <?php endif; ?>
                    </div>
                <?php endfor; ?>
            </div>
        <?php endfor; ?>
    </div>
    
    <div class="controls">
        <a href="?reset=1" class="reset-button">게임 재시작</a>
    </div>
    
    <?php if ($_SESSION['vs_computer'] && $_SESSION['current_player'] == 2 && !$_SESSION['game_over']): ?>
    <script>
        // 페이지 로드 후 자동으로 새로고침하여 컴퓨터 턴 진행
        setTimeout(function() {
            window.location.reload();
        }, 500);
    </script>
    <?php endif; ?>
</body>
</html>
