SsolGom SsolGom -4 years ago 62
Python Question

python pygame: How to exit if the number of times the ball hits the wall and the input () value are equal

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])

# A transparent surface with per-pixel alpha.
circle = pygame.Surface((60, 60), pygame.SRCALPHA)
# Draw a circle onto the `circle` surface.
pygame.draw.circle(circle, [255,0,0], [30, 30], 30)

x = 10
y = 10
x_speed = 5
y_speed = 5

done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

pygame.time.delay(20)
screen.fill((40, 40, 40))
x = x + x_speed
y = y + y_speed
if x > screen.get_width() - 30 or x < 0:
x_speed = -x_speed
if y > screen.get_height() - 30 or y < 0:
y_speed = -y_speed
# Now blit the surface.
screen.blit(circle, [x, y])
pygame.display.flip()

pygame.quit()


Let me know how to:


  1. find the number of times a ball collides with the a wall

  2. specify the maximum number of times a ball can hit the wall with and exit when the number of times the ball has hit the wall is equal to the maximum value


Answer Source

Declare 2 new variables, wall_hit = 0 which will count the number of times the ball has hit a wall and max_wall_hit = 5, which is the maximum number of times a ball can hit a wall before exiting. In my case it will exit after hitting the wall 5 times.

Now every time the ball hits a wall you already change the speed direction, I just added a line to increase the counter wall_hit by one and then compare it against the limit of max_wall_hit. Once wall_hit reaches the maximum value, just call sys.exit().

Here is the full code:

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])

# A transparent surface with per-pixel alpha.
circle = pygame.Surface((60, 60), pygame.SRCALPHA)
# Draw a circle onto the `circle` surface.
pygame.draw.circle(circle, [255,0,0], [30, 30], 30)

x = 10
y = 10
x_speed = 5
y_speed = 5
wall_hit = 0
max_wall_hit = 5

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    pygame.time.delay(20)
    screen.fill((40, 40, 40))
    x = x + x_speed
    y = y + y_speed
    if x > screen.get_width() - 30 or x < 0:
        x_speed = -x_speed
        wall_hit += 1
    if y > screen.get_height() - 30 or y < 0:
        y_speed = -y_speed
        wall_hit += 1
    if wall_hit >= max_wall_hit:
        sys.exit()
    # Now blit the surface.
    screen.blit(circle, [x, y])
    pygame.display.flip()

pygame.quit()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download