06-02-py-bug-invaders.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. In this game, bugs come down at random from the top of the screen and the player
  3. has to zap them. We’ll be using keyboard controls to move the ninja, but using the
  4. mouse is also acceptable.
  5. Decomposition:
  6. * bugs cloning from top at random x
  7. * keyboard controls to move ninja
  8. * bullet fired
  9. * collision with bugs adds to score
  10. */
  11. //****************Scene Object - Initialize When Scene Starts Even***************//
  12. // game variables
  13. $this.totalScore = 0;
  14. bullet.fired = false; // set up boolean to control shooting
  15. if($this.scene.state() == "PLAY") { //cloning of bugs
  16. createTimer(1000, function() {
  17. var nbug = bug.clone();
  18. nbug.x(random(720, 80)); // set bug starting position
  19. nbug.y(-80);
  20. });
  21. }
  22. //******************ninja Object - Update Every Frame Event**********************//
  23. // set up controls
  24. var rightArrowPressed = isKeyPressed(Keys.rightArrow);
  25. var leftArrowPressed = isKeyPressed(Keys.leftArrow);
  26. var spacePressed = isKeyPressed(Keys.space);
  27. if(rightArrowPressed && this.x() < 777) {
  28. $this.moveX(100);
  29. }
  30. if(leftArrowPressed && this.x() > 23) {
  31. $this.moveX(-100);
  32. }
  33. if(spacePressed && bullet.fired === false) {
  34. bullet.fired = true; //send true to bullet
  35. }
  36. //******************bug Object - Update Every Frame Event************************//
  37. if($this.y() < 600) {
  38. $this.moveY(50);
  39. $this.incrementAnimation();
  40. } else {
  41. $this.remove();
  42. $this.scene.totalScore -= 1;
  43. score.text($this.scene.totalScore);
  44. }
  45. if($this.isTouching(bullet)) {
  46. $this.remove();
  47. $this.scene.totalScore += 1;
  48. score.text($this.scene.totalScore);
  49. bullet.fired = false;
  50. }
  51. //****************bullet Object - Update Every Frame****************************//
  52. if($this.fired && $this.y() > 0) { //bullet listening for fired = true
  53. $this.moveY(-250);
  54. } else {
  55. $this.fired = false;
  56. $this.x(ninja.x()); //reset bullet to ninja.x, y
  57. $this.y(ninja.y());
  58. }