ActionQueue.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import AsyncTween from "./AsyncTween.js"
  2. import { Easing } from "./Easing.js"
  3. export class ActionQueue {
  4. constructor() {
  5. this.pendingActions = []
  6. }
  7. push(action) {
  8. this.pendingActions.push(action)
  9. }
  10. execute(actionType, isAllowedCallback = () => true) {
  11. return new Promise((resolve, reject) => {
  12. const actionsToRun = this.pendingActions.filter((action) => action instanceof actionType)
  13. const pending = actionsToRun.map((action) => action.execute(isAllowedCallback))
  14. Promise.all(pending).then(() => {
  15. this.pendingActions = this.pendingActions.filter((action) => !(action instanceof actionType))
  16. resolve()
  17. }, () => {
  18. this.pendingActions = this.pendingActions.filter((action) => !(action instanceof actionType))
  19. reject()
  20. })
  21. })
  22. }
  23. }
  24. export class SwapTileAction {
  25. constructor(firstTile, otherTile) {
  26. this.firstTile = firstTile
  27. this.otherTile = otherTile
  28. this.tweens = []
  29. }
  30. execute(isAllowedCallback = () => true) {
  31. return new Promise((resolve, reject) => {
  32. if(!isAllowedCallback()) {
  33. reject()
  34. return
  35. }
  36. this.tweens = [
  37. AsyncTween.create(this.firstTile.position, this.otherTile.position, 500, Easing.Elastic.EaseOut),
  38. AsyncTween.create(this.otherTile.position, this.firstTile.position, 500, Easing.Elastic.EaseOut)]
  39. Promise.all(this.tweens.map((tween) => tween.promise)).then(() => {
  40. resolve()
  41. this.tweens = []
  42. })
  43. })
  44. }
  45. }
  46. export class MatchTilesAction {
  47. constructor(tilesToMatch) {
  48. this.tilesToMatch = tilesToMatch
  49. this.tweens = []
  50. }
  51. execute(isAllowedCallback = () => true) {
  52. return new Promise((resolve, reject) => {
  53. if(!isAllowedCallback()) {
  54. reject()
  55. return
  56. }
  57. this.tweens = []
  58. this.tilesToMatch.forEach((tile) => {
  59. this.tweens.push(AsyncTween.create(tile, {scale: 0}, 500, Easing.Quadratic.EaseInOut))
  60. })
  61. Promise.all(this.tweens.map((tween) => tween.promise)).then(() => {
  62. resolve()
  63. this.tweens = []
  64. })
  65. })
  66. }
  67. }