verfolgung
Deutsch   English   

7. FOLLOWING

 

 

YOU LEARN HERE...

 

how characters can move within a grid, i.e. from cell to cell, towards the object they are following.

 

 

EXAMPLES

 

 

Example: A shark tracks Nemo
 

Nemo swims horizontally back and forth and is pursued by the shark. The shark moves from cell to cell in the direction of Nemo's current position.

The shark can choose one of the 8 possible neighbouring cells at each step. The optimal direction is determined using the method
getCompassDirectionTo().

 

This method receives the position of the pursued object as a parameter.
To prevent the shark from catching Nemo immediately, we only move the shark every fifth simulation cycle.

Program:

# Gg7.py
from gamegrid import *

# --------------------- class Fish ---------------------
class Fish(Actor):
    def __init__(self):
        Actor.__init__(self, "sprites/snemo.gif")
 
    def act(self):
        self.move()
        if self.getX() == 9:
            self.turn(180)
            self.setHorzMirror(True)
        if self.getX() == 0:
            self.turn(180)
            self.setHorzMirror(False)

# --------------------- class Shark ---------------------
class Shark(Actor):
    def __init__(self):
        Actor.__init__(self, True, "sprites/shark.gif")
 
    def act(self):
        if self.nbCycles % 5 == 0 and not nemo.isRemoved():
            self.setDirection(self.getLocation().
                  getCompassDirectionTo(nemo.getLocation()))
            self.move()
        aNemo = getOneActorAt(self.getLocation(), Fish)
        if aNemo != None:
            aNemo.removeSelf()


makeGameGrid(10, 10, 60, Color.red, "sprites/reef.gif", False)
nemo = Fish()
addActor(nemo, Location(0, 1))
shark = Shark()
addActor(shark, Location(7, 9))
show()
doRun()
► Copy to clipboard

 

 

REMEMBER YOU...

 

neighbouring cells at each step. The optimal direction is determined using the method getCompassDirectionTo(). To move the pursuer more slowly, you can execute the movement only every fifth simulation cycle in its method act().

 

 

TO SOLVE BY YOURSELF

 

1.

Create an actor Fly() (fly.gif) that can be moved using the cursor keys. The fly is pursued by the actor Frog (frog.gif). Create a playing field with 20 horizontal and 20 vertical cells measuring 30 pixels and grey grid lines.
For the pursuit, you can use the programme code from example 1 as a template. When the frog reaches the cell where the fly is located, the fly is eaten.