I was trying to apply what I have learnt in class into 1 project. However, since I am not particularly good with art, I decided to do an interactive project. This was when I remember of a game that I played a lot with my friends before: Tic Tac Toe.
I used a nested for loop to create a 2D array so that all the steps can be stored and correctly outputted. Since I want the game to be 2 players, as the way it is in Tic Tac Toe, I used different colors (black and white) to signify for the difference in players.
In this assignment, I aims to make everything as flexible as possible. Therefore, I made the dimensions of the board environment editable. In other words, the user can change the dimension before starting the game. Below is the code for displaying the moves with any initialized dimensions:
for (let i = 0; i < boardSizeX; i++){ for (let j=0; j < boardSizeY; j++){ if (moves_lst[i][j] > 0){ fill("white"); ellipse((i + 1)*widthX - widthX/2, (j+1)*widthX - widthX/2, widthX, widthX); } else if(moves_lst[i][j] < 0) { fill('black'); ellipse((i + 1)*widthX - widthX/2, (j+1)*widthX - widthX/2, widthX, widthX); } } }
I part that I am proud of is doing the checking condition. I used the nested for loops to loop through every single piece and 4 cases (horizontal, vertical, diagonal left, and diagonal right). However, I also think that it is not the most efficient way to write this the program need to loop through every element in the array for every draw loop.
function checking_win(player){ //horizontal for (let i = 0; i < boardSizeX; i++){ for (let j=0; j < boardSizeY-4; j++){ if (moves_lst[i][j] == player && moves_lst[i][j+1] == player && moves_lst[i][j+2] == player && moves_lst[i][j+3] == player && moves_lst[i][j+4] == player){ return true; } } } //vertical for (let i = 0; i < boardSizeX-4; i++){ for (let j=0; j < boardSizeY; j++){ if (moves_lst[i][j] == player && moves_lst[i+1][j] == player && moves_lst[i+2][j] == player && moves_lst[i+3][j] == player && moves_lst[i+4][j] == player){ return true; } } } //diagonal right for (let i = 0; i < boardSizeX-4; i++){ for (let j=0; j < boardSizeY-4; j++){ if (moves_lst[i][j] == player && moves_lst[i+1][j+1] == player && moves_lst[i+2][j+2] == player && moves_lst[i+3][j+3] == player && moves_lst[i+4][j+4] == player){ return true; } } } //diagonal left for (let i = 3; i < boardSizeX; i++){ for (let j=0; j < boardSizeY-4; j++){ if (moves_lst[i][j] == player && moves_lst[i-1][j+1] == player && moves_lst[i-2][j+2] == player && moves_lst[i-3][j+3] == player && moves_lst[i-4][j+4] == player){ return true; } } } }
Reflection:
In general, I want to improve the algorithm for the checking function. Also, the current codes only allow modification directly on the codes. I want to make it more user friendly by allowing to make changes on the displaying screen.
Below is my p5.js screen: