moveLeft.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import 'package:flutter_2048/store/game_state.dart';
  2. class MoveLeftAction {}
  3. GameState moveLeft(GameState state, MoveLeftAction 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(i, j).value == 0) j++;
  14. if (j > clonestate.mode - 1) break;
  15. if (j > k) {
  16. isMoved = haveMove = true;
  17. var block = clonestate.getBlock(i, j);
  18. block.needMove = true;
  19. block.needCombine = false;
  20. clonestate.swapBlock(i * clonestate.mode + k, i * clonestate.mode + j);
  21. }
  22. if (k > 0 &&
  23. clonestate.getBlock(i, k).value ==
  24. clonestate.getBlock(i, k - 1).value &&
  25. clonestate.getBlock(i, k - 1).needCombine != true) {
  26. var currentBlock = clonestate.getBlock(i, k);
  27. var prevBlock = clonestate.getBlock(i, k - 1);
  28. prevBlock.before =
  29. isMoved ? currentBlock.before : (i * clonestate.mode + k);
  30. prevBlock.current = i * clonestate.mode + k - 1;
  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 = i * clonestate.mode + k;
  37. } else {
  38. k++;
  39. }
  40. j++;
  41. }
  42. }
  43. if (haveMove || haveCombin) {
  44. clonestate.update();
  45. }
  46. return clonestate;
  47. }