moveDown.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import 'package:flutter_2048/store/game_state.dart';
  2. class MoveDownAction {}
  3. GameState moveDown(GameState state, MoveDownAction action) {
  4. if (state.status.end) return state.clone();
  5. var clonestate = state.clone();
  6. var 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 = clonestate.mode - 1;
  12. while (true) {
  13. while (j > -1 && clonestate.getBlock(j, i).value == 0) j--;
  14. if (j < 0) 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 < clonestate.mode - 1 &&
  23. clonestate.getBlock(k, i).value ==
  24. clonestate.getBlock(k + 1, i).value &&
  25. !clonestate.getBlock(k + 1, i).needCombine) {
  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. }