web游戏用什么开发(怎样用JavaScript开发一个Web版的迷宫游戏?这是第一讲)

发布时间:2023-11-27 14:29:33 浏览量:115次

怎样用JavaScript开发一个Web版的迷宫游戏?这是第一讲

web游戏用什么开发(怎样用JavaScript开发一个Web版的迷宫游戏?这是第一讲)

为了减小篇幅,我计划分2-3篇来写,不足之处,欢迎指正。

在这里,我教大家如何实现一个简单的迷宫游戏。这个迷宫很简单,但可以玩。最终效果如下图所示。

初始界面

挑战成功界面

这是我几年前写的游戏,代码可能写的不是很好,当时用的语言是typescript,改成JS版很容易。

我是用画布实现的,要实现这个游戏,主要需要这些步骤:

我们需要根据视口宽度,行数和列数,以及墙的厚度来生成迷宫。我们需要根据设备像素比来更新画布的宽和高,并计算路的宽度。在这里,我将路称为单元格。

 private updateSize (options: UiOptions = {}) {
    this.cols = options.cols || this.cols || 16
    const width = this.cvs.offsetWidth * this.pixRatio
    const maxWallWidth = width / (this.cols * 2 + 1)
    const wallWidth = Math.min(maxWallWidth, options.wallWidth || this.pixRatio * 5)
    const cellWidth = (width - (this.cols + 1) * wallWidth) / this.cols
    const maxHeight = (this.cvs.parentElement?.offsetHeight as number) * this.pixRatio
    const maxRows = Math.floor((maxHeight - wallWidth) / (cellWidth + wallWidth))
    this.rows = Math.min(maxRows, options.rows || this.cols)
    this.realRows = this.rows * 2 - 1
    this.realCols = this.cols * 2 - 1
    this.cellWidth = cellWidth
    this.wallWidth = wallWidth
    this.cvs.width = this.gameCvs.width = width
    this.cvs.height = this.gameCvs.height = this.rows * (cellWidth + wallWidth) + wallWidth
  }

我们需要根据行数和列数,生成一个初始的网格,这个网格是一个二维数组,包含:墙和单元格。我们需要一个标识,来确定格子的类型。

private genGrid () {
    const grid: Block[][] = []
    const { realRows, realCols } = this
    for (let row = 0; row < realRows; row++) {
      grid[row] = []
      for (let col = 0; col < realCols; col++) {
        grid[row][col] = {
          row,
          col,
          type: row % 2 || col % 2 ? BlockType.WALL : BlockType.CELL
        }
      }
    }
    return grid
  }

有了尺寸和网格,我们还需要生成入口和出口位置。这个位置是根据列数,以及单元格和墙的宽度,随机生成的。代码如下:

web游戏用什么开发(怎样用JavaScript开发一个Web版的迷宫游戏?这是第一讲)

private getStartPoint () {
    const col = getRandInt(0, this.cols - 1)
    const { cellWidth, wallWidth } = this
    return {
      x: (cellWidth + wallWidth) * (col + 1 / 2),
      y: wallWidth + cellWidth / 2 - this.pixRatio / 2
    }
  }

private getEndPoint () {
    const col = getRandInt(0, this.cols - 1)
    const { cellWidth, wallWidth } = this
    return {
      x: (cellWidth + wallWidth) * col + wallWidth / 2,
      y: this.cvs.height - this.wallWidth
    }
  }

在迷宫图中,我们的可移动目标是一个圆形物体。需要给它一个初始位置,这个位置就是入口。还需要提供一个半径,用于绘制,这个圆的直径必须小于单元格宽度。

this.ball = { ...this.startPoint, r: this.cellWidth * .32 }

感谢阅读!以上就是本篇文章的全部内容,童鞋们都看懂了吗?下篇文章,我将给大家讲解迷宫图的生成,以及怎样在迷宫中移动目标,还会涉及到碰撞检测等。

#头条创作挑战赛# #前端##程序员#

web游戏用什么开发(怎样用JavaScript开发一个Web版的迷宫游戏?这是第一讲)

热门课程推荐

热门资讯

请绑定手机号

x

微信扫码在线答疑

扫码领福利1V1在线答疑

点击咨询
添加老师微信,马上领取免费课程资源

1. 打开微信扫一扫,扫描左侧二维码

2. 添加老师微信,马上领取免费课程资源

同学您好!

您已成功报名0元试学活动,老师会在第一时间与您取得联系,请保持电话畅通!
确定