跳过

AI开发贪吃蛇(完整代码)

发布时间: at 16:16
本文收录在以下合集中:

本文为AI开发实例,所有代码均为AI生成,仅供参考。 使用工具:智谱清言 项目:贪吃蛇游戏开发 时间:2024年11月10日16:16:16 用户:祎果 AI:ChatGLM

HTML部分

// index.html

<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>贪吃蛇小游戏</title>
    <style>
      #gameCanvas {
        border: 1px solid black;
        background-color: #ddd;
      }
      #score {
        font-family: Arial, sans-serif;
        font-size: 24px;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <div id="score">得分: 0</div>
    <script src="game.js"></script>
  </body>
</html>

JavaScript部分

// game.js
const canvas = document.getElementById('gameCanvas')
const ctx = canvas.getContext('2d')
const scoreElement = document.getElementById('score') // 获取得分元素
const scale = 20
const rows = canvas.height / scale
const columns = canvas.width / scale
let score = 0 // 初始化得分
let paused = false // 初始化暂停状态

window.addEventListener('keydown', evt => {
  const direction = evt.key.replace('Arrow', '')
  snake.changeDirection(direction)
})

function Snake() {
  this.currentDirection = 'Right' // 初始化当前方向
  this.x = 0
  this.y = 0
  this.xSpeed = scale * 1
  this.ySpeed = 0
  this.total = 0
  this.tail = []

  this.draw = function () {
    ctx.fillStyle = '#FFFFFF'
    for (let i = 0; i < this.tail.length; i++) {
      ctx.fillRect(this.tail[i].x, this.tail[i].y, scale, scale)
    }

    ctx.fillRect(this.x, this.y, scale, scale)
  }

  this.update = function () {
    for (let i = 0; i < this.tail.length - 1; i++) {
      this.tail[i] = this.tail[i + 1]
    }

    this.tail[this.total - 1] = {x: this.x, y: this.y}

    this.x += this.xSpeed
    this.y += this.ySpeed

    if (this.x > canvas.width) {
      this.x = 0
    }

    if (this.y > canvas.height) {
      this.y = 0
    }

    if (this.x < 0) {
      this.x = canvas.width
    }

    if (this.y < 0) {
      this.y = canvas.height
    }
  }

  this.changeDirection = function (direction) {
    const oppositeDirections = {
      Up: 'Down',
      Down: 'Up',
      Left: 'Right',
      Right: 'Left',
    }

    // 防止蛇掉头
    if (oppositeDirections[direction] !== this.currentDirection) {
      switch (direction) {
        case 'Up':
          this.xSpeed = 0
          this.ySpeed = -scale * 1
          break
        case 'Down':
          this.xSpeed = 0
          this.ySpeed = scale * 1
          break
        case 'Left':
          this.xSpeed = -scale * 1
          this.ySpeed = 0
          break
        case 'Right':
          this.xSpeed = scale * 1
          this.ySpeed = 0
          break
      }
      this.currentDirection = direction // 更新当前方向
    }
  }

  this.eat = function (fruit) {
    if (this.x === fruit.x && this.y === fruit.y) {
      this.total++
      return true
    }

    return false
  }

  this.checkCollision = function () {
    for (let i = 0; i < this.tail.length; i++) {
      if (this.x === this.tail[i].x && this.y === this.tail[i].y) {
        this.total = 0
        this.tail = []
      }
    }
  }
}

function Food() {
  this.x
  this.y

  this.pickLocation = function () {
    let locationFound = false
    while (!locationFound) {
      this.x = (Math.floor(Math.random() * rows - 1) + 1) * scale
      this.y = (Math.floor(Math.random() * columns - 1) + 1) * scale
      locationFound = true // 假设位置是好的,除非下面的循环证明不是

      // 检查食物是否生成在蛇的身体上
      for (let i = 0; i < snake.tail.length; i++) {
        if (this.x === snake.tail[i].x && this.y === snake.tail[i].y) {
          locationFound = false // 如果食物在蛇的身体上,重新寻找位置
          break
        }
      }
    }
  }

  this.draw = function () {
    ctx.fillStyle = '#FF0000'
    ctx.fillRect(this.x, this.y, scale, scale)
  }
}

const snake = new Snake()
let food = new Food()
food.pickLocation()

function gameLoop() {
  if (!paused) {
    // 如果游戏没有暂停,则更新游戏
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    snake.update()
    snake.draw()
    food.draw()

    // Check for collision with food
    if (snake.x === food.x && snake.y === food.y) {
      snake.total++
      score += 10 // 每次吃到食物得分增加10
      updateScore() // 更新得分显示
      food = new Food() // 创建新的食物实例
      food.pickLocation() // 为新食物设置位置
    }

    // Check for collision with self
    for (let i = 0; i < snake.tail.length; i++) {
      if (snake.x === snake.tail[i].x && snake.y === snake.tail[i].y) {
        snake.total = 0
        score = 0 // 重置得分
        updateScore() // 更新得分显示
        snake.tail = []
      }
    }
  }
  setTimeout(gameLoop, 1000 / 10) // 10 updates per second
}

gameLoop()

// Update the score display
function updateScore() {
  scoreElement.textContent = '得分: ' + score
}

// Toggle pause state
function togglePause() {
  paused = !paused
}

// Add keyboard event listener
window.addEventListener('keydown', function (e) {
  let direction = ''
  switch (e.keyCode) {
    case 37:
      direction = 'Left'
      break
    case 38:
      direction = 'Up'
      break
    case 39:
      direction = 'Right'
      break
    case 40:
      direction = 'Down'
      break
    case 32: // Space key to pause/resume the game
      togglePause()
      return // No need to change direction
  }
  if (direction && snake.direction !== direction && snake.direction !== oppositeDirection(direction)) {
    snake.changeDirection(direction)
  }
})

// Helper function to get the opposite direction
function oppositeDirection(direction) {
  switch (direction) {
    case 'Up':
      return 'Down'
    case 'Down':
      return 'Up'
    case 'Left':
      return 'Right'
    case 'Right':
      return 'Left'
  }
}

游戏试玩和下载

相关工具