Day 11: Game Loop and Computer AI

Dan Esmail - 1/11/2023

Intro

Day 11 is here and past today will finish up the last of the tic tac toe project. I may revisit things at a different point but this is the end for now. I'll get into the main game loop and the computer AI today

Game Loop

First let's get into the game loop and how everything works from there


JS
Game Loop Code

                
                    
              $('.Tac-Square').click(function(){
                if (playerCount == 1) {
                  if (gameStatus == 1) {
                    gameStatus = 0
                    if (move(currentMove,this)=='Correct') {
                      moveCounter +=1;
                      if (moveCounter == 9) {
                        if (winCheck(currentMove,board) == 'win') {
                          setTimeout(function(){
                          gameStatus = 1
                          },3000)
                        }else {
                          boardReset(board);
                          addScore('cats');
                          gameStatus = 1
                        }

                      }else {
                        if (winCheck(currentMove,board) == 'win') {
                          setTimeout(function(){
                          gameStatus = 1
                          },3000)

                        }else{
                          computerAI(playerPiece,aiPiece,board)
                          moveCounter +=1;
                          if (winCheck(aiPiece,board) == 'win') {
                            setTimeout(function(){
                            gameStatus = 1
                            },3000)
                          }else {
                            gameStatus = 1
                          }
                        }
                      }
                    }else{
                      gameStatus = 1
                    }
                  }
                }else{
                  if (gameStatus == 1) {
                    gameStatus = 0
                    if (move(currentMove,this)=='Correct') {
                      moveCounter +=1;
                      if (moveCounter == 9) {
                        if (winCheck(currentMove,board) == 'win') {
                          setTimeout(function(){
                          gameStatus = 1
                          },3000)
                        }else {
                          boardReset(board);
                          addScore('cats');
                          gameStatus = 1
                        }

                      }else{
                        winCheck(currentMove,board)
                        currentMove = switchPlayer(currentMove);
                      }
                    }else{
                      gameStatus = 1
                    }
                  }
                }

              })

	    
                
            

The first thing that the game loop checks for is if there is one player or two players. I'm going to go into the one player loop first. The loop will take into effect if the player clicks on a title to place their piece. The loop will then check to see if the game status is 1. If the status is not one it won't do anything. If the status is 1 it will set the status to 0 so the player doesn't press another title. Then it will move on and check if the current move is in an open title. It will do this with the move function. If the space isn't free it will give the status back to the player to choose a different title. If the space is open the move counter is incremented to check for cats games. Then the computer checks to make sure the move counter isn't at 9 which would be a full board. If the board is filled it will look to see if the player has won. If the payer wins the score is added and the board is reset. If the payer did not win the board is reset and the cats game score is updated. Now if the board isn't full the game will still do a win check. If the player has won it will reset the board and update the score. If the game hasn't been won it will pass the game to the computer. The computer will make its move and then increment the move counter. Then the computer checks if it won. After all this the game status is set to 1 to pass the game back to the player. That is the loop when playing with one player

Next let's talk about the two player loop. The two player loop is very similar. First the computer checks the game status. If the status is 1 it will set the status to 0. After this it will check if the space is free. If the space is free it will increment the move counter and check for a cats game. If there is no cats game it will check for a win. Now if there is no win it will switch the player, set the status to 1 and start all over again.

Computer AI

There are a few function that go into the main brain of the computer while it's player the game. I'll go over all the function first and then talk about the main thought process of the computers turn.


JS
Computer Move Function

                
                    
            function computerMove(location,letter){
                $('#'+location).text(letter)
                board[location] = letter
              }
	    
                
            

First is the computers move. This will take in the location the computer wants to go to and the letter that the computer is playing with. It will write the letter to the location and then update the board array with the letter that the computer is using.


JS
Check Space Function

                
                    
              function checkSpace(location){
                let str = $('#'+location).text()
                if (str == 'x') {
                  return 'x';
                }else if (str == 'o') {
                  return 'o';
                }else{
                  return 'open'
                }
              }
	    
                
            

Next is the check space function. This function will check to see if the title is open. It will take the text from the title that the computer is trying to go to. It will then go through a nested if loop and return the text. Since we know that there are only three options for the text we make the if statement look for x and o. if it's not that we know the space is open and return open.


JS
Add Spots Function

                
                    
              function addSpots(num1,num2,num3){
                return num1 + num2 + num3
              }
	    
                
            

