需要帮助在p5.js中为井字游戏绘制X

时间:2018-09-17 09:56:19

标签: javascript processing tic-tac-toe p5.js

我正在关注有关制作扫雷游戏的Youtube(编码火车)的教程。我一直跟踪视频,直到拍了X。 我要使彼此交叉并形成一个大x的线像这样:

The board with a X
The board with a X

我的问题是我不知道每个单元格该怎么做。

我有一个Cell课程:

function Cell(x, y, w) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.busy = true;
    this.player = true;
    this.computer = true;
}

Cell.prototype.show = function() {
    stroke(0);
    noFill();
    rect(this.x, this.y, this.w, this.w);
    if (true) {
        line(0, 0, 100, 100);
        line(0, 100, 100, 0);
    }
}

主要代码是:

function make2DArray(cols, rows) {
    var arr = new Array(cols);
    for (var i = 0; i < arr.length; i++) {
        arr[i] = new Array(rows);
    }
    return arr;
}

var grid;
var rows;
var cols;
var w = 100;

function setup() {
    createCanvas(300, 300);
    cols = floor(width/w);
    rows = floor(width/w);
    grid = make2DArray(cols, rows);
    for (var i = 0; i < cols; i++) {
        for (var j = 0; j < rows; j++) {
            grid[i][j] = new Cell(i * w, j * w, w);
        }
    }
}

function draw() {
    background(255);
    for (var i = 0; i < cols; i++) {
        for (var j = 0; j < rows; j++) {
            grid[i][j].show();
        }
    }
}

我希望能够在玩家单击一个单元格并显示它时调用X。该行必须位于Show对象的Cell类中。

1 个答案:

答案 0 :(得分:1)

每个Cell左上角的坐标存储在xy属性中。宽度存储在w中。
因此,可以通过以下方式绘制整个Cell的十字线:

line(this.x, this.y, this.x+this.w-1, this.y+this.w-1);
line(this.x, this.y+this.w-1, this.x+this.w-1, this.y);

要根据单击单元格在Cell中绘制十字,必须通过player初始化false属性:

function Cell(x, y, w) {

    .......

    this.player = false;
}

根据Cell属性在player上绘制十字:

Cell.prototype.show = function() {
    stroke(0);
    noFill();
    rect(this.x, this.y, this.w-1, this.w-1);
    if (this.player) {
        line(this.x, this.y, this.x+this.w-1, this.y+this.w-1);
        line(this.x, this.y+this.w-1, this.x+this.w-1, this.y);
    }
}

创建一个函数,以检查测试点是否在Cell中,如果测试成功,则设置player属性true

Cell.prototype.testX = function(px, py) {
    if (px >= this.x && px < this.x+this.w && py >= this.y && py < this.y+this.w ) {
        this.player = true;
    }
}

添加一个mousePressed事件,并为每个testX调用测试函数Cell。如果鼠标位置在单元格中,则player的{​​{1}}属性将变为Cell,并且下一个{{1} }:

true

Cell
draw

相关问题