Табло в Pygame не приводит игроков в порядок или даже не показывает их - PullRequest
1 голос
/ 10 апреля 2019

Я потратил около 2 недель на создание игры в Pygame, и я почти закончил, единственная часть, которую я пытаюсь добавить, - это табло для первого и последнего места (причина, по которой я это сделал, потому что я не был слишком уверен, как создать средний рейтинг или места).

Я создал способ проверить, является ли один из четырех игроков первым. Сначала проверяется, на какой части дорожки находится игрок (сверху, снизу, слева или справа). Затем он проверяет, больше или равно количество кругов игроков, чем количество кругов других игроков, и увеличивается, когда вы пересекаете финишную черту. Затем он проверяет, сколько сегментов вы прошли. Это проверяется после того, как вы пройдете верхнюю левую нижнюю или правую часть экрана, количество сегментов будет увеличено. Затем в зависимости от того, где находится игрок на экране, будет сравниваться позиция x или y (например, если игрок находится в верхней части экрана, он проверяет, является ли xpos (позиция x)> всеми остальными xpos. других игроков) Остальные показаны в коде.

diagram

if player_one.speed_y <= -1 and player_one.ypos > 30 and player_one.ypos < 662 and player_one.xpos < 100 and player_one.xpos > 0: #SHOWS WHICH PART OF TEH TRACK THE CHARACTER IS ON
        direction_one = "left" #meaning you are on the left side of the track
        if segment_lock_one == False:
            segment_amount_one += 1
            segment_lock_one = True

    elif player_one.speed_y >= 1 and player_one.xpos < 1200 and player_one.xpos > 1161 and player_one.ypos > 30 and player_one.ypos < 662:
        direction_one = "right"
        if segment_lock_one == False:
            segment_amount_one += 1
            segment_lock_one = True

    elif player_one.speed_x >= 1 and player_one.ypos > 0  and player_one.ypos < 30 and player_one.xpos > 100 and player_one.xpos < 1161:
        direction_one = "top"
        if segment_lock_one == False:
            segment_amount_one += 1
            segment_lock_one = True

    elif player_one.speed_x <= -1 and player_one.ypos < 700 and player_one.ypos > 600 and player_one.xpos > 100 and player_one.xpos < 1161:
        direction_one = "bottom"
        if segment_lock_one == False:
            segment_amount_one += 1
            segment_lock_one = True

    elif player_one.xpos >= 0 and player_one.xpos <= 100 and player_one.ypos >= 0 and player_one.ypos <= 40:
        direction_one = "corner top left"
        segment_lock_one = False

    elif player_one.xpos >= 1170 and player_one.xpos <= 1200 and player_one.ypos >= 0 and player_one.ypos <= 40:
        direction_one = "corner top right"
        segment_lock_one = False

    elif player_one.xpos >= 1161 and player_one.xpos <= 1200 and player_one.ypos >= 660 and player_one.ypos <= 700:
        direction_one = "corner bottom right"
        segment_lock_one = False

    elif player_one.xpos <= 100 and player_one.xpos >= 0 and player_one.ypos <= 700 and player_one.ypos >= 660:
        direction_one = "corner bottom left"
        segment_lock_one = False


    #CHECKING FOR FIRST PLACE IN EACH OF THE PLAYERS    
    #CHECK IF PLAYER ONE IS FIRST
    if direction_one == "left":#CHECKS POSITION #CHECKS ALL OF THE IF STATEMENTS TO SEE IF IT IS FIRST OR NOT
        if player_one_laps >= player_two_laps and player_one_laps >= player_three_laps and player_one_laps >= player_four_laps:#CHECKS HOW MANY LAPS HAVE BEEN DONE AND COMPARES IT TO THE OTHERS
            if segment_amount_one >= segment_amount_two and segment_amount_one >= segment_amount_three and segment_amount_one >= segment_amount_four:#HOW MANY SEGMENTS HAVE BEEN COVERED
                if player_one.ypos < player_two.ypos and player_one.ypos < player_three.ypos and player_one.ypos < player_four.ypos:#IF IT IS LESS THAN ALL OF THE OTHERS ON THAT CERTAIN PART OF THE TRACK
                    print("1st on left (player one)")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(one_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, one_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))

    if direction_one == "top":
        if player_one_laps >= player_two_laps and player_one_laps >= player_three_laps and player_one_laps >= player_four_laps:
            if segment_amount_one >= segment_amount_two and segment_amount_one >= segment_amount_three and segment_amount_one >= segment_amount_four:
                if player_one.xpos > player_two.xpos and player_one.xpos > player_three.xpos and player_one.xpos > player_four.xpos:
                    print("1st on top (player one)")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(one_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, one_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))



    if direction_one == "right":
        if player_one_laps >= player_two_laps and player_one_laps >= player_three_laps and player_one_laps >= player_four_laps:
            if segment_amount_one >= segment_amount_two and segment_amount_one >= segment_amount_three and segment_amount_one >= segment_amount_four:
                if player_one.ypos > player_two.ypos and player_one.ypos > player_three.ypos and player_one.ypos > player_four.ypos:
                    print("1st on right (player one)")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(one_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, one_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))

    if direction_one == "bottom":
        if player_one_laps >= player_two_laps and player_one_laps >= player_three_laps and player_one_laps >= player_four_laps:
            if segment_amount_one >= segment_amount_two and segment_amount_one >= segment_amount_three and segment_amount_one >= segment_amount_four:
                if player_one.xpos < player_two.xpos and player_one.xpos < player_three.xpos and player_one.xpos < player_four.xpos:
                    print("1st on bottom (player one)")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(one_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, one_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))

    elif direction_one == "corner top left" or direction_one == "corner top right" or direction_one == "corner bottom right" or direction_one == "corner bottom left":
        pass


