04-08-PY-candy-sort.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. One of 3 random candies drops down the chute onto the conveyor belt and
  3. into one of the bins. The player uses the arrow keys to shift the bins so
  4. that the candy drops into the matching colored bin. There is already a Boolean
  5. key check (bins.keyDown) to detect if either of the arrows has been pressed.
  6. The code for moving the bins is already attached to the group. Ninjas should
  7. reference the timer code from Rain Catcher and Whack a Ninja.
  8. Decomposition
  9. * Candy move down the chute
  10. * Candy changes direction to moves along belt
  11. * Arrow keys control chutes (use boolean)
  12. * Timer is used to spawn new candies
  13. * Check if the correct color dropped in bins
  14. */
  15. //*************Scene Object - Initialize When Scene Starts***********//
  16. //Create score variable
  17. $this.totalScore = 0;
  18. //Create variable to compare binColor with candyColor
  19. $this.binColor = 0;
  20. if ($this.scene.state() = "PLAY") {
  21. createTimer(2000, function() {
  22. var candyColor = random(2);
  23. var nCandy = candy.clone();
  24. nCandy.color = candyColor;
  25. nCandy.frameIndex(candyColor);
  26. nCandy.x(58);
  27. nCandy.y(154);
  28. });
  29. }
  30. //boolean used to check which arrow is pressed
  31. bins.keyDown = false;
  32. //**************candy Object - Update Every Frame********************//
  33. //Candy should move only until y = 278
  34. if ($this.y() < 278) {
  35. $this.moveY(50); //move horizontally at speed 50
  36. } else if ($this.x() < 408) { //at the end of the chute
  37. $this.moveX(50); //move down at speed 50
  38. $this.y(278);
  39. } else {
  40. $this.moveY(50);
  41. }
  42. if ($this.isTouching(bins)) { //check if candy is touching bin
  43. if($this.color == $this.scene.binColor) { //candy color = bin color
  44. $this.scene.totalScore += 1;
  45. score.text($this.scene.totalScore);
  46. } else { //candy color != bin color
  47. $this.scene.totalScore -= 1;
  48. score.text($this.scene.totalScore);
  49. }
  50. $this.remove(); //candy disappears in bin whether the color matches or not
  51. }