generated from mwc/project_game
I decided to have the ball check for collision with the paddle instead of having the paddle check for collision with the ball. Either way could work, but it seemed easier to have the ball do the checking since the ball will need to respond with a change in velocity anyway.
34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
# ball.py
|
|
class Ball:
|
|
character = "O"
|
|
name = "ball"
|
|
|
|
def __init__(self, position):
|
|
self.position = position
|
|
self.velocity = (1, 1)
|
|
|
|
def play_turn(self, game):
|
|
x, y = self.position
|
|
vx, vy = self.velocity
|
|
new_x = x + vx
|
|
new_y = y + vy
|
|
board_x, board_y = game.board_size
|
|
if new_x < 0 or board_x <= new_x:
|
|
self.velocity = (-vx, vy)
|
|
elif new_y < 0 or board_y <= new_y:
|
|
self.velocity = (vx, -vy)
|
|
elif self.check_for_collision_with_paddle((new_x, new_y), game):
|
|
self.velocity = (vx, -vy)
|
|
else:
|
|
self.position = (new_x, new_y)
|
|
|
|
def check_for_collision_with_paddle(self, position, game):
|
|
"""Checks whether the given position collides with a piece of the paddle.
|
|
We pass a position rather than using self.position so that we can check
|
|
potential future positions.
|
|
"""
|
|
for agent in game.get_agents_by_position()[position]:
|
|
if not isinstance(agent, Ball):
|
|
return True
|
|
|