Chingu FCC Speedrun Challenge: Tic Tac Toe

Amir Fakheraldeen
Chingu FCC Speedrun
2 min readMay 22, 2017

Phew! I can’t believe I finally finished this one. It took quite a while, and honestly perhaps more than it should have. I’ll admit I was a bit busy while doing it, so didn’t get to put a lot of time into it.

Anyways, I’ll be honest, it did not turn out exactly the way I would have liked, and I’m sure the code could have been written in a better way. I also wanted to create an unbeatable AI. However, that’s a task for another day as I’d like to move on with the speedrun. Note to self: Make an unbeatable AI and improve code next time I do this project. :)

As for the challenges, well, they were many. For example, figuring out a way to make the computer make a move. I had to write a separate function for computer moves, which is called from within the function that handles player moves. Here the functions I’m talking about (SPOILER ALERT for those who wish to attempt the project on their own):

makeMove(row, index) {
if (!this.gameOver &&
this.turn == "player" &&
!this.board[row][index]) {
this.setSquare(row, index, this.playerMark);
this.turn = "computer";
setTimeout(this.computerMove, 500);
}
}
computerMove() {
if (!this.gameOver &&
this.turn == "computer" &&
this.moves < this.board.length ** 2) {
let square;
do {
square = this.randomSquare();
} while (this.board[square.x][square.y]);
this.setSquare(square.x, square.y, this.computerMark);
this.turn = "player";
}
}

If you’re wondering what all thethis keywords are, they’re the reference to the Vue isntance. That’s the way you access data you’ve defined in Vue.

Anyways, as you can see, the computerMove function is called from within the makeMove function (which is called once the user clicks on a square). We keep getting a random square until we get an empty one, since we don’t want to replace one that’s already filled.

That’s about it. If you wish to know more about how this app works, you can check the source code below.

Links:

Previous projects:

--

--