Here are two possible solutions for Quiz #8. The first example is an attempt to be simple and readable:
function drawStairs(g:Graphics, num:int = 10, size:Number = 20, xp:Number = 0, yp:Number = 0):void{
with (g) moveTo(xp, yp), lineStyle(2, 0x000000);
var edge:Number = num * size;
var offX:Number;
var offY:Number = yp + edge
g.moveTo(xp + size, yp - size);
g.lineTo(xp, yp);
g.lineTo(xp, offY);
g.lineTo(xp + edge, offY);
for (var i:int = 0; i < num; i++){
g.moveTo(xp, yp);
xp += size;
offX = xp + size;
offY = yp - size;
g.lineTo(xp, yp);
g.lineTo(offX, offY);
g.lineTo(xp, offY);
g.moveTo(offX, offY);
yp += size;
offY = yp - size;
g.lineTo(offX, offY);
g.lineTo(xp, yp);
g.lineTo(xp, offY);
}
}
This next example is more convoluted, and while it's interesting, on a real project I would opt for the first solution:
function drawStairs(g:Graphics, num:int = 10, size:Number = 20, xp:Number = 0, yp:Number = 0):void{
with (g) moveTo(xp, yp), lineStyle(0, 0x000000);
var cmds:Vector. = new Vector.();
var dat:Vector. = new Vector.();
var edge:Number = num * size
cmds.push(1, 2, 2, 2, 1);
dat.push(xp + size, yp - size, xp, yp, xp, yp + edge, xp + edge, yp + edge, xp, yp);
num *= 2;
for (var i:int = 0; i < num; i++){
var mod:int = i % 2;
(mod == 0) ? xp += size : yp += size;
var step:Number = size * mod;
cmds.push(2, 2, 2, 1);
dat.push(xp, yp, xp + size, yp - size, xp + step, yp - size - step, xp, yp);
}
g.drawPath(cmds, dat);
}
drawPath() can be much faster than using lineTo(), moveTo() etc... but in the scenario it probably
isn't... as we are instantiating two vectors within the drawStairs function - and instantiation is always an expensive operation.