Печать текста - Python / Pygame

В настоящее время я работаю над небольшой игрой в стиле «космические захватчики» с использованием pygame, и я хотел добиться различных результатов в зависимости от оценки / уровня здоровья. Я хочу сделать так, чтобы если вражеские корабли прошли мимо игрока и ушли с экрана, а целевой показатель еще не достигнут, я хочу, чтобы он отображал сообщение о том, что целевой счет не был достигнут.

У меня есть этот код, который, я думаю, должен позволить этому случиться:

if block.rect.y >= 600 and health >=25 and score < 70:
    font = pygame.font.Font("freesansbold.ttf", 30)
    label2 = font.render("Score target not met", 1, (0,255,0))
    label2Rect = label.get_rect()
    labelRect.center = (400, 250)

Здесь это реализовано более подробно:

while True:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
    if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
        pygame.quit()
        sys.exit()

    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        laser.play()
        k_space = True

if k_space:
    bullet = Bullet()
    bullet.rect.x = player.rect.x
    bullet.rect.y = player.rect.y
    all_sprites_list.add(bullet)
    bullet_list.add(bullet)

k_space = False






for player in player_list:

    block_hit_list = pygame.sprite.spritecollide(player, block_list, True)

    for block in block_hit_list:
        collision.play()
        block_list.remove(block)
        all_sprites_list.remove(block)
        health -= 25

        if health == 0:
            font = pygame.font.Font("freesansbold.ttf", 30)
            label = font.render("GAME OVER", 1, (255,0,0))
            labelRect = label.get_rect()
            labelRect.center = (400, 250)
            gameover.play()
            collision.stop()
            player_list.remove(player)
            all_sprites_list.remove(player)
            break












for bullet in bullet_list:

    block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

    for block in block_hit_list:
        explosion.play()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
        score += 10

        if health >= 25 and score == 70:
            win.play()
            font = pygame.font.Font("freesansbold.ttf", 30)
            label = font.render("LEVEL COMPLETE!", 1, (0,255,0))
            labelRect = label.get_rect()
            labelRect.center = (400, 250)
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            break

    if score >= 70:
        collision.stop()
        laser.stop()
        explosion.stop()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)
        block_list.remove(block)
        all_sprites_list.remove(block)
        player_list.remove(player)
        all_sprites_list.remove(player)

    if health == 0:
        laser.stop()
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

    if bullet.rect.y < -10:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

    #NOT FUNCTIONING

if block.rect.y >= 600 and health >=25 and score < 70:
    font = pygame.font.Font("freesansbold.ttf", 30)
    label2 = font.render("Score target not met", 1, (0,255,0))
    label2Rect = label.get_rect()
    labelRect.center = (400, 250)

    #NOT FUNCTIONING
font = pygame.font.Font(None, 30)
text = font.render("Score: " + str(score), True, WHITE)
textpos = text.get_rect(centerx=screen.get_width()/5)

font = pygame.font.Font(None, 30)
text2 = font.render("Health: " + str(health), True, GREEN)
textpos2 = text2.get_rect(centerx=screen.get_height())

all_sprites_list.update()

screen.blit(background, (0,0))

if label != None: 
        screen.blit(label, labelRect)

if health == 75:
    text2 = font.render("Health: " + str(health), True, YELLOW)
elif health == 50:
    text2 = font.render("Health: " + str(health), True, ORANGE)
elif health == 25:
    text2 = font.render("Health: " + str(health), True, RED)
elif health == 0:
    text = font.render(" ", True, BLACK)
    text2 = font.render(" ", True, BLACK)

if score >= 70:
    text = font.render(" ", True, BLACK)
    text2 = font.render(" ", True, BLACK)

screen.blit(text, textpos)

screen.blit(text2, textpos2)

screen.blit(label, labelRect)

all_sprites_list.draw(screen)

pygame.display.update()

clock.tick(190)

pygame.quit()

Если кто-то знает, почему текст не печатается после выполнения оператора if, id действительно ценит помощь. Спасибо.


ОБНОВИТЬ

Я только что понял, что шрифт действительно печатается на экране, однако это происходит только в том случае, если мне удается избежать столкновений со всеми вражескими кораблями и если я не стреляю пулей. Кто-нибудь знает, почему это может происходить? Спасибо


person Oscar    schedule 29.04.2014    source источник


Ответы (1)


Хммм ... Мне кажется, ты все сделал правильно. Вот часть моего кода для вывода текста на экран, который, как я знаю, работает:

font = pygame.font.Font("Fonts/Typewriter.ttf", 20)
deathCount = font.render("Deaths: "+str(deaths), 1,(255,255,255))
winTally = font.render("Wins: "+str(winCount), 1,(255, 255, 255))
screen.blit(deathCount, (5, 5))

Кроме того, если ваш оператор if не работает, я не уверен, извините: /

person Andy    schedule 29.04.2014
comment
Спасибо за ответ, я попробовал ваше предложение, но мне все равно не повезло :( Я думаю, это может быть проблема с разделом block.rect.y оператора if, но я новичок в python, поэтому я не уверен! - person Oscar; 29.04.2014
comment
Что вы пытаетесь сделать с block.rect.y и когда вы его определяете? - person Andy; 30.04.2014