Building like Lego, Possible?

Hi everyone, I would love to build a set of modular pieces much like lego then design a script that puts those pieces together randomly but with some control is it possible?

How would those pieces align and attach with each other e.g. make sure piece A only attaches to piece B, piece C can only face Direction Z etc etc.

Would love to hear your thoughts.

cheers :)