Color Bar

Change Color

We'll make some bars grow in size and change color, let's switch the base function from String m, block(x,y,z,m) to Number m, block(x,y,z,m).

A bar grows longer

A black bar keeps growing at both ends.

# grow_bar
def grow_bar(x, y, z, size):
    for i in range(-size, size+1):
        block((x+i), y, z, 1)

    if size < 8:
        game.set_timer(1, grow_bar, x, y, z, size+1)

grow_bar(-8, 10,-20,1)

(If we call function bar_x instead of reconstruct from block, then the bar will grow only at one end.)

Can you make a yellow bar that grows vertically?

Changing colors

Let's start with a fixed length bar, we update m value in the timer indicating the color change. (make sure about the terminating condition!)

# barColor, m: 45 to 59
def barColor(x,y,z,m):
    for i in range(-5,6):
        block(i,y,z, m)

    if m < 59:          # !! terminating condition
        game.set_timer(1, barColor, x, y, z, m+1)

barColor(0, 5,-20, 45)      # color from linen_black: 45

Change color and size together

On top of the fixed length color changing bar, we also add size argument and vary it's value in timer to change the bar length together with color

# grow_barColor                                                                                                                                               
def grow_barColor(x,y,z,size,m):
    for i in range(-size,size+1):
        block(x+i, y,z,m)

    if size < 10:
        game.set_timer(1, grow_barColor, x, y, z, size+1, m+1)

grow_barColor(0, 10,-20,1, 45)

In grow_barColor(), the for loop builds a whole new longer bar replacing the previous one after each time delay. So we always see a bar of single color.

Multi-color bar

Try to make a multi-color bar, instead of making a bar and increase it's size, now we just add more color blocks to both ends of the existing bar to make a multi-color bar.

# multi_colorBar, d is the distance from the center
def multi_colorBar(x,y,z,d,m):
    block(x-d, y,z,m)
    block(x+d, y,z,m)

    if d < 10:
        game.set_timer(1, multi_colorBar, x, y, z, d+1, m+1)

multi_colorBar(0, 15, -20, 0, 45)

CodeCraft is handy to visualize how recursion and for loop behaves.

Use list in multi_colorBar Let's use list to store the values, [x-d, x+d]. Write multi_colorBar in another way:

# use list 
def multi_colorBar2(x,y,z,d,m):
    for i in [x-d, x+d]:
        block(i, y, z, m)

    if d < 10:
        game.set_timer(1, multi_colorBar2, x, y, z, d+1, m+1)

multi_colorBar2(0, 20,-20,0, 50)

Both functions work the same.

results matching ""

    No results matching ""