开发者

Detecting when the ball hits the paddle in pong?

I have b开发者_运维技巧een reading through this tutorial. I am in a chapter where you can build a pong game. However I am having trouble trying to make a function that can detect when the ball hits the paddle?

It says I should do this:

Make a boolean function hit(bx, by, r, px, py, h) that returns True when the vertical coordinate of the ball (by) is between the bottom and top of the paddle, and the horizontal location of the ball (bx) is less than or equal to the radius (r) away from the front of the paddle.

I have tried this so far:

def hit(bx, by, r, px, py, h):
    if by > py and by <= h:
        if bx <= r:
            return True
    else:
        return False

...

# If this returns True then change the direction of the ball (dx).
if hit(ball_x, ball_y, radius, paddle_x, paddle_y, height):
    dx *= -1

I'm having trouble translating the quoted paragraph into code. What am I doing wrong?

Note: The expected output of this function would be:

hit(760, 100, 10, 780, 100, 100)
    False

hit(770, 100, 10, 780, 100, 100)
    True

hit(770, 200, 10, 780, 100, 100)
    True

hit(770, 210, 10, 780, 100, 100)
    False


You're not accounting for the actual locations of the items - the coordinates you have refer to a specific point on the ball and paddle. What your code does is check that the ball is above the paddle and has a bigger radius than the distance from the y-origin to the paddle, then check that it's wider than the distance from the x-origin to the paddle.

Assuming that (px, py) is the top-left corner of the paddle, you could try something like this:

def hit(bx, by, r, px, py, h):
    if by >= py and by <= py + h:
        print "Y satisfied."
        if bx <= px + r:
            print "HIT"
            return True
        print "X not satisfied."
    print "not hit."
    return False

Bear in mind this doesn't account for the ball being round (or whatever other shape you have in mind).

EDIT: If you're having issues with making it work, you could try sticking in some print statements to let you know what the values of your parameters are and what the return value is. This should give you some insights into what is actually going on.

EDIT AGAIN: Realised that there was a possibility that the function didn't return a value. Also, this code doesn't pass all the test cases - it counts the first one as a hit.


This is my 'hit' code:

def hit(bx, by, r, px, py, h):
    if bx >= px - r and py <= by <= py + h:
        True
    else:
        False

this code seems to work on the values he has us test. however when i put it into the game i have modified it to be (under the 'while True' section)

hit(ball_x, ball_y, 10, paddle_x, paddle_y, 50)
#10 and 50 are the width and height of my paddle

yet, with those calculations, my ball does not hit the paddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