问题描述
我在 pygame 中将 4 个僵尸传送到屏幕上。僵尸需要在他们被 blit 的地方周围的特定区域(让我们说 10 x 10 区域)徘徊。显然,让玩家进入该区域后,让僵尸追击玩家,太难了。
import pygame,random,os
from pygame.locals import *
pygame.init()
scr_width = 1020
scr_height = 510
screen = pygame.display.set_mode((scr_width,scr_height))
clock = pygame.time.Clock()
images = {}
path = 'Desktop/Files/Dungeon Minigame/'
filenames = [f for f in os.listdir(path) if f.endswith('.png')]
for name in filenames:
imagename = os.path.splitext(name)[0]
images[imagename] = pygame.image.load(os.path.join(path,name))
pygame.display.set_caption('Dungeon Minigame')
font = pygame.font.SysFont('Times_New_Roman',27)
white = [240,240,240]
fps = 60
lives = 3
score = 0
playerX = 510
playerY = 220
playerxchange = 0
playerychange = 0
def player(x,y):
screen.blit(images['r_knight'],(playerX,playerY))
class Enemy:
def __init__(self):
self.x = random.randint(8,800)
self.y = random.randint(8,440)
self.moveX = 0
self.moveY = 0
def move(self):
self.speed = 3
def draw(self):
screen.blit(images['r_zombie'],(self.x,self.y))
def enemy(x,y):
screen.blit(images['r_zombie'],(x,y))
enemy_list = []
for i in range(4):
new_enemy = Enemy()
enemy_list.append(new_enemy)
while True:
for enemy in enemy_list:
enemy.move()
enemy.draw()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
clock.tick(fps)
pygame.display.update()
解决方法
这是一些让敌人跟随玩家的代码
class Enemy:
def __init__(self,x,y,images,name):
self.x = x
self.y = y
self.images = images
self.animation_count = 0
self.offset_x = random.randrange(-600,600)
self.offset_y = random.randrange(-600,600)
self.reset_offset = 0
self.bullet_cooldown = 0
self.health = 50
def main(self,display,player_pos_x,player_pos_y):
if self.reset_offset == 0:
self.offset_x = random.randrange(-400,400)
self.offset_y = random.randrange(-400,400)
self.reset_offset = random.randrange(75,100)
else:
self.reset_offset -= 1
if player_pos_x + self.offset_x > self.x]:
self.x += random.randrange(1,3)
elif player_pos_x + self.offset_x < self.x:
self.x -= random.randrange(1,3)
if player_pos_y + self.offset_y > self.y:
self.y += random.randrange(1,3)
elif player_pos_y + self.offset_y < self.y:
self.y -= random.randrange(1,3)
display.blit(image,(self.x,self.y))