为什么我的计分板在pygame中不更新?

时间:2019-08-19 02:34:53

标签: python python-3.x pygame

我正在为网球比赛记分牌。停球时为什么不更新?

我尝试将缩进改组,删除for循环。

while carryOn:
    font = pygame.font.Font('freesansbold.ttf', 32)
    screen.fill(OUT)

    camden.update()
    robert.update()
    tennisball.update()

    epsilonComp = .1
    stops = []
    ballstop = abs(tennisball.speedx) < epsilonComp and abs(tennisball.speedy) < epsilonComp
    if abs(tennisball.speedx) < epsilonComp and abs(tennisball.speedy) < epsilonComp:
        stops.append(1)
        if sum(stops) == 2:
            score = 15
        elif sum(stops) == 3:
            score = 30
    scorebox = font.render(str(score), True, WHITE, BLACK)
    scoreRect = scorebox.get_rect()
    scoreRect.center = (625, 50)
    screen.blit(scorebox, scoreRect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            carryOn = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                carryOn = False



    all_sprites.update()

    # Update
    all_sprites.draw(screen)
    pygame.display.update()
    clock.tick(60)

pygame.quit()

当球停下时应更新为15,然后再次停下时应更新为30。如果有人可以解决这个问题,我可以解决其余的分数。

1 个答案:

答案 0 :(得分:1)

永远不会满足条件if sum(stops) == 2:,因为stops在每一帧中都会被初始化。 sum(stops)永远不会超过1。在主循环之前执行stops = []

stops = []
while carryOn:

    # [...]

    #stops = [] <---- DELETE this
    ballstop = abs(tennisball.speedx) < epsilonComp and abs(tennisball.speedy) < epsilonComp
    if abs(tennisball.speedx) < epsilonComp and abs(tennisball.speedy) < epsilonComp:
        stops.append(1)
        if sum(stops) == 2:
            score = 15
        elif sum(stops) == 3:
            score = 30

可能条件if sum(stops) == 2:是错误的,必须为if sum(stops) == 1:。但这取决于您的游戏逻辑。如果球在开始时处于“停止”状态,则if sum(stops) == 2:是正确的。


根据评论:

当球停止时,您必须设置状态ball_is_stopped = True。在评估球是否停止的条件下,您必须评估该状态,以便停止球不会导致跑步得分:

if not ball_is_stopped and ....
    ball_is_stopped = True

当球开始移动时,您必须重置状态,以便下一站可以增加得分。通过True来初始化状态,因为在开始时球已停止,但得分不应增加。

if abs(tennisball.speedx) > epsilonComp and abs(tennisball.speedy) > epsilonComp:
    ball_is_stopped = False

此外,stops不是列表,计数器就足够了。只要count小于3,计数器就会递增。

stops = stops+1
if stops == 4: 
    stops = 0

增加得分的完整代码如下:

scores = [0, 15, 30, 40]
stops = 0
games = 0
ball_is_stopped = True

while carryOn:

    # [...]

    epsilonComp = .1
    is_moving = abs(tennisball.speedx) > epsilonComp or abs(tennisball.speedy) > epsilonComp
    if is_moving:
        ball_is_stopped = False

    if not ball_is_stopped and not is_moving:
        ball_is_stopped = True

        stops = stops+1
        if stops == 4:
            stops = 0
            games += 1

        score = scores[stops]