2048游戏核心逻辑代码

main(){
  List a = [
    0,2,0,2,
    0,0,4,4,
    2,0,4,0,
    2,4,0,2
  ];

  List temp = right(a);  //change to others later,
  List result = [[],[],[],[]];
  for(int i=0; i<16; i++){
    result[i%4].add(temp[i]);
  }

  for(int i=0; i<result.length; i++){
    print(result[i]);
  }
}

right(List x){
  x = x.reversed.toList();
  x = left(x);
  x = x.reversed.toList();
  List temp = [[],[],[],[]];
  for(int i=0; i<x.length; i++){
    temp[i%4].add(x[i]);
  }

  return x;
}

left(List x){
  List temp = [[],[],[],[]];
  for(int i=0; i<16; i++){
    temp[i~/4].add(x[i]);
  }
  x = [];
  for(int i=0; i<temp.length; i++){
    x.addAll(merge(temp[i]));
  }
  temp = [[],[],[],[]];
  for(int i=0; i<16; i++){
    temp[i%4].add(x[i]);
  }
  x = [];
  for(int i=0; i<temp.length; i++){
    x.addAll(temp[i]);
  }
  return x;
}

up(List x){
  List temp = [[],[],[],[]];
  for(int i=0; i<16; i++){
    temp[i%4].add(x[i]);
  }
  x = [];
  for(int i=0; i<temp.length; i++){
    x.addAll(merge(temp[i]));
  }
  return x;
}

down(List x){
  x = x.reversed.toList();
  x = up(x);
  return x.reversed.toList();
}



merge(List arr){
  var i, nextI, len, m;
  len = arr.length;
  for(i=0; i<len; i++){
    nextI = -1;
    for(m=i+1; m<len; m++){
      if(arr[m]!=0){
        nextI = m;
        break;
      }
    }

    if(nextI!=-1){
      if(arr[i]==0){
        arr[i] = arr[nextI];
        arr[nextI] = 0;
        i -= 1;
      }else if(arr[i]==arr[nextI]){
        arr[i] = arr[i] * 2;
        arr[nextI] = 0;
      }
    }
  }
  return arr;
}

  

原文地址:https://www.cnblogs.com/pythonClub/p/10878164.html