Drone Class in CodeCraft

make a wall, use drone method removeBlock to make some holes and combine with time delay, make the holes one by one or make the holes get bigger slowly(woodPecker_)

))

CodeCraft for OOP Learning

For most people who begin coding not long and especially young students, the brand new concepts like class and object are too abstract, really confusing. Because most (if not all) of the teaching programs are in the format of lines of codes: words, numbers..., OOP is really a very hard topic for beginners.

While, not any more!

Through CodeCraft, we can learn about classes, objects, inheritance, run our programs in the game World, and see methods in action through the objects, see how inheritance works.

We'll learn about class and object through the making of a Drone class

We define various class methods to control the drone object to move up/down/left/right/forward/backward; The drone object can show itself as a flashing pumpkin(I started writing Drone at the end of Nouvember)

Applying inheritance knowledge, we define some sub-class of the Drone class, their objects inherit all the functions of the parent class, and they each have particular functions of their own: a builder can place blocks, an eliminator can make a block disappear.

Drone

We will define a Drone class, start with standard class constructor, __init__() that defines the location state variables x,y,z, with default values (0, 1, -10); then some setter and getter methods for x,y,z; followed with the standard __str__ method to represent the Drone; the Drone class also defines some object methods to perform moving functions.

Class Drone:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

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

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

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

Demo how to use the Drone class, first we create a Drone object, d, then use the object methods to perform some movements. Since d is invisible, we have to use the help of print() function to show the results of these movements:

d = Drone(10,5,-20)
print(d)        # Drone is at location (10,5,-20)

d.moveLeft(10)
print(d.x)      # 0

d.goTo(8, 20, -10)
print(d)        # Drone is at location (8, 20,-10)

===end here

results matching ""

    No results matching ""