You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

p5.js开发问题:仅显示背景,游戏棋盘无法正常渲染

p5.js扫雷项目棋盘不显示问题解决方案

问题

基于p5.js开发学校游戏项目,复用老师的扫雷代码后,运行仅能看到灰色背景,15x15的游戏棋盘完全不显示,预期能看到居中的方格棋盘。

错误原因

代码里有两个关键问题导致棋盘无法渲染:

  1. createBoard函数创建了棋盘数组,但没有返回这个数组,导致全局变量gameBoard一直是undefined,循环调用draw()时找不到对象
  2. HTML中引入了Square.js,但你的SQUARE类已经写在sketch.js里,重复引入会导致类定义冲突或找不到正确的类

修复步骤

1. 给createBoard函数添加返回语句

在createBoard函数的末尾加上return board;,让函数把创建好的棋盘数组返回给gameBoard变量:

function createBoard(size) {
    let board = []
    for (let i = 0; i < size; i++) {
        let row = []
        for (let j = 0; j < size; j++) {
            let square = new SQUARE(i, j)
            row.push(square)
        }
        board.push(row)
    }
    // 添加这行返回语句
    return board;
}

2. 移除HTML中多余的Square.js引入

因为你的SQUARE类已经定义在sketch.js里,不需要再单独引入Square.js,修改后的HTML代码如下:

<html>
<head>
    <script src="p5.min.js"></script>
    <!-- 移除Square.js的引入 -->
    <script src="sketch.js"></script>
</head>
<body>
</body>
</html>

完整修复后代码

sketch.js

//global variables
let gameBoard           //holds information about the state of the board      
let size = 15          //horz and vert size of the board
 
//runs once at the start
function setup() {
    createCanvas(windowWidth, windowHeight)
    gameBoard = createBoard(size)
}

function draw() {
    background(220)
    translate(windowWidth/2 - size/2*30, windowHeight/2 - size/2*30)
    for (let x = 0; x < size; x++) {
        for (let y = 0; y < size; y++) {
            gameBoard[x][y].draw()
        }
    }
}

function createBoard(size) {
    let board = []
    for (let i = 0; i < size; i++) {
        let row = []
        for (let j = 0; j < size; j++) {
            let square = new SQUARE(i, j)
            row.push(square)
        }
        board.push(row)
    }
    return board;
}

class SQUARE {
    constructor(column,row){
        this.x = column
        this.y = row
    }
    draw(){
        rect(this.x*30, this.y*30, 30, 30)
    }
}

index.html

<html>
<head>
    <script src="p5.min.js"></script>
    <script src="sketch.js"></script>
</head>
<body>
</body>
</html>

修改后运行,就能看到居中的15x15方格棋盘了。

内容的提问来源于stack exchange,提问作者zyns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 13:17:03