Advertisement
nawamkihafahd

Untitled

Nov 30th, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.07 KB | None | 0 0
  1. package pong;
  2.  
  3.  
  4. /**
  5. * Write a description of class Ball here.
  6. *
  7. * @author (your name)
  8. * @version (a version number or a date)
  9. */
  10. import java.awt.Color;
  11. import java.awt.Graphics;
  12. import java.util.Random;
  13. public class Ball
  14. {
  15. public int x, y, width = 25, height = 25;
  16. public int motionX, motionY;
  17. public Random random;
  18. private Pong pong;
  19. public int amountOfHits;
  20.  
  21. public Ball(Pong pong)
  22. {
  23. this.pong = pong;
  24. this.random = new Random();
  25. spawn();
  26. }
  27. public void update(Paddle paddle1, Paddle paddle2)
  28. {
  29. int speed = 5;
  30. this.x += motionX * speed;
  31. this.y += motionY * speed;
  32.  
  33. if(this.y + height - motionY > pong.height || this.y + motionY < 0)
  34. {
  35. if(this.motionY < 0)
  36. {
  37. this.y = 0;
  38. this.motionY = random.nextInt(4);
  39. if(motionY == 0)
  40. {
  41. motionY = 1;
  42. }
  43. }
  44. else
  45. {
  46. this.motionY = -random.nextInt(4);
  47. this.y = pong.height - height;
  48. if(motionY == 0)
  49. {
  50. motionY = -1;
  51. }
  52. }
  53. }
  54.  
  55. if(checkCollision(paddle1) == 1)
  56. {
  57. this.motionX = 1 + (amountOfHits / 5);
  58. this.motionY = -2 + random.nextInt(4);
  59. if(motionY == 0)
  60. {
  61. motionY = 1;
  62. }
  63.  
  64. amountOfHits++;
  65. }
  66. else if(checkCollision(paddle2) == 1)
  67. {
  68. this.motionX = -1 + (amountOfHits / 5);
  69. this.motionY = -2 + random.nextInt(4);
  70. if(motionY == 0)
  71. {
  72. motionY = 1;
  73. }
  74. }
  75. if(checkCollision(paddle1) == 2)
  76. {
  77. paddle2.score++;
  78. spawn();
  79. }
  80. else if(checkCollision(paddle2) == 2)
  81. {
  82. paddle1.score++;
  83. spawn();
  84. }
  85. }
  86. public void spawn()
  87. {
  88. this.amountOfHits = 0;
  89. this.x = pong.width / 2 - this.width / 2;
  90. this.y = pong.height / 2 - this.height / 2;
  91.  
  92. this.motionY = -2 + random.nextInt(4);
  93.  
  94. if(motionY == 0)
  95. {
  96. motionY = 1;
  97. }
  98. if(random.nextBoolean())
  99. {
  100. motionX = 1;
  101. }
  102. else
  103. {
  104. motionX = -1;
  105. }
  106. }
  107. public int checkCollision(Paddle paddle)
  108. {
  109. if(this.x < paddle.x + paddle.width && this.x + width > paddle.x && this.y < paddle.y + paddle.height && this.y + height > paddle.y)
  110. {
  111. return 1;
  112. }
  113. else if((paddle.x > x && paddle.paddleNumber == 1) || (paddle.x < x - width && paddle.paddleNumber == 2))
  114. {
  115. return 2;
  116. }
  117. return 0;
  118. }
  119. public void render(Graphics g)
  120. {
  121. g.setColor(Color.WHITE);
  122. g.fillOval(x, y, width, height);
  123. }
  124. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement