Reputation: 1
This is my code. I want to make tic toc toe game I'm stuck at check value in cell. now I want to use for loop to check cell by cell. I don't know how to write it. Pls help me. TT
function onEdit(e) {
var activeSheet = e.source.getActiveSheet();
var cell = activeSheet.getRange("B2:D4");
var data = cell.getValues();
var data1 = data[2][2];
if(cell.getValues !== [["","",""],["","",""],["","",""]]){
Logger.log(cell.getValues());
Logger.log(data1)
for (var i = 2; i < 5; i++)
{
Logger.log("for1");
for (var j = 2; j < 5; j++)
{
Logger.log("for2");
if(data[i][j] == "X")
{
Logger.log("D")
activeSheet.getRange("H2").setValue("Playing");
}else
{
activeSheet.getRange("H2").setValues("");
Logger.log("F")
Logger.log(data1)
}
}
}
}
}
Upvotes: 0
Views: 1921
Reputation: 5543
I tried to replicate your code and found some issues.
Array comparison - Comparing array with another array will not work, you have to either compare each element or convert the array into string by using JSON.stringify(array). See example 1 below.
In your for (var i = 2; i < 5; i++)
and for (var j = 2; j < 5; j++)
, this will prompt index out of bounds once it reached 3, 4. The reason for this is the array in var data = cell.getValues()
always start at zero. Instead you could use the array size to prevent error. See example 2 below.
setValues can only accept 2 dimensional arrays. See documentation.
if else statement - The else statement will override the value of H2
if the next element in your array is not X.
example 1:
if(JSON.stringify(data) != "[[\"\",\"\",\"\"],[\"\",\"\",\"\"],[\"\",\"\",\"\"]]"){
}
example 2:
for (var i = 0; i < data.length; i++)
{
for (var j = 0; j < data[0].length; j++)
{
//some statement
}
}
This will print every value in tictactoe Range:
Code:
function tictactoe(e) {
var activeSheet = e.source.getActiveSheet();
var cell = activeSheet.getRange("B2:D4");
var data = cell.getValues();
var a1 = ['B', 'C', 'D'];
if(JSON.stringify(data) != "[[\"\",\"\",\"\"],[\"\",\"\",\"\"],[\"\",\"\",\"\"]]"){
for (var i = 0; i < data.length; i++)
{
var column = i+2;
for (var j = 0; j < data[0].length; j++)
{
Logger.log("Value in " + a1[j] + (column) +" : "+ data[i][j]);
}
}
}
}
Output:
Additional info: You can get the A1 notation of the range being populated/edited by using e.range.getA1Notation();
Upvotes: 1