Search code examples
pythonpygamepacman

Pygame Pacman ghost, random change direction


I am creating a pacman game, so far everything works aside from the ghosts, when a ghost collides against a wall the class bellow is called. However as you can see self.a returns a str, but I need it to be applied to my ghost sprites, Ghost1,Ghost2, etc. So it calls, Ghost1.a and the ghost moves accordingly.

Any help would be appreciated, thank you.

class Ghost_move(object):
    def __init__(self,g_speed):
        super(Ghost_move, self).__init__()
        self.left=".rect.x-=g_speed"
        self.right=".rect.x+=g_speed"
        self.up=".rect.y-=g_speed"
        self.down=".rect.y+=g_speed"
        self.direction=self.left,self.right,self.up,self.down
        self.a=random.choice(self.direction)

Solution

  • As abccd already pointed out, it is a bad idea to put source code, that you want to be executed into strings. The solution that is nearest to yours is defining functions for left, right, up, down. Then you can store those functions in directions and execute a randomly chosen one:

    class Ghost_move(object):
        def __init__(self,g_speed):
            super(Ghost_move, self).__init__()
            self.g_speed = g_speed
            self.directions = self.left, self.right, self.up, self.down
            self.a = random.choice(self.directions)
        def left(self):
            self.rect.x -= self.g_speed
        def right(self):
            self.rect.x += self.g_speed
        def up(self):
            self.rect.y -= self.g_speed
        def down(self):
            self.rect.y += self.g_speed
    

    Now self.a is a function that you can call. For example ghost1.a() would move ghost1 randomly in one of the four directions. But be careful, because a is just set once and therefore ghost1.a() always moves this ghost in the same direction and does not choose a random direction everytime you call it.


    A different approach is to do it with vectors:

    class Ghost_move(object):
        def __init__(self,g_speed):
            super(Ghost_move, self).__init__()
            self.left = (-g_speed, 0)
            self.right = (g_speed, 0)
            self.up = (0, -g_speed)
            self.down = (0, g_speed)
            self.directions = self.left, self.right, self.up, self.down
            self.random_dir = random.choice(self.directions)
        def a():
            self.rect.x += self.random_dir[0]
            self.rect.y += self.random_dir[1]
    

    The usage is the same as before, you would just call a() on a ghost.