如何在pygame中让敌人跟随玩家? [英] How to make enemy follow player in pygame?

查看:47
本文介绍了如何在pygame中让敌人跟随玩家?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经用 pygame.draw.rect 创建了一个小游戏,到目前为止我已经创建了一个可以在屏幕上移动的玩家和一个现在什么都不做的敌人.如果我进入一定距离(比如 100 像素),我希望敌人在屏幕上跟随玩家.我将如何定义这个?我的玩家从 x = 300 和 y = 300 开始,敌人从 x = 500 和 y = 400 开始.

Ok, I've created a small game with pygame.draw.rect and so far I have created a player who can move around on the screen and an enemy who doesn't do anything as of right now. I would like the enemy to follow the player around on the screen if I come within a certain distance (say 100 pixels). How would I define this? My player starts at x = 300 and y = 300, the enemy starts at x = 500 and 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()

推荐答案

首先你必须解决一个问题.变量 enemy_xenemy_y 被声明了两次.Onec 全局和一次在 gameLoop 中.保留全局变量,但删除函数中的局部变量:

First you have to solve an issue. The variables enemy_x and enemy_y are declared twice. Onec global and once inside the gameLoop. Keep the global variables, but delete the local variables in the function:

enemy_x = 500
enemy_y = 400

# [...]

def gameLoop():

     global enemy_x, enemy_y

     # [...]

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

定义敌人和玩家之间的阈值距离,该距离激活和停用跟随并定义敌人的速度:

Define a threshold distance between the enemy and the player, which activates and deactivates the following up and define the speed of the enemy:

例如

enemySpeed = 5
min_dist = 200

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

To make the enemy follow player you have to calculate the distance between the enemy and the player:

delta_x = lead_x - enemy_x
delta_y = lead_y - enemy_y

检查玩家是否离敌人足够近.测试是否在两个方向(x 和 y)上都低于阈值.确定敌人沿 x 轴或 y 轴的步数:

Check if the player is close enough to the enemy. Test whether the threshold is undershot in both directions (x and y). Decide i the enemy steps along the x or y axis:

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

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

If the enemy is far away enough on both axis (more then 1 step), the the axis for the step can be chosen randomly. Note this is optional:

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

与敌人一起走一步,但要限制与玩家的距离(敌人不应该越过"玩家):

Do a step with the enemy, but limit the step by the distance to the player (the enemy should not step "over" the player):

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)

    # [...]

这篇关于如何在pygame中让敌人跟随玩家?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