Monday, 8 December 2014

Munching Squares

Munching Squares is a graphical that goes back to the PDP-1

The code (available on GitHub) is very simple and easy to experiment with:

  for (int x = 0; x < 256; x++) {
    for (int y = 0; y < 256; y++) {

      ch = (x ^ y) % 256;

      c2d..fillStyle = "rgb(0, 0, $ch)"
         ..fillRect(x, y, w, w)
         ..fillStyle = "rgb($ch, 0, 0)"
         ..fillRect(256 + x, y, w, w)
         ..fillStyle = "rgb(0, $ch, 0)"
         ..fillRect(x, 256 + y, w, w)
         ..fillStyle = "rgb($ch, $ch, 0)"
         ..fillRect(256 + x, 256 + y, w, w);
Changing the x^y to have constants or a different operator yields different results. As this is rather a static demo, I have not included a live Dart version this time. If you want a couple of exercises, try cycling the colours using a timer or sliders to adjust the size. Have fun with it!

Update Thanks for the suggestion from Seth Ladd to use the cascade operator '..' which helps make the code much more readable!