Inheritance in CodeCraft
Seeds
is a CodeCraft class, it's object, such as s
upon creation, is planted(show up) at location(x,z)
, it's brown color. it has methods plant()
, when we call s.plant()
, another 'brown seed' will show up at the right side(shift right 4 blocks)
Another method s.grow()
, the 'seed' will grow taller(green color) and sprout.
class Seeds:
def __init__(self, x,z):
self.x = x
self.z = z
self.plant()
def plant(self):
block(self.x, 1, self.z, 'box_brown')
self.x += 4
def grow(self):
for j in range(5):
game.set_timer(j/2, block, self.x-7, j, self.z, 'box_green')
game.set_timer(3.5, block,self.x-8, 5, self.z, 'box_lime')
game.set_timer(4, block,self.x-6, 5, self.z, 'box_lime')
# new object
s = Seeds(0, -20) # a seed at x:0
s.grow() # it grows
s.plant() # another seed at x:4
s.grow() # it grows
Corn
Corn
is a subclass of Seeds
, it inherits every thing in Seeds
, and has one more method growCorn()
, a ordinary 'seed' will grown bigger and into a yellow corn.
# child, Corn
class Corn(Seeds):
def growCorn(self):
self.grow()
game.set_timer(4.5, block,self.x-7, 5, self.z, 'box_green')
game.set_timer(5, block,self.x-7, 6, self.z, 'box_green')
game.set_timer(5, block,self.x-9, 6, self.z, 'box_lime')
game.set_timer(5, block,self.x-5, 6, self.z, 'box_lime')
for j in range(5):
game.set_timer(6+j/2, block, self.x-7, j+7, self.z, 'box_yellow')
# new object
c = Corn(0, -10)
c.grow()
for i in range(10):
c.plant()
c.growCorn()
Flower
Flower
is another subclass of Seeds
, it overrides Seeds' method
initto accept another argument
color`;
it's method growFlower()
, a object will grow bigger and into a flower with a special color.
# child, Flower
class Flower(Seeds):
def __init__(self, x,z, material):
self.x = x
self.z = z
self.m = material
def growFlower(self,m):
self.grow()
game.set_timer(4.5, block,self.x-7, 5, self.z, 'box_green')
game.set_timer(5, block,self.x-7, 6, self.z, 'box_green')
game.set_timer(5, block,self.x-9, 6, self.z, 'box_lime')
game.set_timer(5, block,self.x-5, 6, self.z, 'box_lime')
game.set_timer(6, block,self.x-7, 7, self.z, m)
game.set_timer(6, block,self.x-7, 9, self.z,m)
game.set_timer(6, block,self.x-8, 8, self.z, m)
game.set_timer(6, block,self.x-6, 8, self.z, m)
In Flower, __init__
method overrides the parent's, other than x,z
, it needs one more argument, material
(for flower color)
# some flowers
s = Flower(-10, -20)
print(s)
s.grow()
s.growFlower('linen_purple')
for i in range(4):
s.plant()
s.growFlower('linen_purple')
# flowers can have different colors
s.plant()
s.growFlower('linen_yellow')
s.plant()
s.growFlower('linen_red')
s.plant()
s.growFlower('box_pink')