如何让敌人在pygame中跟随玩家?

时间:2019-01-23 03:08:04

标签: python pygame

好吧,我已经使用pygame.draw.rect创建了一个小游戏,到目前为止,我已经创建了一个可以在屏幕上移动的玩家和一个目前不做任何事情的敌人。如果我到一定距离(例如100像素)以内,我希望敌人在屏幕上跟随玩家。我该如何定义?我的玩家从x = 300和y = 300开始,敌人从x = 500和y = 400开始。

import pygame
import time
import random 
import math


pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
blue = (35,65,155)

gameDisplay = pygame.display.set_mode((1280,800))
pygame.display.set_caption('Practice Game')

#FPS
clock = pygame.time.Clock()
#player block size
block_size = 20

#enemy block size
block_sz = 30

enemy_x = 500
enemy_y = 400

#player health
playerHealth = 100

#Health image
healthImg = pygame.image.load('healthbarimg.png')
#enemy image
enemyImg = pygame.image.load('enemyimg.png')

font = pygame.font.SysFont(None, 25)

def player(block_size, playerList):
    for XnY in playerList:
        pygame.draw.rect(gameDisplay, black, [XnY[0],XnY[1],block_size,block_size])        

def enemy(block_sz):
    #gameDisplay.blit(enemyImg,(900,700))
    pygame.draw.rect(gameDisplay, blue,(enemy_x,enemy_y,block_sz,block_sz))

def playerHp(block_sz):
    gameDisplay.blit(healthImg,(10,10))
    gameDisplay.blit(healthImg,(45,10))
    gameDisplay.blit(healthImg,(80,10))

def message_to_screen(msg,color):
    screen_text = font.render(msg, True, color)
    gameDisplay.blit(screen_text, [450,350])

def gameLoop():
    gameExit = False
    gameOver = False

    lead_x = 300
    lead_y = 300

    enemy_x = 500
    enemy_y = 400

    enemy_x_change = 0
    enemy_y_change = 0

    lead_x_change = 0
    lead_y_change = 0

    healthList = []
    healthLength = 1

    playerList = []
    playerLength = 1

    randAppleX = round(random.randrange(0, 800-10))#/10.0)*10.0
    randAppleY = round(random.randrange(0, 800-10))#/10.0)*10.0


    while not gameExit:

        while gameOver == True:
            gameDisplay.fill(white)
            message_to_screen("Game over, press C to play again or Q to quit", red)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameOver = False
                    gameExit = True

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()


        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True  
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    lead_x_change = -10
                if event.key == pygame.K_RIGHT:
                    lead_x_change = 10
                if event.key == pygame.K_UP:
                    lead_y_change = -10
                if event.key == pygame.K_DOWN:
                    lead_y_change = 10   
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    lead_x_change = 0
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    lead_y_change = 0
            if lead_x >= 1280 or lead_x < 0 or lead_y >= 800 or lead_y < 0:
                gameOver = True       

            '''if enemy_x >= 900:
                enemy_x = -10 * enemySpeed                            
            if enemy_x <= 250:
                enemy_x = 10 * enemySpeed
            if enemy_y >= 700:
                enemy_y = -10 * enemySpeed
            if enemy_y <= 50:
                enemy_y = -10 * enemySpeed'''




        pygame.display.update()

        lead_x += lead_x_change
        lead_y += lead_y_change


        gameDisplay.fill(white)

        AppleThickness = 30
        pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, AppleThickness,AppleThickness])


        playerHead = []
        playerHead.append(lead_x)
        playerHead.append(lead_y)
        playerList.append(playerHead)

        if len(playerList) > playerLength:
            del playerList[0]
        player(block_size, playerList)
        enemy(block_sz)
        playerHp(block_sz)         

        pygame.display.update()

