Search
Write a publication
Pull to refresh

«Матрица» на javascript

Очередной раз пересматривал/перечитывал Объекты, ООП.
Ввиду желания повысить личный expirience написался такой вот скрипт 'matrix'.
В качестве условия — использовать наследование в javascript. Не сильно обращая внимания на визуальное соответствие. Главная цель — функциональное соответствие.
Имеем три объекта-класса: objMatrix и с наследованием от него objCol,objLetter.
В objMatrix собраны основные методы и свойства которые соответственно доступны всем.
objCol описывает отдельно взятую колонку матрицы, objLetter — отдельно взятую букву.

Вобщем то в коде ни строчки без комментария, там все достаточно просто и категорически понятно.
Подозреваю что то было сделано неправильно по сему хочется увидеть конструктивную критику.

js:

(function(){
/* функция взята http://javascript.ru/tutorial/object/inheritance#nasledovanie-na-klassah-funkciya-extend */
function extend(Child, Parent) {
var F = function() {}
F.prototype = Parent.prototype
Child.prototype = new F()
Child.prototype.constructor = Child
Child.superclass = Parent.prototype
}
/**
* базовый класс matrix
* набор основных методов и свойств
*/
function objMatrix(){
this.cols=this.arCols()
}
objMatrix.prototype={
/**
* ширина рабочего пространства
*/
maxWidth:500,
maxHeight:400,
arLetter:["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
/**
* случайное целое число
*/
ceilGetRand:function getRandomArbitary(min, max){
return Math.floor(Math.random() * (max - min) + min);
},
/**
* случайная буква из arLetter
*/
getLetter:function(){
return this.arLetter[this.ceilGetRand(1,26)]
},
/**
* случайное число для позиции Х
*/
getXPos:function(){
return this.ceilGetRand(1,this.maxWidth)
},
/**
* количество колонок
*/
numCols:30,
/**
* содержимое колонок
*/
arCols:function(){
this.arCol=[]
for(var iCols=this.numCols;iCols--;){
this.arCol[iCols]=new objCol()
}
},
/**
* отображение
*/
render:function(){
/**
* заполняем фон
*/
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#051807';
ctx.fillRect(0,0,500,400);
/**
* отрисовываем колонки "матрицы"
*/
for(var i=0;i<this.arCol.length;i++){
for(var j=0;j<this.arCol[i].arLet.length;j++){
/**
* определяем текущую высоту и задаем новую
*/
var curLet = this.arCol[i].arLet[j]
if(curLet.isFirst==true){
if(curLet.Y<this.arCol[i].fontSize){
curLet.Y=this.arCol[i].fontSize
}else{
curLet.Y+=this.arCol[i].fontSize
}
}else{
curLet.curLetter=this.getLetter()
if(curLet.Y<this.arCol[i].fontSize){
if(this.arCol[i].arLet[j-1].Y>this.arCol[i].fontSize){
curLet.Y=this.arCol[i].arLet[j-1].Y-this.arCol[i].fontSize
}
}else{
curLet.Y+=this.arCol[i].fontSize
}
}
/**
* параметры отрисовки
*/
ctx.fillStyle = '#05B010';
ctx.strokeStyle = "#155E16"
ctx.font = 'bold '+this.arCol[i].fontSize+'px sans-serif';
ctx.textBaseline = 'top';
ctx.fillText(curLet.curLetter, this.arCol[i].XPos, curLet.Y);
ctx.strokeText(curLet.curLetter, this.arCol[i].XPos, curLet.Y);
}
/**
* если колонка ушла вниз, то создаем новую
*/
if(curLet.isLast==true){
if(curLet.Y>this.maxHeight) {
this.arCol[i]=new objCol()
}
}
}
}
}
/**
* объект letter
* описывает отдельно взятую букву в матрице
*/
function objLetter(){
/**
* первая буква в массиве
*/
this.isFirst =false
/**
* последняя буква в массиве
*/
this.isLast =false
/**
* получаем непосредственно саму букву
*/
this.curLetter =this.getLetter()
this.Y=-20
}
/**
* объект objCol
* описывает методы и свойства для колонки в матрице
*/
function objCol(){
/**
* скорость "падения" колонки
*/
this.speed =this.ceilGetRand(5,35)
/**
* размер шрифта колонки
*/
this.fontSize =this.ceilGetRand(9,28)
/**
* позиция по Х для колонки
*/
this.XPos =this.getXPos()
/**
* количество букв в колонке
*/
this.numLet =this.ceilGetRand(5,15)
/**
* массив букв для колонки
*/
this.arLet =[]
for(var i=this.numLet;i--;){
this.arLet[i]=new objLetter()
}
this.arLet[0].isFirst=true
this.arLet[this.arLet.length-1].isLast=true
}

/**
* наследование
*/
extend(objCol, objMatrix)
extend(objLetter, objMatrix)

var canvas = document.getElementById('matrix');
if (canvas.getContext){
var matrix = new objMatrix()
matrix.render()
setInterval(function(){matrix.render()}, 150)
}
})();


и HTML:

<!DOCTYPE html>
/>
matrix




Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.