AS3 code snippet: draw a star and determine its area

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.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers