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()
让我知道如何:
答案 0 :(得分:0)
声明2个新变量wall_hit = 0
,它将计算球击中墙的次数和max_wall_hit = 5
,这是球在退出前撞到墙壁的最大次数。在我的情况下,它会在击中墙壁5次后退出。
现在,每当球撞到墙壁时你已经改变了速度方向,我只需添加一行来将计数器wall_hit
增加1,然后将其与max_wall_hit
的限制进行比较。 wall_hit
达到最大值后,只需致电sys.exit()
。
以下是完整代码:
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()