0

I am trying to make a code that finds the red cell on the spreadsheets, and moves it up one cell. Here is what I have:

var ymax = 23;
var xmax = 23;
var playerx = 0;
var playery = 0;
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
function moveup(){
findplayer();
sheet.getRange(playerx, playery + 1).setBackground('red');
sheet.getRange(playerx, playery).setBackground('white');
}
function findplayer(){
for(var x = 1; x < xmax; x++)
  for(var y = 1; y < ymax; y++)
  {
    var cell = sheet.getRange( 'a1:z23' ).getCell(x, y).getBackground();
    if(cell = 'red'){
      var playerfound = true;
      playerx = x;
      playery = y;

    }
  }
if (playerfound = false)
{
  findplayer();
  }
 }
 function onOpen() {
 var ui = SpreadsheetApp.getUi();
 ui.createMenu('controol')
   .addItem('up', 'moveup')
   .addToUi();
 }

For some reason instead of moving the red square from T10, it just makes a new one at W22.

What am I doing wrong?

also I claim rights

Rubén
  • 34,714
  • 9
  • 70
  • 166

2 Answers2

1

This will move the red cell up by one and wrap around to the bottom when it get's to top.

function moveRedCell(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getRange(1,1,20,10);
  var cA=rg.getBackgrounds();
  var changed=false;
  for(var i=0;i<cA.length;i++){
    for(var j=0;j<cA[i].length;j++){
      if(cA[i][j]=='#ff0000' && !changed){
        if(i>0){
           cA[i][j]='#00ff00'; //assume green is default background
           cA[i-1][j]='#ff0000';
        }else{
           cA[i][j]='#00ff00'; //assume green is default background   
           cA[cA.length-1][j]='#ff0000';
        }
        changed=true;
      }
    }
  }
  rg.setBackgrounds(cA);
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
0

The following comparisons has an error:

cell = 'red'

playerfound = false

They use a single equality sign wich in JavaScript is used to assign a value to a variable, instead it should use == (abstract equality) or === (strict equality).

By the other hand, getBackground() returns the color code, not the color name, so instead of red use #ff0000.

Rubén
  • 34,714
  • 9
  • 70
  • 166