The next function is the add spots function. This function will take three numbers and return the sum of them. This is done so the computer can check if it has a chance to win or if the player is going to win.


JS
Find Opening Function

                
                    
              function findOpening(num1,num2,num3){
                if (checkSpace(num1)=='open') {
                  return num1
                }else if (checkSpace(num2)=='open') {
                  return num2
                }else if (checkSpace(num3)=='open') {
                  return num3
                }
              }
	    
                
            

Find opening is the next function. This function will take three numbers and use the check space function to see if they are open. The computer uses this function to find out what space is open if it has two of it's pieces in a row and needs to know where the third opening is. It will do the same if the player has two pieces in a row.


JS
Finish Three Function

                
                    
              function finishThree(num1,num2,num3,letter){
                switch (findOpening(num1,num2,num3)) {
                  case num1:
                    computerMove(num1,letter)
                    break;
                  case num2:
                    computerMove(num2,letter)
                    break;
                  case num3:
                    computerMove(num3,letter)
                    break;
                  default:

                }
              }
	    
                
            

Finally we have finish three. This function will take in the three numbers needed to make a row of three and the letter the computer is using. The find opening function will run in a switch to find the open space. Then the function will have the computer make a move based on the opening.


JS
Finish Three Function

                
                    
              function computerAI(playerLetter, comLetter, arr){
                let gameArr = []
                for (var i in arr) {
                  if (arr[i] == playerLetter) {
                    gameArr[i] = -1
                  }else if (arr[i] == comLetter) {
                    gameArr[i] = 1
                  }else{
                    gameArr[i] = 0
                  }
                }
                //check for win
                if (addSpots(gameArr[0],gameArr[4],gameArr[8]) == 2) {
                  finishThree(0,4,8,comLetter)
                  return
                }else if (addSpots(gameArr[2],gameArr[4],gameArr[6]) == 2) {
                  finishThree(2,4,6,comLetter)
                  return
                }else if (addSpots(gameArr[1],gameArr[4],gameArr[7]) == 2) {
                  finishThree(1,4,7,comLetter)
                  return
                }else if (addSpots(gameArr[3],gameArr[4],gameArr[5]) == 2) {
                  finishThree(3,4,5,comLetter)
                  return
                }else if (addSpots(gameArr[0],gameArr[1],gameArr[2]) == 2) {
                  finishThree(0,1,2,comLetter)
                  return
                }else if (addSpots(gameArr[2],gameArr[5],gameArr[8]) == 2) {
                  finishThree(2,5,8,comLetter)
                  return
                }else if (addSpots(gameArr[6],gameArr[7],gameArr[8]) == 2) {
                  finishThree(6,7,8,comLetter)
                  return
                }else if (addSpots(gameArr[0],gameArr[3],gameArr[6]) == 2) {
                  finishThree(0,3,6,comLetter)
                  return
                }
                //check if oppenent will win
                if (addSpots(gameArr[0],gameArr[4],gameArr[8]) == -2) {
                  finishThree(0,4,8,comLetter)
                  return
                }else if (addSpots(gameArr[2],gameArr[4],gameArr[6]) == -2) {
                  finishThree(2,4,6,comLetter)
                  return
                }else if (addSpots(gameArr[1],gameArr[4],gameArr[7]) == -2) {
                  finishThree(1,4,7,comLetter)
                  return
                }else if (addSpots(gameArr[3],gameArr[4],gameArr[5]) == -2) {
                  finishThree(3,4,5,comLetter)
                  return
                }else if (addSpots(gameArr[0],gameArr[1],gameArr[2]) == -2) {
                  finishThree(0,1,2,comLetter)
                  return
                }else if (addSpots(gameArr[2],gameArr[5],gameArr[8]) == -2) {
                  finishThree(2,5,8,comLetter)
                  return
                }else if (addSpots(gameArr[6],gameArr[7],gameArr[8]) == -2) {
                  finishThree(6,7,8,comLetter)
                  return
                }else if (addSpots(gameArr[0],gameArr[3],gameArr[6]) == -2) {
                  finishThree(0,3,6,comLetter)
                  return
                }
                //Place a piece
                if (checkSpace(4)=='open') {
                  computerMove(4,comLetter)
                }else if (checkSpace(0)=='open') {
                  computerMove(0,comLetter)
                }else if (checkSpace(2)=='open') {
                  computerMove(2,comLetter)
                }else if (checkSpace(6)=='open') {
                  computerMove(6,comLetter)
                }else if (checkSpace(8)=='open') {
                  computerMove(8,comLetter)
                }else if (checkSpace(1)=='open') {
                  computerMove(1,comLetter)
                }else if (checkSpace(7)=='open') {
                  computerMove(7,comLetter)
                }else if (checkSpace(3)=='open') {
                  computerMove(3,comLetter)
                }else if (checkSpace(5)=='open') {
                  computerMove(5,comLetter)
                }


              }

              function checkSpace(location){
                let str = $('#'+location).text()
                if (str == 'x') {
                  return 'x';
                }else if (str == 'o') {
                  return 'o';
                }else{
                  return 'open'
                }
              }

              function computerMove(location,letter){
                $('#'+location).text(letter)
                board[location] = letter
              }

              //switch piece
              function clearScore(){
                $('.Score').text('0')
              }

              function switchPieces(obj){
                boardReset(board);
                clearScore();
                if ($(obj).text() == 'x') {
                  aiPiece = 'o'
                  playerPiece = 'x'
                }else{
                  aiPiece = 'x'
                  playerPiece = 'o'
                }
                return $(obj).text()
              }


              //game loop
              $('.Tac-Square').click(function(){
                if (playerCount == 1) {
                  if (gameStatus == 1) {
                    gameStatus = 0
                    if (move(currentMove,this)=='Correct') {
                      moveCounter +=1;
                      if (moveCounter == 9) {
                        if (winCheck(currentMove,board) == 'win') {
                          setTimeout(function(){
                          gameStatus = 1
                          },3000)
                        }else {
                          boardReset(board);
                          addScore('cats');
                          gameStatus = 1
                        }

                      }else {
                        if (winCheck(currentMove,board) == 'win') {
                          setTimeout(function(){
                          gameStatus = 1
                          },3000)

                        }else{
                          computerAI(playerPiece,aiPiece,board)
                          moveCounter +=1;
                          if (winCheck(aiPiece,board) == 'win') {
                            setTimeout(function(){
                            gameStatus = 1
                            },3000)
                          }else {
                            gameStatus = 1
                          }
                        }
                      }
                    }else{
                      gameStatus = 1
                    }
                  }
                }else{
                  if (gameStatus == 1) {
                    gameStatus = 0
                    if (move(currentMove,this)=='Correct') {
                      moveCounter +=1;
                      if (moveCounter == 9) {
                        if (winCheck(currentMove,board) == 'win') {
                          setTimeout(function(){
                          gameStatus = 1
                          },3000)
                        }else {
                          boardReset(board);
                          addScore('cats');
                          gameStatus = 1
                        }

                      }else{
                        winCheck(currentMove,board)
                        currentMove = switchPlayer(currentMove);
                      }
                    }else{
                      gameStatus = 1
                    }
                  }
                }

              })

              //Reset Game Button
              $('#reset-button').click(function(){
                boardReset(board)
              })
              //clear score button
              $('#clear-score').click(function(){
                clearScore()
              })
              //switch Piece Button clicks
              $('.switch-button').click(function(){
                currentMove = switchPieces(this)
              })

              //player count button
              $('.player-button').click(function(){
                if ($(this).text()== 'One Player') {
                  playerCount = 1;
                  boardReset(board)
                  clearScore()
                }else{
                  playerCount = 2;
                  boardReset(board)
                  clearScore()
                }
              })
	    
                
            

Now we can run all the functions together to get the computer AI function. The first thing the computer does is find out what pieces are currently on the board so it can make a decision on what title it is going to play. It does this by running a for loop against the board array. If the piece in a title is the computers it will assign a 1. If the title is the players it will assign a -1, and finally if it's open the title will be 0. This helps since the next set of code will check all 8 combos that will give the computer a win. If the computer has a plus 2 in any of these combos it will try and finish the row and win the game. If it can't win the game it will look to see if the player has any of the combos by looking for negative 2s. if neither the computer nor the player are going to win this round the computer will just play in an open tile. It will prioritize the middle first then the corners, and finally the middle sides.

Now that's everything that I have for the tic tac toe game. I'm not sure what's next but I'm sure it will put me into another research phase.



Day 1

Day 1