I created a Tic Tac Toe algorithm in JavaScript that can be used to play the game anywhere. By anywhere, I mean you can use this algorithm (which is warped in a JavaScript class) in React, Angular, React Native and even in web console. Wanna try?
How it works
You just need to define a new class and you can use methods of class to play the game.
Here's an example
letgame=newGameBoard(PLAYER_ONE,PLAYER_TWO);
Here, PLAYER_ONE and PLAYER_TWO refers to the name of players that will be playing the game. Now, when you have defined a new class. You can play the game by calling different methods. For example, in console, you can do this
So, now you just need to create the interface and perform actions with game and it will return the results. It can be implemented anywhere where JavaScript code can be executed. Right?
You can use this to create your own version of game. Here's the code. Just import the class and start implementing functions.
Implementation with Firebase
So, I decided to use this along with Firebase to create an online version of this game.
It works like this:
You create a room.
Share your room ID with your friend.
Your friend joins the room and both of you can now play the game.
Yes. You can also chat 😃!
Behind the scene, it is simple. I used Firebase Real-time Database for this. the game variable will result in an object that contains the information about the status of the game. It has properties for who's turn it is, what's the status of board and who is winning.
The program just keeps storing this object on Firebase after every turn. While, on the other hand, it keeps reading the data in real-time and shows the changes to the other player.
firebase.database().ref(roomID).on('value',(snap)=>{constdataFromServer=snap.val();// just use above object to show values on UI});
As the game object has every data in it, it will indicate winner, loser, turn and everything else. The program just needs to update the data from Firebase remote server to player's local device.
Chat also works with the simple terminology. But I used Firestore for this purpose. You can see the code on GitHub. It's pretty simple.
I would love it if someone reviews my code and find a bugs in it 💫.