moveUp.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import 'package:flutter_2048/store/game_state.dart';
  2. class MoveUpAction {}
  3. GameState moveUp(GameState state, MoveUpAction action) {
  4. if (state.status.end) return state.clone();
  5. var clonestate = state.clone();
  6. int i, j, k;
  7. bool isMoved = false;
  8. bool haveMove = false;
  9. bool haveCombin = false;
  10. for (i = 0; i < clonestate.mode; i++) {
  11. j = k = 0;
  12. while (true) {
  13. while (j < clonestate.mode && clonestate.getBlock(j, i).value == 0) j++;
  14. if (j > clonestate.mode - 1) break;
  15. if (j > k) {
  16. isMoved = haveMove = true;
  17. var block = clonestate.getBlock(j, i);
  18. block.needMove = true;
  19. block.needCombine = false;
  20. clonestate.swapBlock(k * clonestate.mode + i, j * clonestate.mode + i);
  21. }
  22. if (k > 0 &&
  23. clonestate.getBlock(k, i).value ==
  24. clonestate.getBlock(k - 1, i).value &&
  25. clonestate.getBlock(k - 1, i).needCombine != true) {
  26. var currentBlock = clonestate.getBlock(k, i);
  27. var prevBlock = clonestate.getBlock(k - 1, i);
  28. prevBlock.before =
  29. isMoved ? currentBlock.before : (k * clonestate.mode + i);
  30. prevBlock.current = (k - 1) * clonestate.mode + i;
  31. prevBlock.needMove = true;
  32. prevBlock.needCombine = haveCombin = true;
  33. prevBlock.value <<= 1;
  34. clonestate.status.scores += prevBlock.value;
  35. currentBlock.reset();
  36. currentBlock.current = currentBlock.before = k * clonestate.mode + i;
  37. } else {
  38. k++;
  39. }
  40. j++;
  41. }
  42. }
  43. if (haveMove || haveCombin) {
  44. clonestate.update();
  45. }
  46. return clonestate;
  47. }