Как сделать так, чтобы текст появлялся после того, как машина пересекла финишную черту sh? - PullRequest
0 голосов
/ 02 августа 2020

Итак, что я пытаюсь получить, так это текст, который появляется после того, как машина пересекает финишную sh линию, например: «Игра окончена, первая машина выиграна», но все, что я делал до сих пор, не сработало, и я надеялся, что смогу некоторая помощь здесь.

import pygame, random
import time

pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')

#Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE =(96, 96, 96)

SCREENWIDTH = 400
SCREENHEIGHT = 500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
#all_sprites_list = pygame.sprite.Group()

#player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 250
playerY = 450
playerCar_position = 0


#player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0


#player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 50
playerY_three = 450
playerCar_position_three = 0

#player4
playerIMG_four = pygame.image.load("image/yellow_car.png")
playerX_four = 200
playerY_four = 450
playerCar_position_four = 0


#Putting cars to the screen
def player(x, y):
    screen.blit(playerIMG, (x, y))

def player_two(x, y):
    screen.blit(playerIMG_two, (x, y))

def player_three(x, y):
    screen.blit(playerIMG_three, (x, y))

def player_four(x, y):
    screen.blit(playerIMG_four, (x, y))

finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 45)
players_finished = 0
placings = ["1st", "2nd", "3rd", "4th"]


def text_objects(text, font):
    textSurface = font.render(text, True, RED)
    return textSurface, textSurface.get_rect()


def message_display(text):
    largText =pygame.font.Font("Mulish-Regular.ttf", 15)
    TextSurf, TextRect = text_objects(text, largText)
    TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    time.sleep(2)


screen.blit(bg, (0, 0))

pygame.display.flip()


# Main game loop
run = True
clock = pygame.time.Clock()
#TIP - lots of our actions take place in our while loop cause we want the function/program to run consistently
while run:
    # Drawing on Screen
    screen.fill(GREEN)
    # Draw The Road
    pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
    # Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
    #Finish line
    pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
    pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
    font = pygame.font.SysFont("Impact", 35)
    text = font.render("Finish line!", 4, (150, 50, 25))
    screen.blit(text, (180 - (text.get_width() / 2), -8))


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            # Number of frames per secong e.g. 60
            clock.tick(60)

        keys = pygame.key.get_pressed()

        if keys[pygame.K_1]:
            CarSound.play()
            playerCar_position = -0.1
        if keys[pygame.K_q]:
            playerCar_position = 0.1
        if keys[pygame.K_2]:
            CarSound_two.play()
            playerCar_position_two = -0.1
        if keys[pygame.K_w]:
            playerCar_position_two = 0.1
        if keys[pygame.K_3]:
            CarSound_three.play()
            playerCar_position_three = -0.1
        if keys[pygame.K_e]:
            playerCar_position_three = 0.1
        if keys[pygame.K_4]:
            CarSound_four.play()
            playerCar_position_four = -0.1
        if keys[pygame.K_r]:
            playerCar_position_four = 0.1

        # our functions
    playerY += playerCar_position
    playerY_two += playerCar_position_two
    playerY_three += playerCar_position_three
    playerY_four += playerCar_position_four

    player(playerX, playerY)
    player_two(playerX_two, playerY_two)
    player_three(playerX_three, playerY_three)
    player_four(playerX_four, playerY_four)


    finish_line_rect = pygame.Rect(50, 70, 235, 32)

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

    # Did anyone cross the line?
    if (finish_line_rect.collidepoint(playerX, playerY)):
        if finish_text[:8] != "Player 1":  # so it doesnt do this every frame the car is intersecting
            finish_text = "Player 1 is " + placings[players_finished]
            players_finished += 1
            print("Player (one) has crossed into finish line!")


    elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
        if finish_text[:8] != "Player 2":
            print("Player one has crossed into finish line first other car lost!")
            finish_text = "Player 2 is " + placings[players_finished]
            players_finished += 1


    elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
        if finish_text[:8] != "Player 3":
            print("Player two has crossed into finish line first other car lost!")
            finish_text = "Player 3 is " + placings[players_finished]
            players_finished += 1


    elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
        if finish_text[:8] != "Player 4":
            print("Player two has crossed into finish line first other car lost!")
            finish_text = "Player 4 is " + placings[players_finished]
            players_finished += 1



            #print("Player two has crossed into finish line first other car lost!")
            #finish_text = "Player 4 is " + placings[players_finished]








    pygame.display.flip()
















pygame.quit()

1 Ответ

0 голосов
/ 02 августа 2020

Попробуйте что-нибудь вроде этого. В конце l oop, если есть финишер, отобразите текст на экране так же, как вы написали «Fini sh Line!»

if (players_finished and finish_text):
    font = pygame.font.SysFont("Impact", 35)
    text = font.render(finish_text, 4, (150, 250, 25))
    screen.blit(text, (180 - (text.get_width() / 2), -8))

Если вы хотите, чтобы всплывающее окно 'чтобы быть временным, вам нужно будет добавить таймер или счетчик, чтобы очистить finish_text, чтобы он перестал отображаться.

...