ball.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from turtle import Turtle
  2. from config import SCREEN_HEIGHT, SCREEN_WIDTH, PADDLE_LENGTH
  3. import time
  4. import os
  5. from random import randint
  6. STEP = 10
  7. INITIAL_SPEED = 10
  8. class Ball(Turtle):
  9. def __init__(self):
  10. super().__init__()
  11. self.shape("circle")
  12. self.setheading(randint(15, 45))
  13. self.color("white")
  14. self.speed = INITIAL_SPEED
  15. self.penup()
  16. self.goto(0, 0)
  17. def move(self):
  18. if self.ycor() >= SCREEN_HEIGHT / 2 - STEP - 20 or self.ycor() <= STEP + 20 - SCREEN_HEIGHT / 2:
  19. # os.system("mpg123 " + "sound/ping.mp3")
  20. self.hit('ver')
  21. time.sleep(1 / self.speed)
  22. self.forward(STEP)
  23. def hit(self, direction):
  24. if direction == "ver":
  25. self.setheading(-self.heading())
  26. elif direction == "hor":
  27. self.setheading(-self.heading() + 180)
  28. def is_paddle_hit(self, pl, pr):
  29. if (self.xcor() < 0):
  30. x = abs(self.xcor() - pl.xcor()) - 20
  31. y1 = pl.ycor() + PADDLE_LENGTH * 10
  32. y2 = pl.ycor() - PADDLE_LENGTH * 10
  33. else:
  34. x = pr.xcor() - self.xcor() - 20
  35. y1 = pr.ycor() + PADDLE_LENGTH * 10
  36. y2 = pr.ycor() - PADDLE_LENGTH * 10
  37. if x < 10 and self.ycor() < y1 and self.ycor() > y2: return True
  38. return False
  39. def speed_up(self):
  40. self.speed += 5
  41. def reset(self):
  42. angle = randint(15, 45)
  43. if self.heading() < 181:
  44. angle += 180
  45. self.setheading(angle)
  46. self.speed = INITIAL_SPEED
  47. self.goto(0, 0)
  48. time.sleep(0.5)