龙空技术网

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

前端梁哥 33

前言:

如今兄弟们对“js开发网页游戏”大体比较着重,同学们都需要剖析一些“js开发网页游戏”的相关文章。那么小编在网络上收集了一些对于“js开发网页游戏””的相关文章,希望看官们能喜欢,朋友们一起来了解一下吧!

为了减小篇幅,我计划分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  }
生成入口和出口位置

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

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 }

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

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

标签: #js开发网页游戏 #javascript网页游戏制作轻松学pdf