Created
March 25, 2024 14:31
-
-
Save crispy-computing-machine/9d19ed8a4713b0c6a98f11fec57dca62 to your computer and use it in GitHub Desktop.
Rule30
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Rule30ImageGenerator { | |
private $width; | |
private $height; | |
private $image; | |
public function __construct($width, $height) { | |
$this->width = $width; | |
$this->height = $height; | |
$this->image = imagecreate($this->width, $this->height); | |
imagecolorallocate($this->image, 255, 255, 255); // Background color: white | |
} | |
public function generateRule30() { | |
// Rule 30 initial state | |
$initial_row = array_fill(0, $this->width, 0); | |
$initial_row[$this->width / 2] = 1; | |
// Generate subsequent rows based on Rule 30 | |
$rows = array($initial_row); | |
for ($y = 1; $y < $this->height; $y++) { | |
$prev_row = $rows[$y - 1]; | |
$new_row = array(); | |
for ($x = 0; $x < $this->width; $x++) { | |
$left = $prev_row[($x - 1 + $this->width) % $this->width]; | |
$center = $prev_row[$x]; | |
$right = $prev_row[($x + 1) % $this->width]; | |
$new_row[$x] = $this->applyRule($left, $center, $right); | |
} | |
$rows[] = $new_row; | |
} | |
// Draw the image | |
foreach ($rows as $y => $row) { | |
foreach ($row as $x => $cell) { | |
imagesetpixel($this->image, $x, $y, $cell ? 0 : 16777215); // Black for active cells, white for inactive | |
} | |
} | |
} | |
private function applyRule($left, $center, $right) { | |
return ($left xor ($center || $right)) ? 1 : 0; | |
} | |
public function outputImage($filename) { | |
imagepng($this->image, $filename); | |
imagedestroy($this->image); | |
} | |
} | |
// Usage example: | |
$width = 1000; // Width of the image | |
$height = 1000; // Height of the image | |
$generator = new Rule30ImageGenerator($width, $height); | |
$generator->generateRule30(); | |
$generator->outputImage('rule30.png'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment