Advertisement
juliazhang03

Crab

Apr 30th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
  2.  
  3. /**
  4. * This class defines a crab. Crabs live on the beach. They like sand worms
  5. * (very yummy, especially the green ones).
  6. *
  7. * Version: 5
  8. *
  9. * In this version, the crab behaves as before, but we add animation of the
  10. * image.
  11. */
  12.  
  13. public class Crab extends Animal
  14. {
  15. private GreenfootImage image1;
  16. private GreenfootImage image2;
  17. private int wormsEaten;
  18.  
  19. /**
  20. * Create a crab and initialize its two images.
  21. */
  22. public Crab()
  23. {
  24. image1 = new GreenfootImage("crab2.png");
  25. image2 = new GreenfootImage("crab.png");
  26. setImage(image1);
  27. wormsEaten = 0;
  28. }
  29.  
  30. /**
  31. * Act - do whatever the crab wants to do. This method is called whenever
  32. * the 'Act' or 'Run' button gets pressed in the environment.
  33. */
  34. public void act()
  35. {
  36. checkKeypress();
  37. move();
  38. lookForWorm();
  39. switchImage();
  40. }
  41.  
  42. /**
  43. * Alternate the crab's image between image1 and image2.
  44. */
  45. public void switchImage()
  46. {
  47. if (getImage() == image1)
  48. {
  49. setImage(image1);
  50. }
  51. else
  52. {
  53. setImage(image2);
  54. }
  55. }
  56.  
  57. /**
  58. * Check whether a control key on the keyboard has been pressed.
  59. * If it has, react accordingly.
  60. */
  61. public void checkKeypress()
  62. {
  63. if (Greenfoot.isKeyDown("left"))
  64. {
  65. turn(-4);
  66. }
  67. if (Greenfoot.isKeyDown("right"))
  68. {
  69. turn(4);
  70. }
  71. if (Greenfoot.isKeyDown("up"))
  72. {
  73. turn(4);
  74. }
  75. if (Greenfoot.isKeyDown("down"))
  76. {
  77. turn(-4);
  78. }
  79. }
  80.  
  81. /**
  82. * Check whether we have stumbled upon a worm.
  83. * If we have, eat it. If not, do nothing. If we have
  84. * eaten eight worms, we win.
  85. */
  86. public void lookForWorm()
  87. {
  88. if ( canSee(Worm.class) )
  89. {
  90. eat(Worm.class);
  91. Greenfoot.playSound("slurp.wav");
  92.  
  93. wormsEaten = wormsEaten + 1;
  94. if (CrabWorld.getWorm() == 0)
  95. {
  96. Greenfoot.playSound("fanfare.wav");
  97. Greenfoot.stop();
  98. }
  99. }
  100. }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement