js实现ai自己玩贪吃蛇游戏代码

代码语言:html

所属分类:游戏

代码描述:js实现ai自己玩贪吃蛇游戏代码

代码标签: js ai 自己 贪吃蛇 游戏

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开


<!DOCTYPE html>
<html lang="en" >

<head>

  <meta charset="UTF-8">

  
  
  
  
<style>
@import url("https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Press Start 2P", "Courier New", Courier, monospace;
}

html,
body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: gray;
}

h1 {
  color: white;
  width: 100%;
  position: fixed;
  top: 10px;
  left: 50%;
  transform: translate(-50%, 0);
  text-align: center;
  font-size: 20px;
}

canvas {
  border: 1px solid red;
  border-radius: 4px;
  box-shadow: 0 0 20px red;
}
</style>


</head>

<body >
  <h1>Snake AI 🐍</h1>
<canvas id="Canvas" width="800px" height="800px"></canvas>

  
      <script >
const randomNumber = (min = 0, max = 10) =>
Math.floor(Math.random() * (max - min + 1) + min);

const colors = {
  tile: "rgba(100, 100, 100, 0.75)",
  apple: "#ff0000",
  head: "#00ffff",
  label: "#ffff00" };


class Game {
  constructor() {
    const width = 800;
    const height = 800;

    this.canvas = document.getElementById("Canvas");
    this.canvas.width = width;
    this.canvas.height = height;
    this.ctx = this.canvas.getContext("2d");

    this.width = width;
    this.height = height;

    this.startDate = new Date().getTime();

    this.init();
    this.create();
    this.update();
  }

  init() {
    this.score = 0;
    this.tileSize = 40;
    this.numRows = 20;
    this.numColumns = 20;
  }

  create() {
    this.stopGame = false;

    this.player = {
      x: this.numRows - 1,
      y: this.numColumns - 1,
      body: [] };


    this.apple = {
      x: 0,
      y: 0 };

    this.setAppleRandomPosition();

    // Set Canvas Color
    this.ctx.strokeStyle = "rgba(255, 255, 255, 0.1)";
    this.ctx.textAlign = "left";
    this.ctx.textBaseline = "middle";
    this.ctx.font = "30px monospace";
  }

  setAppleRandomPosition() {
    let occupiedCell = false;

    do {
      const { apple, player } = this;
      occupiedCell = false;

      // Apple Random Position
      apple.x = randomNumber(0, this.numColumns - 1);
      apple.y = randomNumber(0, this.numColumns - 1);

      // Check Position Width Player
      if (apple.x == player.x && apple.y == player.y) {
        occupiedCell = true;
        continue;
      }

      // Check Position Width Player Body Cells
      if (player.body.length) {
        for (let i = 0; i < player.body.length; i++) {
          const b = player.body[i];
          if (apple.x == b.x && apple.y == b.y) {
            occupiedCell = true;
            break;
          }
        }
      }
    } while (occupiedCell).........完整代码请登录后点击上方下载按钮下载查看

网友评论0