Search code examples
google-sheets-macros

Tic Tac Toe in Google Sheets (Apps Script)


I'm trying to create a two player tic tac toe (no AI). I have a cell that displays an X or an O depending on whos turn it is in cell J2. If it displays and X, then I want a checkbox, when checked, for that cell to be displayed as an X, and same for O. Also, when the cells contents is deleted, I want the cell to revert to the FALSE Boolean on the checkbox(second else if). I'm pretty sure my problem is in my IF, but I am not completely sure.

function onEdit(TTT2) {
  var ss = SpreadsheetApp.getActive();
  var Range = ss.getActiveSelection();
  var Turn = SpreadsheetApp.getrange("J2").getValue();
  if(Range = ('TRUE') && Turn == ('X')) {
    spreadsheet.getActiveSelection().setValue("X"); 
  }else if(Range = ('TRUE') && Turn == ('O')){
    spreadsheet.getActiveSelection().setValue("O"); 
  }else if(Range = (''))
    spreadsheet.getActiveSelection().setValue("TRUE");
}

Edit: Found the (an?) error, it doesn't recognize the getrange. Which begs the question: How do I set the value of a cell to a variable?


Solution

  • This should help, it will check if the range is in the first three columns and rows, and then set the value to X or O and change the turn. Instead of working with getting the SpreadsheetApp, I used the e from onEdit(e) which gives you a more direct path to the selected area and its value.

    //Set board between a specific range. 
    
    function onEdit(e) {
      if(e){
      var ss = SpreadsheetApp.getActive();
      var range = e.range;
    
      //Check that its in the begining range
      if(range.getColumn() < 4 && range.getRow() < 4) {
        //Get the turn
        var turnRange = ss.getRange("J2");
        var turn = turnRange.getValue();
    
        //If the checkbox is checked
        if(range.getValue() == true){
          if(turn == 'X') {
            //set the box to X and change turn to O
            range.setValue("X");
            turnRange.setValue("O");
          }else if(turn == 'O'){
            //Set box to O and change turn to X
            range.setValue("O"); 
            turnRange.setValue("X");
          }
        }
        }
       }
    }