Ooer.com by Chris Neale

Mondrian Art in PHP

<?php
while ($building == 0) {
    if (
$c++ > 20 and count($block) > 0) {
        
$building = 1;
    }

    if (
count($block) >= $segments) {
        
$building = 1;
    }

    
$x = rand(1,39)*10;
    
$y = rand(1,39)*10;
    
$w = rand(3,10)*10;
    
$h = rand(3,10)*10;
    
$add = 0;
    if (
is_array($block)) {
        foreach (
$block as $bl) {
            if (!((
$x >=$bl['x'])and($x <=($bl['x']+$bl['w'])))
            and!(((
$x+$w)>=$bl['x'])and(($x+$w)<=($bl['x']+$bl['w'])))
            and!((
$x <=$bl['x'])and(($x+$w)>=($bl['x']+$bl['w'])))
            and!((
$y >=$bl['y'])and($y <=($bl['y']+$bl['h'])))
            and!(((
$y+$h)>=$bl['y'])and(($y+$h)<=($bl['y']+$bl['h'])))
            and!((
$y <=$bl['y'])and(($y+$h)>=($bl['y']+$bl['h']))) ) {
                
$add = 1;
            } else {
                
$add = 0;
                break;
            }
        }
    } else {
        
$add = 1;
    }

    if (
$add == 1) {
        
$block[$counter]['x'] = $x;
        
$block[$counter]['y'] = $y;
        
$block[$counter]['w'] = $w;
        
$block[$counter]['h'] = $h;
        
$counter++;
    }
}
?>

The placing of the colour blocks is acheived by looping through some code that randomly places a block in the grid, checks whether it overlaps any other blocks, and keeps it if it does not. If it does then the code loops through until the number of required blocks are found. As the code loops there is a variable, $add, that is set to either 0 or 1. If $add is 0 then the block is ignored because it overlaps another, if it is set to 1 then the block is added to an array so that subsequent blocks are checked to see if they overlap it.

Each time a block is added a counter is incremented. When the counter reaches the target number of blocks, or if the code loops around too many times, the loop exits. This is to stop it in cases where it randomly generates overlapping blocks too many times. While this is unlikely it is possible, and should be therefore considered.
Move to page: 1 2 3

Comments

Comments are not currently being accepted for this article.
Sidebar
Published:
10/01/2007
Views:
9794
Author:
Chris Neale
Labels:
Print:
Sidebar: