python pygame:如果球击中墙的次数和input()值相等,如何退出

时间:2017-06-10 17:34:30

标签: python python-3.x pygame

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()

让我知道如何:

  1. 查找球与墙碰撞的次数
  2. 指定球撞到墙壁的最大次数,当球撞到墙壁的次数等于最大值时退出

1 个答案:

答案 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()