【Lua】py里py气的生命游戏示例,你的第一行代码何必是hello,world

m, n = 10, 10
world = {}
for i = 0, m - 1 do
    world[i] = {}
    for j = 0, n - 1 do
        world[i][j] = 0
    end
end
world[0][1], world[1][2], world[2][0], world[2][1], world[2][2] = 1, 1, 1, 1, 1

function deepCopy(tb)
    if tb == nil then
        return nil
    end
    local copy = {}
    for k, v in pairs(tb) do
        if type(v) == 'table' then
            copy[k] = deepCopy(v)
        else
            copy[k] = v
        end
    end
    setmetatable(copy, deepCopy(getmetatable(tb)))
    return copy
end

while(cmd ~= 'q') do
    os.execute('cls')
    local _world = deepCopy(world)
    for i = 0, m - 1 do
        for j = 0, n - 1 do
            local state = 0
            if (not ((i == 0) or (j == 0))) then
                state = state + world[i - 1][j - 1]
            end
            if (not (i == 0)) then
                state = state + world[i - 1][j]
            end
            if (not ((i == 0) or (j == n - 1))) then
                state = state + world[i - 1][j + 1]
            end
            if (not (j == 0)) then
                state = state + world[i][j - 1]
            end
            if (not (j == n - 1)) then
                state = state + world[i][j + 1]
            end
            if (not ((i == m - 1) or (j == 0))) then
                state = state + world[i + 1][j - 1]
            end
            if (not (i == m - 1)) then
                state = state + world[i + 1][j]
            end
            if (not ((i == m - 1) or (j == n - 1))) then
                state = state + world[i + 1][j + 1]
            end

            if ((state < 2) or (state > 3)) then
                _world[i][j] = 0
            else if (state == 3) then
                    _world[i][j] = 1
                end
            end

            if (_world[i][j] == 1) then
                io.write('||')
            else
                io.write('  ')
            end
        end
        io.write('\n')
    end
    world = deepCopy(_world)
    cmd = io.read()
end
Comments
登录后评论
Sign In

你是语言学家