본문 바로가기
AI

[Claude 3.5 Sonnet]무료 AI로 간단한 미로 만들기

by Mr.noobiest 2024. 7. 19.

미로 게임


리셋버튼을 누르면 미로가 랜덤하게 재 설정됩니다. 방향키로 조작 가능

 

 

 

개선된 50x50 랜덤 미로 게임

개선된 50x50 랜덤 미로 게임

점수: 0 시간: 00:00

 

 

 

 

전체 코드

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>개선된 50x50 랜덤 미로 게임</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-family: Arial, sans-serif;
        }
        #maze {
            display: grid;
            grid-template-columns: repeat(50, 10px);
            grid-template-rows: repeat(50, 10px);
            gap: 1px;
            border: 1px solid black;
        }
        .cell {
            width: 10px;
            height: 10px;
            background-color: white;
        }
        .wall { background-color: black; }
        .player { 
            background-color: red !important; 
            z-index: 2;
        }
        .exit { background-color: green; }
        .path { 
            background-color: yellow; 
            z-index: 1;
        }
        .player.path {
            background-color: orange !important;
        }
        #controls, #info { margin-top: 20px; }
        button { margin: 0 10px; }
    </style>
</head>
<body>
    <h1>개선된 50x50 랜덤 미로 게임</h1>
    <div id="info">
        <span>점수: <span id="score">0</span></span>
        <span>시간: <span id="time">00:00</span></span>
    </div>
    <div id="maze"></div>
    <div id="controls">
        <button id="resetBtn">리셋</button>
        <button id="solutionBtn">해결책</button>
        <button id="timeBtn">기록 조회</button>
    </div>

    <script>
        const maze = document.getElementById('maze');
        const resetBtn = document.getElementById('resetBtn');
        const solutionBtn = document.getElementById('solutionBtn');
        const timeBtn = document.getElementById('timeBtn');
        const scoreElement = document.getElementById('score');
        const timeElement = document.getElementById('time');
        const size = 50;
        let grid = [];
        let cells = [];
        let player = { x: 1, y: 1 };
        let exit = { x: size - 2, y: size - 2 };
        let score = 0;
        let startTime;
        let timerInterval;
        let gameRecords = [];

        function initializeMaze() {
            maze.innerHTML = '';
            cells = [];
            for (let i = 0; i < size * size; i++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                maze.appendChild(cell);
                cells.push(cell);
            }
        }

        function createMaze() {
            grid = Array(size).fill().map(() => Array(size).fill(1));
            
            function recursiveBacktracker(x, y) {
                const directions = [
                    [0, -1], [1, 0], [0, 1], [-1, 0]
                ];
                
                directions.sort(() => Math.random() - 0.5);

                for (let [dx, dy] of directions) {
                    const nx = x + dx * 2, ny = y + dy * 2;
                    if (nx > 0 && nx < size - 1 && ny > 0 && ny < size - 1 && grid[ny][nx] === 1) {
                        grid[y + dy][x + dx] = 0;
                        grid[ny][nx] = 0;
                        recursiveBacktracker(nx, ny);
                    }
                }
            }

            recursiveBacktracker(1, 1);

            // Add some random passages to increase complexity
            for (let i = 0; i < size * size / 10; i++) {
                const x = Math.floor(Math.random() * (size - 2)) + 1;
                const y = Math.floor(Math.random() * (size - 2)) + 1;
                if (grid[y][x] === 1) {
                    grid[y][x] = 0;
                }
            }

            // Ensure the exit is accessible
            grid[exit.y][exit.x] = 0;
            grid[exit.y][exit.x - 1] = 0;

            renderMaze();
        }

        function renderMaze() {
            grid.forEach((row, y) => {
                row.forEach((cell, x) => {
                    const index = y * size + x;
                    cells[index].className = 'cell' + (cell ? ' wall' : '');
                    if (x === player.x && y === player.y) cells[index].classList.add('player');
                    if (x === exit.x && y === exit.y) cells[index].classList.add('exit');
                });
            });
        }

        function movePlayer(dx, dy) {
            const nx = player.x + dx;
            const ny = player.y + dy;
            if (nx >= 0 && nx < size && ny >= 0 && ny < size && grid[ny][nx] === 0) {
                cells[player.y * size + player.x].classList.remove('player');
                player.x = nx;
                player.y = ny;
                cells[player.y * size + player.x].classList.add('player');

                if (player.x === exit.x && player.y === exit.y) {
                    clearInterval(timerInterval);
                    const time = (Date.now() - startTime) / 1000;
                    score += 100;
                    scoreElement.textContent = score;
                    gameRecords.push({ score, time });
                    alert(`축하합니다! 미로를 탈출했습니다!\n점수: ${score}\n시간: ${formatTime(time)}`);
                }
            }
        }

        function findSolution() {
            const visited = Array(size).fill().map(() => Array(size).fill(false));
            const queue = [[player.x, player.y]];
            visited[player.y][player.x] = true;
            const parent = new Map();

            while (queue.length > 0) {
                const [x, y] = queue.shift();
                if (x === exit.x && y === exit.y) {
                    let current = [exit.x, exit.y];
                    while (current[0] !== player.x || current[1] !== player.y) {
                        const cell = cells[current[1] * size + current[0]];
                        if (!cell.classList.contains('player') && !cell.classList.contains('exit')) {
                            cell.classList.add('path');
                        }
                        current = parent.get(current.join(','));
                    }
                    // 플레이어 위치에 'path' 클래스 추가
                    cells[player.y * size + player.x].classList.add('path');
                    return;
                }

                [[0, -1], [1, 0], [0, 1], [-1, 0]].forEach(([dx, dy]) => {
                    const nx = x + dx, ny = y + dy;
                    if (nx >= 0 && nx < size && ny >= 0 && ny < size && grid[ny][nx] === 0 && !visited[ny][nx]) {
                        visited[ny][nx] = true;
                        parent.set(`${nx},${ny}`, [x, y]);
                        queue.push([nx, ny]);
                    }
                });
            }
            alert('해결책을 찾을 수 없습니다.');
        }

        function resetGame() {
            player = { x: 1, y: 1 };
            score = 0;
            scoreElement.textContent = score;
            clearInterval(timerInterval);
            startTime = Date.now();
            updateTimer();
            timerInterval = setInterval(updateTimer, 1000);
            createMaze();
            // 모든 'path' 클래스 제거
            cells.forEach(cell => cell.classList.remove('path'));
        }

        function updateTimer() {
            const elapsedTime = (Date.now() - startTime) / 1000;
            timeElement.textContent = formatTime(elapsedTime);
        }

        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        }

        function showRecords() {
            if (gameRecords.length === 0) {
                alert('아직 기록이 없습니다.');
            } else {
                const recordsText = gameRecords.map((record, index) => 
                    `게임 ${index + 1}: 점수 - ${record.score}, 시간 - ${formatTime(record.time)}`
                ).join('\n');
                alert('게임 기록:\n' + recordsText);
            }
        }

        resetBtn.addEventListener('click', resetGame);
        solutionBtn.addEventListener('click', findSolution);
        timeBtn.addEventListener('click', showRecords);

        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp': 
                    e.preventDefault();
                    movePlayer(0, -1); 
                    break;
                case 'ArrowDown': 
                    e.preventDefault();
                    movePlayer(0, 1); 
                    break;
                case 'ArrowLeft': 
                    e.preventDefault();
                    movePlayer(-1, 0); 
                    break;
                case 'ArrowRight': 
                    e.preventDefault();
                    movePlayer(1, 0); 
                    break;
            }
        });

        initializeMaze();
        resetGame();
    </script>
</body>
</html>

 

 

 

728x90
반응형