Updated: followed suggestions by tonyl
The series continues… I just had a big problem with my pc but I’ve found and old one to work with while I find a proper replacement… but it’s SLOOOOOW
Anyway, here’s the tutorial.
To have a look at the final file here’s the link
In this exercise I learned how to use the arrays. What is an array? It is better explained here
In computer science, an array type is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices that can be computed at run time by the program.
I not only needed an array but a bidimensional one. You can think of a 2d array simply as a table that lets you access every cell like you did when you played naval battle. You have an index for the x and one for the y.
To declare a bidimensional array you first need to declare a simple array (note that you don’t need to specify how many cell will have the array).
var arr = ; //or var arr = new Array();
Then you declare an array for every element in the previous array. In my case I needed a 3×3 array so I declared 3 more array using a for cicle.
for (var i=0;i<3;i++)
Lastly I need to initialize the array to have a known starting point. Since my starting point is an empty board I will initialize the array to zero.
for (var x=0;x<3;x++)
for (var y=0;y<3;y++)
As you probably realized by looking at the previous code to access the cells you need need to write the name of the array variable folowed by the indexes between “[" and "]“.
The other new command I used is
Which simply reloads the page. I used it to start a new game every time someone won or the where no more moves.
Tic Tac Toe flow
At every click the program should do the following operations
- Update the game board (visually and the represantation)
- Check if it was a winning move
- If yes congratulate and end the game
- Check if it was the last move
- Change player
If you need any other explanation or if you have something to add please comment below.
You can try it here