##        if lead_x >= randAppleX and lead_x <= randAppleX + AppleThickness:
##            if lead_y >= randAppleY and lead_y <= randAppleY + AppleThickness:
##                randAppleX = round(random.randrange(0, 800-10))#/10.0)*10.0
##                randAppleY = round(random.randrange(0, 800-10))#/10.0)*10.0
##                snakeLength += 1 

        if lead_x > randAppleX and lead_x < randAppleX + AppleThickness or lead_x + block_size > randAppleX and lead_x + block_size < randAppleX + AppleThickness:
            #print("x crossover")
            if lead_y > randAppleY and lead_y < randAppleY + AppleThickness:

                randAppleX = round(random.randrange(0, 800-10))#/10.0)*10.0
                randAppleY = round(random.randrange(0, 800-10))#/10.0)*10.0
                playerLength += 1 

            elif lead_y + block_size > randAppleY and lead_y + block_size < randAppleY + AppleThickness:

                randAppleX = round(random.randrange(0, 800-10))#/10.0)*10.0
                randAppleY = round(random.randrange(0, 800-10))#/10.0)*10.0
                playerLength += 1






        clock.tick(10)

    pygame.quit()
    quit()

gameLoop()

2 个答案:

答案 0 :(得分:2)

首先,您必须解决一个问题。变量enemy_xenemy_y被声明两次。 Onec全局,一次进入gameLoop内部。保留全局变量,但删除函数中的局部变量:

enemy_x = 500
enemy_y = 400

# [...]

def gameLoop():

     global enemy_x, enemy_y

     # [...]

     # enemy_x = 500 <---- delete this
     # enemy_y = 400 <---- delete this

定义敌人与玩家之间的阈值距离,该距离可激活和停用后续动作并定义敌人的速度:

例如

enemySpeed = 5
min_dist = 200

要使敌人跟随玩家,您必须计算敌人与玩家之间的距离:

delta_x = lead_x - enemy_x
delta_y = lead_y - enemy_y

检查玩家是否足够靠近敌人。测试阈值是否在两个方向(x和y)上均不足。确定我的敌人沿着x轴或y轴行走:

if abs(delta_x) <= min_dist and abs(delta_y) <= min_dist:
    enemy_move_x = abs(delta_x) > abs(delta_y)

如果敌人在两个轴上的距离都足够远(大于1步),则可以随机选择该步的轴。请注意,这是可选的:

if abs(delta_x) > enemySpeed and abs(delta_x) > enemySpeed:
    enemy_move_x = random.random() < 0.5

与敌人一起迈步,但以与玩家的距离为限(敌人不应“越过”玩家):

if enemy_move_x:
    enemy_x += min(delta_x, enemySpeed) if delta_x > 0 else max(delta_x, -enemySpeed)
else:
    enemy_y += min(delta_y, enemySpeed) if delta_y > 0 else max(delta_y, -enemySpeed)

lead_xlead_y更新之后添加代码:

enemySpeed = 5
min_dist = 200

while not gameExit:

    while gameOver == True:
        gameDisplay.fill(white)
        # [...]


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True  
        # [...]


    pygame.display.update()

    lead_x += lead_x_change
    lead_y += lead_y_change

    delta_x = lead_x - enemy_x
    delta_y = lead_y - enemy_y

    if abs(delta_x) <= min_dist and abs(delta_y) <= min_dist:
        enemy_move_x = abs(delta_x) > abs(delta_y)
        if abs(delta_x) > enemySpeed and abs(delta_x) > enemySpeed:
           enemy_move_x = random.random() < 0.5
        if enemy_move_x:
           enemy_x += min(delta_x, enemySpeed) if delta_x > 0 else max(delta_x, -enemySpeed)
        else:
           enemy_y += min(delta_y, enemySpeed) if delta_y > 0 else max(delta_y, -enemySpeed)

    gameDisplay.fill(white)

    # [...]

答案 1 :(得分:0)

您需要一个pathfinding。游戏中最常用的寻路是A* pathfinding。 Python中已经有大量的实现。

但是,A *算法将找到到目标(因此是玩家)的最短路径,这可能不是必需的。愚蠢的举动有时会给玩家时间做出反应并击退,因此,无论障碍如何,简单地朝玩家移动就足够了。情况要视情况而定。