How would you have an object move randomly in an area?

Viewed 77

I have blitted 4 zombies to the screen in pygame. And the zombies need to wander in a specific region (let us say a 10 x 10 area) around where they were blitted. Apparently, making it so that after the player enters the said area, to have the zombie chase the player, is too difficult.

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()

Output

1 Answers

Here is some code that makes the enemy follow the player

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))
Related