################################################################################################
    #CHECK IF PLAYER TWO IS FIRST
    if player_two.xpos <= 100 and player_two.xpos >= 0 and player_two.ypos >= 30 and player_two.ypos <= 660:#BASICALLY THE DIRECTION AND CHECKS IF IT IS ON THE CORRECT PART OF THE TRACK #on that certain part of the track
        if player_two_laps >= player_three_laps and player_two_laps >= player_one_laps and player_two_laps >= player_four_laps: #how many laps have been covered
            if segment_amount_two >= segment_amount_one and segment_amount_two >= segment_amount_three and segment_amount_two >= segment_amount_four:#checks how many segments have been covered (should be 12 altogether at the end)
                if player_two.ypos < player_one.ypos and player_two.ypos < player_three.ypos and player_two.ypos < player_four.ypos:#checks if the player is furthest ahead
                    print("1st on left")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(two_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, two_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))

    if player_two.ypos >= 0 and player_two.ypos <= 30 and player_two.xpos >= 100 and player_two.xpos <= 1100:
        if player_two_laps >= player_three_laps and player_two_laps >= player_one_laps and player_two_laps >= player_four_laps:
            if segment_amount_two >= segment_amount_one and segment_amount_two >= segment_amount_three and segment_amount_two >= segment_amount_four:
                if player_two.xpos > player_one.xpos and player_two.xpos > player_three.xpos and player_two.xpos > player_four.xpos:
                    print("1st on top")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(two_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, two_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))


    if player_two.xpos >= 1151 and player_two.xpos <= 1200 and player_two.ypos >= 30 and player_two.ypos <= 660:
        if player_two_laps >= player_three_laps and player_two_laps >= player_one_laps and player_two_laps >= player_four_laps:
            if segment_amount_two >= segment_amount_one and segment_amount_two >= segment_amount_three and segment_amount_two >= segment_amount_four:
                if player_two.ypos > player_one.ypos and player_two.ypos > player_three.ypos and player_two.ypos > player_four.ypos:
                    print("1st on right")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(two_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, two_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))

    if player_two.ypos >= 600 and player_two.ypos <= 700 and player_two.xpos >= 100 and player_two.xpos <= 1100:
        if player_two_laps >= player_three_laps and player_two_laps >= player_one_laps and player_two_laps >= player_four_laps:
            if segment_amount_two >= segment_amount_one and segment_amount_two >= segment_amount_three and segment_amount_two >= segment_amount_four:
                if player_two.xpos < player_one.xpos and player_two.xpos < player_three.xpos and player_two.xpos < player_four.xpos:            
                    print("1st on bottom")
                    basicfont = pygame.font.SysFont('OCRB', 40)
                    texto = basicfont.render('1st: ' + (" ") +  str(two_type), True, (0, 125, 255), (0, 0, 0))
                    logo_first = Player(200, 400, two_character_pic, 60, 60)
                    logo_first.draw()
                    textrecto = texto.get_rect()
                    textrecto.centerx = screen.get_rect().centerx
                    textrecto.centery = screen.get_rect().centery
                    screen.blit(texto, (200, 600))


    if player_two.ypos < 20 and player_two.ypos > 0 and player_two.xpos < 80 and player_two.xpos > 0: #TOP LEFT CORNER
        pass

    if player_two.ypos > 0 and player_two.ypos < 20 and player_two.xpos > 1200 and player_two.xpos < 1250: #TOP RIGHT CORNER
        pass

    if player_two.xpos > 1200 and player_two.xpos < 1250 and player_two.ypos > 680 and player_two.ypos < 700: #BOTTOM RIGHT CORNER
        pass

    if player_two.xpos < 80 and player_two.xpos > 0 and player_two.ypos > 670 and player_two.ypos < 700: #BOTTOM LEFT CORNER
        pass

