Interactive Grid of Squares (Click Events) - How to Code?

Hello all,

I am lookin around for haxe & openfl code for making a 10x10 grid of squares that I can have change color if clicked on.

Specifically, they need to change colour whenever they are scrolled over while the mouse click is being held down. They must switch to whichever color they aren’t (of 2 colors, eg. red or yellow).

Got code?

There are a few ways to do it, here’s one example:

package;


import openfl.display.Bitmap;
import openfl.display.BitmapData;
import openfl.display.Sprite;
import openfl.events.MouseEvent;


class Main extends Sprite {
	
	
	private var red:BitmapData;
	private var yellow:BitmapData;
	
	
	public function new () {
		
		super ();
		
		yellow = new BitmapData (20, 20, false, 0xFFFFFF00);
		red = new BitmapData (20, 20, false, 0xFFFF0000);
		
		var bitmap, sprite;
		
		for (row in 0...10) {
			
			for (column in 0...10) {
				
				bitmap = new Bitmap (red);
				bitmap.x = 24 * column;
				bitmap.y = 24 * row;
				
				sprite = new Sprite ();
				sprite.addChild (bitmap);
				sprite.addEventListener (MouseEvent.MOUSE_OVER, sprite_onMouseOver);
				addChild (sprite);
				
			}
			
		}
		
	}
	
	
	private function sprite_onMouseOver (event:MouseEvent):Void {
		
		var bitmap:Bitmap = cast event.currentTarget.getChildAt (0);
		
		if (event.buttonDown) {
			
			if (bitmap.bitmapData == red) {
				
				bitmap.bitmapData = yellow;
				
			} else {
				
				bitmap.bitmapData = red;
				
			}
			
		}
		
	}
	
	
}
3 Likes

Thanks! Just what I needed!

The click and drag is not working perfectly, but I should be able to trouble shoot that.

Actually, is there any way you could elp me with fixing it up? It needs to change box colors from simple clicking, not just click+drag (click + hover).

Could you show me how to make these changes? I still can’t figure out this language, but I won’t give up…
I still can’t get my head around making interactivity work. In fact, I can’t even figure out how to make a simple hello world program print the the screen. I’m only able to see the result in command line or by opening the console.

Thanks for your help!

To respond to full clicks (mouse down then mouse up), use this:

sprite.addEventListener (MouseEvent.CLICK, sprite_onMouseOver);

To respond to half clicks (mouse down), use this:

sprite.addEventListener (MouseEvent.MOUSE_DOWN, sprite_onMouseOver);

To respond to half clicks AND dragging, use this:

sprite.addEventListener (MouseEvent.MOUSE_DOWN, sprite_onMouseOver);
sprite.addEventListener (MouseEvent.MOUSE_OVER, sprite_onMouseOver);

Here’s the full list:

MouseEvent.CLICK
MouseEvent.DOUBLE_CLICK
MouseEvent.MOUSE_DOWN
MouseEvent.MOUSE_MOVE
MouseEvent.MOUSE_OUT
MouseEvent.MOUSE_OVER
MouseEvent.MOUSE_UP
MouseEvent.MIDDLE_CLICK
MouseEvent.MIDDLE_MOUSE_DOWN
MouseEvent.MIDDLE_MOUSE_UP
MouseEvent.RIGHT_CLICK
MouseEvent.RIGHT_MOUSE_DOWN
MouseEvent.RIGHT_MOUSE_UP
MouseEvent.MOUSE_WHEEL
MouseEvent.ROLL_OUT
MouseEvent.ROLL_OVER