So I'm making Tic Tac Toe and I made it so that when I click on the empty rectangles (tiles) it puts the label X or O on the tile, but if the tile is labeled (not empty) I want the code to not write anything.
That's how the piece of code looks currently:
if (!this.empty ()) {
exit ();
}
The issue is that when I press on a tile that is labeled the program stops entirely and I can no longer see a X or an O when clicking on an empty tile. Is there an alternative for exit(); that doesn't do that?
Here's the complete code (this code is actually not by me it's an practice from 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();
};