ИИ проблема (сталкивается сама с собой, хотя не должна) - PullRequest
0 голосов
/ 16 июня 2019

Я в основном пытаюсь сделать очень простой ИИ, где он использует случайные направления для движения.По какой-то причине он будет двигаться внутри себя, даже если я создал операторы If, которые этому препятствуют.Это произойдет только с координатами x, и если я изменю порядок, то произойдет с координатами y.В этом коде я изменил порядок, и он показывает.

Я не вижу проблемы и нуждаюсь в помощи быстро.Пример того, что происходит (список напечатан для просмотра):

Игрок 1 выиграл (синий)

[[205, 300], [210, 300], [215, 300], [220, 300], [225, 300], [225, 305], [225, 310], [225, 315], [225, 320], [225, 325], [225, 320]]

dir_x = -5
dir_y = 0
dir_x2 = 5
dir_y2 = 0

x = 600
y = 300
x2 = 200
y2 = 300


cool = True
list1 = []
list2 = []

player1_score = 0
player2_score = 0

speedP1,speedPN1 = 5,-5
speedP2, speedPN2 = 5, -5

while cool == True: 

        screen.fill(black)
        possible_cor = ([5,0],[-5,0],[0,5],[0,-5])
        choices = random.choice(possible_cor)
        if len(list2) != 0:
            if len(list2)%5 == 0:  
                if dir_y2 == 5:
                    possible_cor = ([5,0],[-5,0],[0,5])
                    choices = random.choice(possible_cor)
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]

                if dir_y2 == -5:

                    possible_cor = ([5,0],[-5,0],[0,-5])
                    choices = random.choice(possible_cor)
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]
                if dir_x2 == 5:

                    possible_cor = ([5,0],[0,5],[0,-5])
                    choices = random.choice(possible_cor)
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]

                if dir_x2 == -5:

                    possible_cor = ([-5,0],[0,5],[0,-5])
                    choices = random.choice(possible_cor) 
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]






        x += dir_x
        y += dir_y

        x2 += dir_x2
        y2 += dir_y2

        message_display(str(score1),20,1.9,12,text_objects2)
        message_display(str(score2),20,2.1,12,text_objects2)
        message_display((":"),20,2,12,text_objects2)

        lightbike(blue,x,y)
        lightbike(green,x2,y2)


        if speedP1 == 5 or speedPN1 == -5:
            list1.append([x,y])
        if speedP2 == 5 or speedPN2 == -5:
            list2.append([x2,y2])




        for event in pygame.event.get():
            print (event)
            #Exit 
            if event.type ==  QUIT:
                pygame.quit()
                sys.exit()
            if (event.type == KEYDOWN):

                #Player1

                if (event.key == 276): #LEFT
                    if dir_x == 0:
                        dir_x = speedPN1
                    if dir_y != 0:
                        dir_y = 0
                if (event.key == 275): #RIGHT
                    if dir_x == 0:
                        dir_x = speedP1
                    if dir_y != 0:
                        dir_y = 0
                if (event.key == 273): #UP
                    if dir_y == 0:
                        dir_y  = speedPN1
                    if dir_x != 0:
                        dir_x = 0
                if (event.key == 274): #DOWN
                    if dir_y == 0:
                        dir_y = speedP1
                    if dir_x != 0:
                        dir_x = 0

        #Boundaries
        if x + 2 > w or x - 2 < 0 or y + 2 > h or y - 2 < 0:
            print ("Player 2 Wins(Green)")
            return AI_GAME(total_score,score2+1,score1)
        if y2 + 2 > h or y2 - 2 < 0 or x2 + 2 > w or x2 - 2 < 0:
            print ("Player 1 Wins(Blue)")
            return AI_GAME(total_score,score2,score1+1)

        for i,j in zip(list1,list2):
            lightbike(blue,i[0],i[1])
            lightbike(green,j[0],j[1])
            if list1.count(i) > 1:
                print ("Player 2 Wins(Green)") 
                return AI_GAME(total_score,score2+1,score1)
            if list2.count(i) > 0:
                player2_score += 1
                if player1_score != 0:
                    print ("Player 2 Wins(Green)") 
                    return AI_GAME(total_score,score2+1,score1)
            if list1.count(j) > 0:
                player1_score += 1
                if player2_score != 0:
                    print ("Player 1 Wins(Blue)")
                    return AI_GAME(total_score,score2,score1+1)
            if list2.count(j) > 1:
                print ("Player 1 Wins(Blue)")
                print (list2)
                pygame.quit()
                sys.exit()







        if len(list1) > 500:
            del list1[0:1]
        if len(list2) > 500:
            del list2[0:1]



        pygame.display.update()
        fpsClock.tick(30)

        if score1 ==3 or score2 == 3:
            cool = False

Ответы [ 2 ]

0 голосов
/ 16 июня 2019

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

                if dir_y2 == 5:
                    possible_cor = ([5,0],[-5,0],[0,5])
                    choices = random.choice(possible_cor)
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]

                if dir_y2 == -5:

                    possible_cor = ([5,0],[-5,0],[0,-5])
                    choices = random.choice(possible_cor)
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]
                if dir_x2 == 5:

                    possible_cor = ([5,0],[0,5],[0,-5])
                    choices = random.choice(possible_cor)
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]

                if dir_x2 == -5:

                    possible_cor = ([-5,0],[0,5],[0,-5])
                    choices = random.choice(possible_cor) 
                    dir_x2 = choices[0]
                    dir_y2 = choices[1]

Я вижу то, что вы, вероятно, не приняли во внимание. Каждый блок if изменяет значения dir_x2 и dir_y2. Поэтому следующий блок if будет использовать эти измененные значения для оценки его состояния. Например, если dir_x2, dir_y2 в начале равно 0, 5, то первый блок if может изменить его на 5, 0. Однако условие третьего блока if, dir_x2 == 5, теперь выполнено, поэтому он также выполняется и может измениться dir_x2, dir_y2 далее на 0, -5. Я думаю, что это может быть не то, что вы хотите.

Если это проблема, решение состоит в том, чтобы изменить последние три if с на elif с. Теперь каждый раз, когда запускается этот фрагмент кода, будет выполнен максимум один из четырех блоков.

0 голосов
/ 16 июня 2019

Я предполагаю, что вы хотите проверить, сталкивается ли игрок с позицией (x, y) с игроком в позиции (x2, y2).
Далее (w, h) соответственно (w2, h2) - ширина и высота игроков.

Используйте объект pygame.Rect и .colliderect(), чтобы убедиться, что игроки столкнутся там на новых позициях.
Измените позиции игроков, если они не сталкиваются:

rect1 = pygame.Rect(x + dir_x, y + dir_y, w, h)
rect2 = pygame.Rect(x2 + dir_x2, y2 + dir_y2, w2, h2)

if not rect1.colliderect(rect2):

    x += dir_x
    y += dir_y

    x2 += dir_x2
    y2 += dir_y2
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...