首页 > 解决方案 > 如果矩形中没有任何内容,我如何让 if 类什么都不做?

问题描述

所以我正在制作井字游戏并且我做到了,当我点击空矩形(瓷砖)时,它会将标签 X 或 O 放在瓷砖上,但是如果瓷砖被标记(不是空的)我想要代码不写任何东西。

这就是这段代码目前的样子:

 if (!this.empty ()) {
        exit ();
    }

问题是,当我按下标有标签的图块时,程序完全停止,单击空图块时我再也看不到 X 或 O。是否有 exit() 的替代方法;那不这样做吗?

这是完整的代码(这段代码实际上不是我写的,它是 KhanAcademy 的做法): https ://www.khanacademy.org/computing/computer-programming/programming-games-visualizations/memory-game/pc/challenge-tic -tac-toe

var playerTurn = 0;
var NUM_COLS = 3;
var NUM_ROWS = 3;
var SYMBOLS =["X","O"];
var tiles = [];

var checkWin = function() {

};

var Tile = function(x, y) {
    this.x = x;
    this.y = y;
    this.size = width/NUM_COLS;
    this.label = "";
};

Tile.prototype.draw = function() {
    fill(214, 247, 202);
    strokeWeight(2);
    rect(this.x, this.y, this.size, this.size, 10);
    textSize(100);
    textAlign(CENTER, CENTER);
    fill(0, 0, 0);
    text(this.label, this.x+this.size/2, this.y+this.size/2);
};

Tile.prototype.empty = function() {
    return this.label === "";
};

Tile.prototype.onClick = function() {
    // If the tile is not empty, exit the function
    if (!this.empty ()) {
        exit();
    }
    // Put the player's symbol on the tile

        this.label = SYMBOLS[playerTurn];

    // Change the turn
    playerTurn ++;
    if (playerTurn >= 1) {
        playerTurn = 0;
    }
};

Tile.prototype.handleMouseClick = function(x, y) {
    // Check for mouse clicks inside the tile
    if (x >= this.x && x <= this.x + this.size &&
    y >= this.y && y <= this.y + this.size)
    {
        this.onClick();
    }
};

for (var i = 0; i < NUM_COLS; i++) {
    for (var j = 0; j < NUM_ROWS; j++) {
        tiles.push(new Tile(i * (width/NUM_COLS-1), j * (height/NUM_ROWS-1)));
    }
}

var drawTiles = function() {
    for (var i in tiles) {
        tiles[i].draw();
    }
};

mouseReleased = function() {
    for (var i in tiles) {
        tiles[i].handleMouseClick(mouseX, mouseY);
    }
};

draw = function() {
    background(143, 143, 143);
    drawTiles();

};

标签: javascriptkhan-academy

解决方案


该函数exit不是javascript的本机函数。在这种情况下它没有任何意义,因为它尚未在任何地方定义。你可以用这个词return来结束一个函数的执行——它完成了我认为你想要完成的事情exit()


Tile.prototype.onClick = function() {
    // If the tile is not empty, exit the function
    if (!this.empty ()) {
        return
    } else {
    // Put the player's symbol on the tile

        this.label = SYMBOLS[playerTurn];

    // Change the turn

    playerTurn ++;
    if (playerTurn >= 1) {
        playerTurn = 0;
    }

  }

};

推荐阅读