суббота, 21 июля 2012 г.

Here I am, again!

Greetings! Is anybody here?
A lot of time passed, a lot of things in my life have changed, but I'm still interesting in Python programming. I'm working right now as game developer using Unity3D (C#), but I already tired of it. I dream about big interesting project where I could use Python. I think it is the most beauty language I've ever seen (after Belorussian, of course:).
And let me show you "Life"!
Just put it in Blender's text editor and run. It will build "3D-history" of life evolution and put every generation on console.


import bpy

GENS = 20   #number of generations
XMAX = 10  #X-length
YMAX = 10  #Y-length

current = [[0 for y in range(YMAX)] for x in range(XMAX)]

#Start with glider
current[0][2] = 1
current[1][2] = 1
current[2][2] = 1
current[2][1] = 1
current[1][0] = 1

next_cell = lambda x, max: 0 if x == (max - 1) else x + 1

def put_cube(x, y, z):
    bpy.ops.mesh.primitive_cube_add(location = (x * 2, y * 2, z * 2))

def count_neibouhrs(field, x, y):
    return field[x-1][y-1]+\
            field[x-1][y]+\
            field[x][y-1]+\
            field[next_cell(x, XMAX)][next_cell(y, YMAX)]+\
            field[x][next_cell(y, YMAX)]+\
            field[next_cell(x, XMAX)][y]+\
            field[x-1][next_cell(y, YMAX)]+\
            field[next_cell(x, XMAX)][y-1]

def is_alive(field, x, y):
    return (count_neibouhrs(field, x, y)==3 or (count_neibouhrs(field, x, y)==2 and field[x][y])) and 1 or 0

def draw(field, generation):
   [[put_cube(x, y, generation) for y in range(YMAX) if field[x][y]] for x in range(XMAX)]
   
for i in range(0, GENS):
    draw(current, i)
    print("Generation #" + str(i))
    for line in current:
        print(line)
    future = [[is_alive(current, x, y) for y in range(YMAX)] for x in range(XMAX)]
    current = future