TinyChan

New reply in topic: Random discussions thread

You are not recognized as the original poster of this topic.

:

You are required to fill in a captcha for your first 5 posts. Sorry, but this is required to stop people from posting while drunk. Please be responsible and don't drink and post!
If you receive this often, consider not clearing your cookies.

Please familiarise yourself with the rules and markup syntax before posting.


Replying to Public poster…

var mouseClick=false;
class Grid{
	constructor(w,h){
		this.w=w;this.h=h;
		//this.grid=[];for(let x=0;x<w;x++){this.grid[x]=[];for(let y=0;y<h;y++)this.grid[x][y]=false;}
		this.grid=Array.from({length:w},()=>Array(h).fill(false));
		this.clickedCell=false;
		this.clickedInside=false;
 	}
	draw(x,y,w,h){
		noFill();stroke(255,100);
		strokeWeight(3);rect(x,y,w,h);
		strokeWeight(1);
		for(let xi=0;xi<this.w;xi++){
			for(let yi=0;yi<this.h;yi++){
				if(this.grid[xi][yi]){fill(255);}else{noFill();}
				rect(x+xi*(w/this.w),y+yi*(h/this.h),w/this.w,h/this.h);
			}
		}
		let mx=floor((mouseX-x)/(w/this.w)),
				my=floor((mouseY-y)/(h/this.h));
		if(!mouseIsPressed)this.clickedInside=false;
		if(mx>=0&&mx<this.w&&my>=0&&my<this.h){
			if(mouseClick){
				this.clickedCell=this.grid[mx][my];
				this.clickedInside=true;
			}
			if(mouseIsPressed&&this.clickedInside)this.grid[mx][my]=!this.clickedCell;
		}
	}
	extractCorners(){
		let corners=[];
		for(let x=0;x<this.w;x++){
			for(let y=0;y<this.h;y++){
				if(this.grid[x][y]){
					if((x===0||!this.grid[x-1][y])&&(y===0||!this.grid[x][y-1])){corners.push({x:x,y:y});}
					if((x===this.w-1||!this.grid[x+1][y])&&(y===0||!this.grid[x][y-1])){corners.push({x:x+1,y:y});}
					if((x===0||!this.grid[x-1][y])&&(y===this.h-1||!this.grid[x][y+1])){corners.push({x:x,y:y+1});}
					if((x===this.w-1||!this.grid[x+1][y])&&(y===this.h-1||!this.grid[x][y+1])){corners.push({x:x+1,y:y+1});}
					if(x>0&&y>0&&this.grid[x-1][y]&&this.grid[x][y-1]&&!this.grid[x-1][y-1]){corners.push({x:x,y:y});}
					if(x<this.w-1&&y>0&&this.grid[x+1][y]&&this.grid[x][y-1]&&!this.grid[x+1][y-1]){corners.push({x:x+1,y:y});}
					if(x>0&&y<this.h-1&&this.grid[x-1][y]&&this.grid[x][y+1]&&!this.grid[x-1][y+1]){corners.push({x:x,y:y+1});}
					if(x<this.w-1&&y<this.h-1&&this.grid[x+1][y]&&this.grid[x][y+1]&&!this.grid[x+1][y+1]){corners.push({x:x+1,y:y+1});}
				}
			}
		}
		return corners.filter((corner,index,self)=>index===self.findIndex((c)=>c.x===corner.x&&c.y===corner.y));
	}
}
function setup(){
	createCanvas(windowWidth,windowHeight);
}
var myGrid=new Grid(24,16);
function draw(){
	background(16);
	let x=32,y=32,w=260,h=150;
	myGrid.draw(x,y,w,h);
	let corners=myGrid.extractCorners();
	stroke(255,0,0);strokeWeight(5);
	for(let i=0;i<corners.length;i++)
		point(x+corners[i].x*(w/myGrid.w),y+corners[i].y*(h/myGrid.h));
	mouseClick=false; //Should be at the bottom.
}
function mousePressed(){
	mouseClick=true;
}