В результате игрок 1 не может быть показан, когда первый, и любой другой игрок не может быть показан, когда он последний, и на определенных участках дорожки ни один игрок не появляется.

Ответы [ 2 ]

2 голосов
/ 11 апреля 2019

Если бы трек всегда был выпуклым многоугольником, я бы использовал угол между игроком и начинал с вершины в центре вашего трека.

Затем вы можете использовать круг * 360 + угол, чтобы сравнить прогресс игроков. Как показано здесь

Быстрый и безобразный пример кода, решение - методы get_angle и Player.get_angular_score:

import pygame
import sys
import time
import math
from collections import namedtuple

Point = namedtuple('Point', ('x','y'))


def get_angle(point, other):
    dx = other.x - point.x
    dy = other.y - point.y
    return math.degrees(math.atan2(dy, dx))


class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = x
        self.laps = 0

    def get_angular_score(self, other: Point, start_angle):
        player_angle = get_angle(self, other)
        angle_between_player_and_start = player_angle - start_angle
        angle_between_player_and_start %= 360 # handle negative angle
        return angle_between_player_and_start + 360 * self.laps

def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    center = Point(320, 240)
    start = Point(50, 50)
    pygame.font.init()
    font = pygame.font.SysFont("Verdana", 30)
    player = Player(*start)
    start_angle = get_angle(start, center)
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    player.laps += 1

        keys=pygame.key.get_pressed()

        if keys[pygame.K_UP]:
            player.y -= 2
        if keys[pygame.K_DOWN]:
            player.y += 2
        if keys[pygame.K_LEFT]:
            player.x -= 2
        if keys[pygame.K_RIGHT]:
            player.x += 2

        screen.fill((0,0,0))
        pygame.draw.circle(screen, (255, 255, 0), (player.x, player.y), 4)
        pygame.draw.line(screen, (0, 0, 255), start, center)

        coords = font.render("x: {}, y: {}".format(player.x, player.y), True, (255,255,255))
        angle = font.render("Player score: {}".format(player.get_angular_score(center, start_angle)), True, (0, 255, 0))

        screen.blit(coords, (5,5))
        screen.blit(angle, (5, 400))

        pygame.display.update()
        time.sleep(.02)

if __name__=="__main__":
    main()

2 голосов
/ 10 апреля 2019

Проверенные вами чеки, за которые игрок выигрывает, очень длинные. Если вы захотите поменять таблицу лидеров на средние позиции, у вас будет МНОГО работы по обновлению этого кода.

Я бы предложил добавить что-то к вашему классу игрока, например player.score, которое будет увеличиваться по мере движения игрока по карте. Счет может увеличиваться, скажем, 100*lapNumber каждый раз, когда вы пересекаете финишную черту, 10*sectionOfCourse каждый раз, когда вы пересекаете контрольную точку, и distanceAlongSection каждый кадр, когда он движется. Таким образом, вы можете просто проверить всех своих игроков на наличие score, и вы будете знать рейтинг всех игроков.

class player()
    def update(self):
        currentSection = checkSection(self.pos)
        if(currentSection = (pastSection + 1)%totalSectionsPerLap): # NEW CHECKPOINT
            self.score += 10
            self.pastSection = currentSection
            if(currentSection == section[0]): #NEW LAP
                self.lap +=1
                self.score += 100
...