Talking about Actionscript 3 and Flash.
Today I want to share with you a quick piece of code I wrote because I had to randomly generate a star and determine its area for a project.
It’s made with AS3 but can be easily ported in any language since the drawing routine is not inside star generation, so both generation and area calculation can be translated line by line in the language you prefer, I think it should fit well in some kind of screen transition.
Look at the result:
Click on the stage to generate a random star, parameters are shown in the upper left corner.
Here is the script:
package { import flash.display.Sprite; import flash.geom.Point; import flash.events.MouseEvent; import flash.text.TextField; public class Main extends Sprite { private var txt:TextField=new TextField(); public function Main():void { addChild(txt); txt.height=200; txt.width=200; clip(null); stage.addEventListener(MouseEvent.CLICK,clip); } private function clip(e:MouseEvent):void { var spikes:int=Math.floor(Math.random()*10)+3; var outer:Number=Math.round(Math.random()*200)+40; var inner:Number=Math.round(outer*Math.random()); var offset:Number=Math.round(Math.random()*360); var color:Number=Math.round(Math.random()*0xffffff); var star:Array=createStar(spikes,new Point(320,240),outer,inner,72) txt.text="Spikes: "+spikes+"\nOuter arm: "+outer+"\nInner arm: "+inner+"\nOffset angle: "+offset+"\nArea: "+Math.round(getArea(star)); drawPolygon(star,color); } private function createStar(arms:int,center:Point,outer:Number,inner:Number,offsetAngle:Number):Array { offsetAngle*=0.0174532925; var starArray:Array=new Array(); var r:Number; var angle:Number=Math.PI/arms; for (var i:int=0; i<2*arms; i++) { if ((i%2)==0) { r=outer; } else { r=inner; } starArray.push(new Point(center.x+Math.cos(i*angle-angle/2+offsetAngle)*r,center.y+Math.sin(i*angle-angle/2+offsetAngle)*r)); } return starArray; } private function drawPolygon(polygon:Array,color:Number):void { graphics.clear(); graphics.lineStyle(1,0x000000,1); graphics.beginFill(color,1); var n:uint=polygon.length; if (n<3) { return; } var p:Point=polygon[0]; graphics.moveTo(p.x, p.y); for (var i:uint = 1; i <= n; ++i) { p=polygon[i%n]; graphics.lineTo(p.x, p.y); } graphics.endFill(); } private function getArea(poly:Array):Number { var n:int=poly.length; var surface:Number=0; for (var i:int=0; i<n; i++) { var j:int=(i+1)%n; surface+=Point(poly[i]).x*Point(poly[j]).y; surface-=Point(poly[i]).y*Point(poly[j]).x; } surface=surface/2; return surface; } } }
Download the source code and tell me if you make something interesting out of it, maybe with some procedural color generation.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.