javascript - 如果矩形中没有任何内容,我如何让 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();
};
解决方案
该函数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;
}
}
};
推荐阅读
- python - 如何获取指定用户的推文
- docker - docker(windows10 wsl2)无法挂载./nginx/conf.d:/etc/nginx/conf.d
- git - 从我的 Git 存储库之一检索克隆数时出错
- arrays - 有没有找到绑定到特定二进制数的组合?
- javascript - 有什么方法可以删除对象数组中的多个特定对象?
- c++ - 如何创建一个数组并开始它的生命周期而不开始它的任何元素的生命周期?
- dependency-injection - 未捕获(承诺):NullInjectorError: R3InjectorError(HistorylogModule)[ModuleHelperService -> Document -> Document -> Document -> Document]:
- vb.net - VB.Net 如何使用 ReportViewer
- python - Python读取带有双引号元素和引号的CSV
- c++ - 通过引用传递向量和传递向量元素的地址