Method show(self)

An invisible Drone object is really hard to understand for the beginners, next we'll add a method show(self) for the object to show itself to the player.

(continue)

Class Drone:
    ...

    def show(self):
        game.set_timer(0.2, block, self.x, self.y, self.z, 'stonebrick_carved')
        game.set_timer(0.4, block, self.x, self.y, self.z, 'air')
        game.set_timer(0.6, block, self.x, self.y, self.z, 'stonebrick_carved')
        game.set_timer(0.8, block, self.x, self.y, self.z, 'air')    

# test the show method
t = Drone(2, 3, -20)
print(t)       # Drone is at location (2,3,-20)

t.show()       # (check to see the image of flashing drone)

t.goTo(0, 5, -10)
t.show()       # (drone shows itself again, alert a problem!)

When we show the test drone t for the first time, it's image flash at it's first location; when we move to another location and show t for the second time, we see two drones show up at the same time at two different places! That's because the computer is so fast, all the commends are executed at the same time! ( at least to human eyes).

Revised show()

To dissolve the confusion, let's add a time shift in the timer in method show(). We need to use a counter variable n to count each movement, the time shift depend on the counter variable n

Revised Drone class

Class Drone:

    def __init__(self, x=0, y=1, z=-10):
        self.x = x
        self.y = y
        self.z = z
        self.n = 0

    def __str__(self):
        return "Drone is at location (%d, %d, %d) % (self.x, self.y, self.z)  

# update variable n at each move

    def moveLeft(self, steps):
        self.n += 1      
        self.x -= steps
    def moveRight(self, steps):
        self.n += 1      
        self.x += steps
    def moveUp(self, steps):
        self.n += 1      
        self.y += steps
    def moveDown(self, steps):
        self.n += 1      
        self.y -= steps
    def moveBackward(self, steps):
        self.n += 1      
        self.z += steps
    def moveForward(self, steps):
        self.n += 1      
        self.z -= steps

    def goTo(self, x,y,z):
        self.n += 1      
        self.x=x
        self.y=y
        self.z=z

    def show(self):
        game.set_timer(self.n + 0.2, block, self.x, self.y, self.z, 'diamond')
        game.set_timer(self.n + 0.4, block, self.x, self.y, self.z, 'air')
        game.set_timer(self.n + 0.6, block, self.x, self.y, self.z, 'diamond')
        game.set_timer(self.n + 0.8, block, self.x, self.y, self.z, 'air')
d=Drone(2,5,-20)
print(d.x)           # 2
d.show()

d.moveUp(5)
print(d.y)           # 10
d.show
d.moveLeft(10)      
print(d.x)           # -8
d.show()

Run the code and see the drone shows itself after each movement.

We add n to record each movement, and then add n to the timer function in method show(), so we can see the drone shows up at different location with a time delay.

results matching ""

    No results matching ""