chatGPT가 만든 스네이크 게임(Snake Game)

2023. 4. 21. 21:16Web/javascript

최근 이슈 되고 있는 chat gpt 이거 정말로 코딩도 해주는지 시험삼아서 한번 해봤습니다!!

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Snake Game</title>
    <style>
      canvas {
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="400" height="400" tabindex="1"></canvas>
    <div>Score: <span id="score">0</span></div>
    <script>
      // Canvas
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      const canvasWidth = canvas.width;
      const canvasHeight = canvas.height;

      // Snake
      let snake = [
        { x: 10, y: 10 },
        { x: 9, y: 10 },
        { x: 8, y: 10 },
      ];
      let direction = "right";

      // Food
      let food = getRandomFoodPosition();

      // Score
      let score = 0;
      const scoreElement = document.getElementById("score");

      // Draw functions
      function drawSnake() {
        ctx.fillStyle = "green";
        ctx.strokeStyle = "darkgreen";
        snake.forEach((segment) => {
          ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10);
          ctx.strokeRect(segment.x * 10, segment.y * 10, 10, 10);
        });
      }

      function drawFood() {
        ctx.fillStyle = "red";
        ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
      }

      function draw() {
        ctx.clearRect(0, 0, canvasWidth, canvasHeight);
        drawSnake();
        drawFood();
        scoreElement.innerText = score;
      }

      // Update functions
      function updateSnake() {
        const head = { x: snake[0].x, y: snake[0].y };
        switch (direction) {
          case "up":
            head.y -= 1;
            break;
          case "down":
            head.y += 1;
            break;
          case "left":
            head.x -= 1;
            break;
          case "right":
            head.x += 1;
            break;
        }

        // Check if snake ate food
        if (head.x === food.x && head.y === food.y) {
          snake.unshift(head);
          food = getRandomFoodPosition();
          score += 10;
          return;
        }

        snake.unshift(head);
        snake.pop();

        // Check if snake collided with itself or the wall
        if (checkCollision()) {
          clearInterval(gameInterval);
          alert("Game over! Your score: " + score);
        }
      }

      function checkCollision() {
        const head = snake[0];

        // Check if snake collided with the wall
        if (head.x < 0 || head.x >= canvasWidth / 10 || head.y < 0 || head.y >= canvasHeight / 10) {
          return true;
        }

        // Check if snake collided with itself
        for (let i = 1; i < snake.length; i++) {
          if (head.x === snake[i].x && head.y === snake[i].y) {
            return true;
          }
        }

        return false;
      }

      function getRandomFoodPosition() {
        let position;
        do {
          position = {
            x: Math.floor(Math.random() * (canvasWidth /        10)),
            y: Math.floor(Math.random() * (canvasHeight / 10)),
          };
        } while (isFoodOnSnake(position));
        return position;
      }
    
      function isFoodOnSnake(position) {
        return snake.some((segment) => {
          return segment.x === position.x && segment.y === position.y;
        });
      }
    
      // Game loop
      let gameInterval;
      function startGame() {
        gameInterval = setInterval(() => {
          updateSnake();
          draw();
        }, 100);
      }
    
      // Keyboard input
      document.addEventListener("keydown", (event) => {
        switch (event.code) {
          case "KeyW":
          case "ArrowUp":
            if (direction !== "down") {
              direction = "up";
            }
            break;
          case "KeyS":
          case "ArrowDown":
            if (direction !== "up") {
              direction = "down";
            }
            break;
          case "KeyA":
          case "ArrowLeft":
            if (direction !== "right") {
              direction = "left";
            }
            break;
          case "KeyD":
          case "ArrowRight":
            if (direction !== "left") {
              direction = "right";
            }
            break;
        }
      });
    
      // Start the game
      startGame();
    </script>

10번정도 수정을 걸쳐서 순수하게 GPT만드로 코드를 만들었습니다. 

생각보다 잘하는데요?

 

아래는 실행 이미지입니다.

코드 실행화면

 

반응형