| 39 | |
| 40 | |
| 41 | class Ball(object): |
| 42 | def __init__(self, screen, radius, x, y): |
| 43 | self.__screen = screen |
| 44 | self._radius = radius |
| 45 | self._xLoc = x |
| 46 | self._yLoc = y |
| 47 | self.__xVel = 7 |
| 48 | self.__yVel = 2 |
| 49 | w, h = pygame.display.get_surface().get_size() |
| 50 | self.__width = w |
| 51 | self.__height = h |
| 52 | |
| 53 | def getXVel(self): |
| 54 | return self.__xVel |
| 55 | |
| 56 | def getYVel(self): |
| 57 | return self.__yVel |
| 58 | |
| 59 | def draw(self): |
| 60 | """ |
| 61 | draws the ball onto screen. |
| 62 | """ |
| 63 | pygame.draw.circle(screen, (255, 0, 0), (self._xLoc, self._yLoc), self._radius) |
| 64 | |
| 65 | def update(self, paddle, brickwall): |
| 66 | """ |
| 67 | moves the ball at the screen. |
| 68 | contains some collision detection. |
| 69 | """ |
| 70 | self._xLoc += self.__xVel |
| 71 | self._yLoc += self.__yVel |
| 72 | # left screen wall bounce |
| 73 | if self._xLoc <= self._radius: |
| 74 | self.__xVel *= -1 |
| 75 | # right screen wall bounce |
| 76 | elif self._xLoc >= self.__width - self._radius: |
| 77 | self.__xVel *= -1 |
| 78 | # top wall bounce |
| 79 | if self._yLoc <= self._radius: |
| 80 | self.__yVel *= -1 |
| 81 | # bottom drop out |
| 82 | elif self._yLoc >= self.__width - self._radius: |
| 83 | return True |
| 84 | |
| 85 | # for bouncing off the bricks. |
| 86 | if brickwall.collide(self): |
| 87 | self.__yVel *= -1 |
| 88 | |
| 89 | # collision detection between ball and paddle |
| 90 | paddleY = paddle._yLoc |
| 91 | paddleW = paddle._width |
| 92 | paddleH = paddle._height |
| 93 | paddleX = paddle._xLoc |
| 94 | ballX = self._xLoc |
| 95 | ballY = self._yLoc |
| 96 | |
| 97 | if ((ballX + self._radius) >= paddleX and ballX <= (paddleX + paddleW)) and ( |
| 98 | (ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH) |