Munching squares: Difference between revisions
(added FreeBASIC) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(70 intermediate revisions by 35 users not shown) | |||
Line 4: | Line 4: | ||
{{omit from|Lilypond}} |
{{omit from|Lilypond}} |
||
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary [[wp:color table|color table]]. |
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary [[wp:color table|color table]]. |
||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">PROC PutBigPixel(BYTE x,y,c) |
|||
BYTE i |
|||
Color=c |
|||
x=x*3+16 |
|||
y=y*12 |
|||
FOR i=0 TO 11 |
|||
DO |
|||
Plot(x,y+i) |
|||
DrawTo(x+2,y+i) |
|||
OD |
|||
RETURN |
|||
PROC Main() |
|||
BYTE |
|||
CH=$02FC, ;Internal hardware value for last key pressed |
|||
x,y |
|||
Graphics(9) |
|||
FOR y=0 TO 15 |
|||
DO |
|||
FOR x=0 TO 15 |
|||
DO |
|||
PutBigPixel(x,y,x!y) |
|||
OD |
|||
OD |
|||
DO UNTIL CH#$FF OD |
|||
CH=$FF |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Munching_squares.png Screenshot from Atari 8-bit computer] |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{libheader|GtkAda}} |
{{libheader|GtkAda}} |
||
Uses the Cairo component of GtkAda to create and save as png |
Uses the Cairo component of GtkAda to create and save as png |
||
< |
<syntaxhighlight lang="ada">with Cairo; use Cairo; |
||
with Cairo.Png; use Cairo.Png; |
with Cairo.Png; use Cairo.Png; |
||
with Cairo.Image_Surface; use Cairo.Image_Surface; |
with Cairo.Image_Surface; use Cairo.Image_Surface; |
||
Line 28: | Line 63: | ||
Status := Write_To_Png (Surface, "AdaXorPattern.png"); |
Status := Write_To_Png (Surface, "AdaXorPattern.png"); |
||
pragma Assert (Status = Cairo_Status_Success); |
pragma Assert (Status = Cairo_Status_Success); |
||
end XorPattern;</ |
end XorPattern;</syntaxhighlight> |
||
{{out}} [[Image:AdaXorPattern.png|Ada Output|200px]] |
{{out}} [[Image:AdaXorPattern.png|Ada Output|200px]] |
||
=={{header| |
=={{header|ATS}}== |
||
<syntaxhighlight lang="ats"> |
|||
#include "share/atspre_staload.hats" |
|||
(* uint2uchar0 seems to have a definition in the prelude, but no |
|||
implementation. Such incompletenesses are common, but usually |
|||
easily overcome. Here I simply redefine uint2uchar0 locally, |
|||
letting C do the casting. *) |
|||
extern castfn uint2uchar0 : uint -<> uchar |
|||
(* write_pam writes a Portable Arbitrary Map to standard output. It |
|||
XORs the positions of colors in a palette of size equal to a power |
|||
of two, containing RGB colors in the usual hex format. The palette |
|||
is otherwise arbitrary. *) |
|||
fn |
|||
write_pam {expnt : nat} |
|||
{numcolors : nat} |
|||
(* The palette size must be proven to be a power of two. *) |
|||
(pf : EXP2 (expnt, numcolors) | |
|||
palette : &array (uint, numcolors), |
|||
numcolors : uint numcolors) : void = |
|||
let |
|||
fun |
|||
loop {x, y : nat | x <= numcolors; y <= numcolors} |
|||
.<numcolors - y, numcolors - x>. |
|||
(palette : &array (uint, numcolors), |
|||
x : uint x, |
|||
y : uint y) : void = |
|||
if y = numcolors then |
|||
() |
|||
else if x = numcolors then |
|||
loop (palette, 0u, succ y) |
|||
else |
|||
let |
|||
val i = g1ofg0 (x lxor y) |
|||
(* Prove that the index is non-negative. *) |
|||
prval () = lemma_g1uint_param i |
|||
(* Test that the index is not out of bounds high. This could |
|||
be proven without a runtime check, but doing that is left |
|||
as an exercise for an advanced reader. For one thing, you |
|||
will need a more complicated version of lxor. Then you |
|||
will need to prove, or provide as an axiom, that the XOR |
|||
of two numbers of the same number of significant bits is |
|||
itself restricted to that number of bits. *) |
|||
val () = assertloc (i < numcolors) |
|||
val color = palette[i] |
|||
val r = uint2uchar0 (color >> 16) |
|||
and g = uint2uchar0 ((color >> 8) land 0xFFu) |
|||
and b = uint2uchar0 (color land 0xFFu) |
|||
in |
|||
print! (r, g, b); |
|||
loop (palette, succ x, y) |
|||
end |
|||
in |
|||
println! ("P7"); |
|||
println! ("WIDTH ", numcolors); |
|||
println! ("HEIGHT ", numcolors); |
|||
println! ("DEPTH 3"); |
|||
println! ("MAXVAL 255"); |
|||
println! ("TUPLTYPE RGB"); |
|||
println! ("ENDHDR"); |
|||
loop (palette, 0u, 0u) |
|||
end |
|||
prfn (* Produces a proof that 2**7 = 128. *) |
|||
exp2_of_7_is_128 () :<prf> EXP2 (7, 128) = |
|||
EXP2ind (EXP2ind (EXP2ind (EXP2ind |
|||
(EXP2ind (EXP2ind (EXP2ind (EXP2bas ()))))))) |
|||
implement |
|||
main0 () = |
|||
let |
|||
(* 128 RGB colors borrowed from |
|||
https://github.com/yeun/open-color *) |
|||
var palette : array (uint, 128) = |
|||
@[uint][128] |
|||
(0xe9ecefu, 0xdee2e6u, 0xced4dau, 0xadb5bdu, 0x868e96u, 0x495057u, |
|||
0x343a40u, 0x212529u, 0xfff5f5u, 0xffe3e3u, 0xffc9c9u, 0xffa8a8u, |
|||
0xff8787u, 0xff6b6bu, 0xfa5252u, 0xf03e3eu, 0xe03131u, 0xc92a2au, |
|||
0xfff0f6u, 0xffdeebu, 0xfcc2d7u, 0xfaa2c1u, 0xf783acu, 0xf06595u, |
|||
0xe64980u, 0xd6336cu, 0xc2255cu, 0xa61e4du, 0xf8f0fcu, 0xf3d9fau, |
|||
0xeebefau, 0xe599f7u, 0xda77f2u, 0xcc5de8u, 0xbe4bdbu, 0xae3ec9u, |
|||
0x9c36b5u, 0x862e9cu, 0xf3f0ffu, 0xe5dbffu, 0xd0bfffu, 0xb197fcu, |
|||
0x9775fau, 0x845ef7u, 0x7950f2u, 0x7048e8u, 0x6741d9u, 0x5f3dc4u, |
|||
0xedf2ffu, 0xdbe4ffu, 0xbac8ffu, 0x91a7ffu, 0x748ffcu, 0x5c7cfau, |
|||
0x4c6ef5u, 0x4263ebu, 0x3b5bdbu, 0x364fc7u, 0xe7f5ffu, 0xd0ebffu, |
|||
0xa5d8ffu, 0x74c0fcu, 0x4dabf7u, 0x339af0u, 0x228be6u, 0x1c7ed6u, |
|||
0x1971c2u, 0x1864abu, 0xe3fafcu, 0xc5f6fau, 0x99e9f2u, 0x66d9e8u, |
|||
0x3bc9dbu, 0x22b8cfu, 0x15aabfu, 0x1098adu, 0x0c8599u, 0x0b7285u, |
|||
0xe6fcf5u, 0xc3fae8u, 0x96f2d7u, 0x63e6beu, 0x38d9a9u, 0x20c997u, |
|||
0x12b886u, 0x0ca678u, 0x099268u, 0x087f5bu, 0xebfbeeu, 0xd3f9d8u, |
|||
0xb2f2bbu, 0x8ce99au, 0x69db7cu, 0x51cf66u, 0x40c057u, 0x37b24du, |
|||
0x2f9e44u, 0x2b8a3eu, 0xf4fce3u, 0xe9fac8u, 0xd8f5a2u, 0xc0eb75u, |
|||
0xa9e34bu, 0x94d82du, 0x82c91eu, 0x74b816u, 0x66a80fu, 0x5c940du, |
|||
0xfff9dbu, 0xfff3bfu, 0xffec99u, 0xffe066u, 0xffd43bu, 0xfcc419u, |
|||
0xfab005u, 0xf59f00u, 0xf08c00u, 0xe67700u, 0xfff4e6u, 0xffe8ccu, |
|||
0xffd8a8u, 0xffc078u, 0xffa94du, 0xff922bu, 0xfd7e14u, 0xf76707u, |
|||
0xe8590cu, 0xd9480fu) |
|||
in |
|||
write_pam (exp2_of_7_is_128 () | palette, 128u) |
|||
end |
|||
</syntaxhighlight> |
|||
Here I use Netpbm to make a PNG, but you could use, for instance, ImageMagick instead. (Then I generally run my PNGs through optipng before posting them.) |
|||
<pre>patscc -std=gnu2x -g -O2 munching_squares.dats && ./a.out | pamtopng > image.png</pre> |
|||
{{out}} |
|||
[[File:Munching squares ATS.png|alt=A geometric mosaic in 128 arbitrarily chosen colors.]] |
|||
=={{header|AWK}}== |
|||
{{works with|gawk}} |
|||
This program generates a PPM image, that you can view/convert using The GIMP or ImageMagick |
|||
<syntaxhighlight lang="awk"> |
|||
BEGIN { |
|||
# square size |
|||
s = 256 |
|||
# the PPM image header needs 3 lines: |
|||
# P3 |
|||
# width height |
|||
# max colors number (per channel) |
|||
print("P3\n", s, s, "\n", s - 1) |
|||
# and now we generate pixels as a RGB pair in a relaxed |
|||
# form "R G B\n" |
|||
for (x = 0; x < s; x++) { |
|||
for (y = 0; y < s; y++) { |
|||
p = xor(x, y) |
|||
print(0, p, p) |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|BASIC}}== |
|||
==={{header|Applesoft BASIC}}=== |
|||
<syntaxhighlight lang="gwbasic"> 100 DATA 0,2, 6,10,5, 6, 7,15 |
|||
110 DATA 0,1, 3,10,5, 3,11,15 |
|||
120 DATA 0,8, 9,10,5, 9,13,15 |
|||
130 DATA 0,4,12,10,5,12,14,15 |
|||
140 LET C = 7 |
|||
150 POKE 768,169: REM LDA # |
|||
160 POKE 770,073: REM EOR # |
|||
170 POKE 772,133: REM STA |
|||
180 POKE 773,235: REM $EB |
|||
190 POKE 774,096: REM RTS |
|||
200 GR |
|||
210 FOR H = 0 TO 1 |
|||
220 FOR W = 0 TO 1 |
|||
230 FOR S = 0 TO C |
|||
240 READ C(S) |
|||
250 NEXT S |
|||
260 FOR Y = 0 TO C |
|||
270 POKE 769,Y |
|||
280 LET Y1 = H * S * 2 + Y * 2 |
|||
290 FOR X = 0 TO C |
|||
300 POKE 771,X |
|||
310 CALL 768 |
|||
320 COLOR= C( PEEK (235)) |
|||
330 VLIN Y1,Y1 + 1 AT W * S + X |
|||
340 NEXT X,Y,W,H</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> size% = 256 |
||
VDU 23,22,size%;size%;8,8,16,0 |
VDU 23,22,size%;size%;8,8,16,0 |
||
Line 53: | Line 252: | ||
REPEAT WAIT 1 : UNTIL FALSE |
REPEAT WAIT 1 : UNTIL FALSE |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Commodore BASIC}}=== |
|||
{{works with|Commodore BASIC|4.0}} |
|||
The TED machines (C-16, Plus/4) are the only Commodore 8-bits with a large- or structured- enough color palette to make this interesting. Here's an extremely low-res version (40x25 character-sized "pixels"): |
|||
<syntaxhighlight lang="basic">100 FOR I=0 TO 24 |
|||
110 : Y=INT(I*127/24) |
|||
120 : FOR J=0 TO 39 |
|||
130 : X=INT(J*127/39) |
|||
140 : HL = (X OR Y) AND NOT (X AND Y) |
|||
150 : H = INT(HL / 8) |
|||
160 : L = HL - 8 * H |
|||
170 : POKE 2048+I*40+J,L*16+H |
|||
180 : POKE 3072+I*40+J,160 |
|||
190 : NEXT J |
|||
210 NEXT I |
|||
220 GETKEY K$</syntaxhighlight> |
|||
{{Out}} |
|||
[https://imgur.com/a/pjl2Pd4 Screenshot.] |
|||
==={{header|Craft Basic}}=== |
|||
<syntaxhighlight lang="basic">let s = 255 |
|||
for y = 0 to s |
|||
for x = 0 to s |
|||
let r = x ~ y |
|||
fgcolor r, r * 2, r * 3 |
|||
dot x, y |
|||
wait |
|||
next x |
|||
next y</syntaxhighlight> |
|||
==={{header|FreeBASIC}}=== |
|||
<syntaxhighlight lang="freebasic">' version 03-11-2016 |
|||
' compile with: fbc -s gui |
|||
Dim As ULong x, y, r, w = 256 |
|||
ScreenRes w, w, 32 |
|||
For x = 0 To w -1 |
|||
For y = 0 To w -1 |
|||
r =(x Xor y) And 255 |
|||
PSet(x, y), RGB(r, r , r) ' gray scale |
|||
' PSet(x, y), RGB(r, 255 - r, 0) ' red + green |
|||
' PSet(x, y), RGB(r, 0, 0) ' red |
|||
Next |
|||
Next |
|||
' empty keyboard buffer |
|||
While Inkey <> "" : Wend |
|||
WindowTitle "Close window or hit any key to end program" |
|||
Sleep |
|||
End</syntaxhighlight> |
|||
==={{header|Liberty BASIC}}=== |
|||
<syntaxhighlight lang="lb"> |
|||
nomainwin |
|||
w =512 |
|||
' allow for title bar and window border |
|||
WindowWidth =w +2 |
|||
WindowHeight =w +34 |
|||
open "XOR Pattern" for graphics_nsb_nf as #w |
|||
#w "trapclose quit" |
|||
#w "down" |
|||
for x =0 to w -1 |
|||
for y =0 to w -1 |
|||
b =( x xor y) and 255 |
|||
print b |
|||
#w "color "; 255 -b; " "; b /2; " "; b |
|||
#w "set "; x; " "; w -y -1 |
|||
scan |
|||
next y |
|||
next x |
|||
#w "flush" |
|||
wait |
|||
sub quit j$ |
|||
close #w |
|||
end |
|||
end sub |
|||
</syntaxhighlight> |
|||
Image available at [[http://www.diga.me.uk/xorRC.gif]] |
|||
==={{header|Microsoft Small Basic}}=== |
|||
<syntaxhighlight lang="smallbasic">' Munching squares - smallbasic - 27/07/2018 |
|||
size=256 |
|||
GraphicsWindow.Width=size |
|||
GraphicsWindow.Height=size |
|||
For i=0 To size-1 |
|||
For j=0 To size-1 |
|||
BitXor() 'color=i Xor j |
|||
GraphicsWindow.SetPixel(i,j,GraphicsWindow.GetColorFromRGB(0,color,color)) |
|||
EndFor |
|||
EndFor |
|||
Sub BitXor '(i,j)->color |
|||
n=i |
|||
Int2Bit() |
|||
ib=ret |
|||
n=j |
|||
Int2Bit() |
|||
jb=ret |
|||
color=0 |
|||
For k=1 to 8 |
|||
ki=Text.GetSubText(ib,k,1) |
|||
kj=Text.GetSubText(jb,k,1) |
|||
If ki="1" Or kj="1" Then |
|||
kk="1" |
|||
Else |
|||
kk="0" |
|||
EndIf |
|||
If ki="1" And kj="1" Then |
|||
kk="0" |
|||
EndIf |
|||
color=2*color+kk |
|||
EndFor |
|||
EndSub |
|||
Sub Int2Bit 'n->ret |
|||
x=n |
|||
ret="" |
|||
For k=1 to 8 |
|||
t=Math.Floor(x/2) |
|||
r=Math.Remainder(x,2) |
|||
ret=Text.Append(r,ret) |
|||
x=t |
|||
EndFor |
|||
EndSub </syntaxhighlight> |
|||
{{out}} |
|||
[https://github.com/Pat-Garrett/RC/blob/master/Munching%20squares%20-%20vbnet.jpg Munching squares - SmallBasic] |
|||
==={{header|PureBasic}}=== |
|||
<syntaxhighlight lang="purebasic">#palletteSize = 128 |
|||
Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values |
|||
Protected result = x ! y |
|||
ProcedureReturn Mod(result, #palletteSize) / #palletteSize |
|||
EndProcedure |
|||
Procedure drawPattern() |
|||
StartDrawing(ImageOutput(0)) |
|||
DrawingMode(#PB_2DDrawing_Gradient) |
|||
CustomGradient(@XorPattern()) |
|||
;specify a gradient pallette from which only specific indexes will be used |
|||
For i = 1 To #palletteSize |
|||
GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD |
|||
Next |
|||
Box(0, 0, ImageWidth(0), ImageHeight(0)) |
|||
StopDrawing() |
|||
EndProcedure |
|||
If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu) |
|||
CreateImage(0, WindowWidth(0), WindowHeight(0)) |
|||
drawPattern() |
|||
ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0)) |
|||
Repeat |
|||
event = WaitWindowEvent(20) |
|||
Until event = #PB_Event_CloseWindow |
|||
EndIf</syntaxhighlight> |
|||
[[File:PureBasic_XOR_Pattern.png|Sample display of PureBasic solution|200px]] |
|||
==={{header|QBasic}}=== |
|||
<syntaxhighlight lang="qbasic">w = 254 |
|||
SCREEN 13 |
|||
VIEW (0, 0)-(w / 2, w / 2), , 0 |
|||
FOR x = 0 TO w |
|||
FOR y = 0 TO w |
|||
COLOR ((x XOR y) AND 255) |
|||
PSET (x, y) |
|||
NEXT y |
|||
NEXT x</syntaxhighlight> |
|||
==={{header|RapidQ}}=== |
|||
{{trans|FreeBASIC}} |
|||
<syntaxhighlight lang="rapidq"> |
|||
'Munching squares |
|||
DECLARE SUB PaintCanvas |
|||
CREATE Form AS QForm |
|||
ClientWidth = 256 |
|||
ClientHeight = 256 |
|||
CREATE Canvas AS QCanvas |
|||
Height = Form.ClientHeight |
|||
Width = Form.ClientWidth |
|||
OnPaint = PaintCanvas |
|||
END CREATE |
|||
END CREATE |
|||
SUB PaintCanvas |
|||
FOR X = 0 TO Canvas.Width - 1 |
|||
FOR Y = 0 TO Canvas.Width - 1 |
|||
R = (X XOR Y) AND 255 |
|||
Canvas.Pset(X, Y, RGB(R, R, R)) ' gray scale |
|||
'Canvas.Pset(X, Y, RGB(R, 255 - R, 0)) ' red + green |
|||
'Canvas.Pset(X, Y, RGB(R, 0, 0)) ' red |
|||
NEXT Y |
|||
NEXT X |
|||
END SUB |
|||
Form.ShowModal |
|||
</syntaxhighlight> |
|||
==={{header|Run BASIC}}=== |
|||
<syntaxhighlight lang="runbasic">w = 100 |
|||
graphic #g, w,w |
|||
for x = 0 to w |
|||
for y = 0 to w |
|||
b = (x xor y) and 255 |
|||
#g color(255 -b,b /2,b) |
|||
#g "set "; x; " "; w -y -1 |
|||
next y |
|||
next x |
|||
render #g |
|||
#g "flush"</syntaxhighlight> |
|||
==={{header|TI-83 BASIC}}=== |
|||
Due to the TI-83's 1 bit black and white display, this program uses the home screen and a gradient of characters. Since the TI-83 does not use a standard encoding, the first Sto→ to Str1 may be subjectively interpreted. |
|||
<syntaxhighlight lang="ti-83b">PROGRAM:XORPATT |
|||
" •.-,+-°-1+o*:πOX"→Str1 |
|||
ClrHome |
|||
{0,0,0,0}→L1 |
|||
{0,0,0,0)→L2 |
|||
For(I,1,8,1) |
|||
For(J,1,16,1) |
|||
J→A |
|||
I→B |
|||
If A>8 |
|||
Then |
|||
A-8→A |
|||
1→L1(1) |
|||
Else |
|||
0→L1(1) |
|||
End |
|||
If A>4 |
|||
Then |
|||
A-4→A |
|||
1→L1(2) |
|||
Else |
|||
0→L1(2) |
|||
End |
|||
If A>2 |
|||
Then |
|||
A-2→A |
|||
1→L1(3) |
|||
Else |
|||
0→L1(3) |
|||
End |
|||
If A>1 |
|||
Then |
|||
1→L1(4) |
|||
Else |
|||
0→L1(4) |
|||
End |
|||
0→L2(1) |
|||
If B>4 |
|||
Then |
|||
B-4→B |
|||
1→L2(2) |
|||
Else |
|||
0→L2(2) |
|||
End |
|||
If B>2 |
|||
Then |
|||
B-2→B |
|||
1→L2(3) |
|||
Else |
|||
0→L2(3) |
|||
End |
|||
If B>1 |
|||
Then |
|||
1→L2(4) |
|||
Else |
|||
0→L2(4) |
|||
End |
|||
L1≠L2→L3 |
|||
8L3(1)+4L3(2)+2L3(3)+L3(4)→C |
|||
Output(I,J,sub(Str1,C+1,1)) |
|||
End |
|||
End |
|||
Pause |
|||
</syntaxhighlight> |
|||
==={{header|Visual Basic .NET}}=== |
|||
{{works with|Visual Basic .NET|2011}} |
|||
<syntaxhighlight lang="vbnet">' Munching squares - 27/07/2018 |
|||
Public Class MunchingSquares |
|||
Const xsize = 256 |
|||
Dim BMP As New Drawing.Bitmap(xsize, xsize) |
|||
Dim GFX As Graphics = Graphics.FromImage(BMP) |
|||
Private Sub MunchingSquares_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint |
|||
'draw |
|||
Dim MyGraph As Graphics = Me.CreateGraphics |
|||
Dim nColor As Color |
|||
Dim i, j, cp As Integer |
|||
xPictureBox.Image = BMP |
|||
For i = 0 To xsize - 1 |
|||
For j = 0 To xsize - 1 |
|||
cp = i Xor j |
|||
nColor = Color.FromArgb(cp, 0, cp) |
|||
BMP.SetPixel(i, j, nColor) |
|||
Next j |
|||
Next i |
|||
End Sub 'Paint |
|||
End Class </syntaxhighlight> |
|||
{{out}} |
|||
[https://github.com/Pat-Garrett/RC/blob/7e9842513d361a5b4241bc6bb28f9985c2bfe161/Munching%20squares%20-%20vbnet.jpg Munching squares - vbnet] |
|||
==={{header|Yabasic}}=== |
|||
{{trans|FreeBASIC}} |
|||
<syntaxhighlight lang="yabasic">w = 256 |
|||
open window w, w |
|||
For x = 0 To w-1 |
|||
For y = 0 To w-1 |
|||
r =and(xor(x, y), 255) |
|||
color r, and(r*2, 255), and(r*3, 255) |
|||
dot x, y |
|||
Next |
|||
Next</syntaxhighlight> |
|||
=={{header|Befunge}}== |
|||
Writes the image to stdout using the PPM format. |
|||
<syntaxhighlight lang="befunge">55+::"3P",,,28*:*::..\,:.\,:v |
|||
>2%*28*:**-2/\1-:v<:8:-1<_@ v |
|||
^\-1*2%2/*:*82::\_$0.0..:^:*<</syntaxhighlight> |
|||
=={{header|BQN}}== |
|||
Outputs a string that represents a PPM image. |
|||
BQN uses the <code>•bit</code> namespace for native bitwise operations, including casting. An input bit width and output bit width have to be given. |
|||
<syntaxhighlight lang="bqn">nl←@+10 |
|||
XORppm ← { |
|||
g←⥊(0∾∾˜)¨((↕𝕩)16‿16•bit._xor⊢)˘↕𝕩 |
|||
s←•Repr 𝕩 |
|||
h←"P3"∾nl∾s∾" "∾s∾nl∾(•Repr 𝕩-1)∾nl |
|||
h∾∾∾⟜nl¨{¯1↓∾∾⟜' '¨•Repr¨𝕩}¨g |
|||
}</syntaxhighlight> |
|||
Example usage: |
|||
<syntaxhighlight lang="bqn">"xor.ppm" •FChars XORppm 256</syntaxhighlight> |
|||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp |
blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp |
||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
||
Line 85: | Line 653: | ||
24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23 8 9 10 11 12 13 14 15 0 1 |
24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23 8 9 10 11 12 13 14 15 0 1 |
||
25 24 27 26 29 28 31 30 17 16 19 18 21 20 23 22 9 8 11 10 13 12 15 14 1 0 |
25 24 27 26 29 28 31 30 17 16 19 18 21 20 23 22 9 8 11 10 13 12 15 14 1 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Must be converted to an image with a seperate program. |
Must be converted to an image with a seperate program. |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdlib.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
#include <math.h> |
#include <math.h> |
||
Line 133: | Line 701: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} [[Image:Xor_pattern_c.png|C output|200px]] |
{{out}} [[Image:Xor_pattern_c.png|C output|200px]] |
||
=={{header|C sharp}}== |
|||
<syntaxhighlight lang="csharp">using System.Drawing; |
|||
using System.Drawing.Imaging; |
|||
using System.Linq; |
|||
class XORPattern |
|||
{ |
|||
static void Main() |
|||
{ |
|||
var size = 0x100; |
|||
var black = Color.Black.ToArgb(); |
|||
var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray(); |
|||
using (var image = new Bitmap(size, size)) |
|||
{ |
|||
for (var x = 0; x < size; x++) |
|||
{ |
|||
for (var y = 0; y < size; y++) |
|||
{ |
|||
image.SetPixel(x, y, palette[x ^ y]); |
|||
} |
|||
} |
|||
image.Save("XORPatternCSharp.png", ImageFormat.Png); |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
[[File:XORPatternCSharp.png|XORPatternCSharp.png]] |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
[[File:msquares_cpp2.png|300px]] |
[[File:msquares_cpp2.png|300px]] |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <windows.h> |
#include <windows.h> |
||
#include <string> |
#include <string> |
||
Line 300: | Line 896: | ||
} |
} |
||
//-------------------------------------------------------------------------------------------------- |
//-------------------------------------------------------------------------------------------------- |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|Clojure}}== |
||
The fun part of munching squares isn't color tables, it's watching them munch: |
|||
<lang csharp>using System.Drawing; |
|||
using System.Drawing.Imaging; |
|||
using System.Linq; |
|||
<syntaxhighlight lang="clojure">(let [n 16] |
|||
class XORPattern |
|||
(loop [i 0] |
|||
{ |
|||
(print "\033[0;0f\033[2J") |
|||
static void Main() |
|||
(doseq [y (range n)] |
|||
{ |
|||
(doseq [x (range n)] |
|||
(print (if (< (bit-xor x y) i) "█" " "))) |
|||
var black = Color.Black.ToArgb(); |
|||
(print "\n")) |
|||
var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray(); |
|||
(flush) |
|||
using (var image = new Bitmap(size, size)) |
|||
(Thread/sleep 150) |
|||
(recur (mod (inc i) (inc n))))) |
|||
for (var x = 0; x < size; x++) |
|||
</syntaxhighlight> |
|||
{ |
|||
for (var y = 0; y < size; y++) |
|||
=={{header|Evaldraw}}== |
|||
{ |
|||
image.SetPixel(x, y, palette[x ^ y]); |
|||
Since all variables in Evaldraw are doubles, convert to binary and do a custom per bit xor operation. |
|||
} |
|||
} |
|||
[[File:Evaldraw xor squares.gif|thumb|alt=xor pattern where color is the result of xor(x,y) over values x from 0 to 128 and y to 128|Coloring the xor munching squares pattern over time]] |
|||
image.Save("XORPatternCSharp.png", ImageFormat.Png); |
|||
} |
|||
<syntaxhighlight lang="c">enum{NUMBITS=7, MAXNUMS=3} |
|||
static binary[MAXNUMS][NUMBITS]; |
|||
() { |
|||
cls(0); |
|||
t = 100*klock(); |
|||
for(y = 0; y < 128; y++) { |
|||
decToBin(y,1); |
|||
for(x = 0; x < 128; x++) { |
|||
decToBin(x,0); |
|||
xor(0,1,2); |
|||
c = binToDec(2); |
|||
setcol(hsv_to_rgb( (t+c*1)%360,.8,1) ); |
|||
setpix(x,y); |
|||
} |
|||
} |
} |
||
} |
|||
}</lang> |
|||
{{out}} |
|||
binToDec(id) { |
|||
[[File:XORPatternCSharp.png|XORPatternCSharp.png]] |
|||
num = 0; |
|||
for(i=0; i<NUMBITS; i++) { |
|||
if( binary[id][i] == 1) { |
|||
num += 2^(NUMBITS-i-1); |
|||
} |
|||
} |
|||
return num; |
|||
} |
|||
decToBin(num,id) { |
|||
for(i=0; i<NUMBITS; i++) binary[id][i] = 0; |
|||
bitpos = NUMBITS-1; |
|||
while( num > 0 && bitpos >= 0) { |
|||
binary[id][bitpos] = num % 2 == 1; |
|||
bitpos--; // ready for next bit |
|||
num = int(num/2); |
|||
} |
|||
} |
|||
xor(num1,num2,store) { |
|||
for(i=0; i<NUMBITS; i++) |
|||
if(binary[num1][i] == binary[num2][i]) binary[store][i] = 0; else binary[store][i] = 1; |
|||
}</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio; |
import std.stdio; |
||
Line 344: | Line 975: | ||
f.rawWrite(u3); |
f.rawWrite(u3); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
|||
{{works with|Delphi|6.0}} |
|||
{{libheader|Windows,Types,ExtCtrls,Graphics}} |
|||
<syntaxhighlight lang="Delphi"> |
|||
procedure MunchingSquares(Image: TImage); |
|||
{XOR's X and Y to select an RGB level} |
|||
var W,H,X,Y: integer; |
|||
begin |
|||
W:=Image.Width; |
|||
H:=Image.Height; |
|||
for Y:=0 to Image.Height-1 do |
|||
for X:=0 to Image.Width-1 do |
|||
begin |
|||
Image.Canvas.Pixels[X,Y]:=RGB(0,X xor Y,0); |
|||
end; |
|||
end; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
[[File:DelphiMunchingSquares.png|thumb|none]] |
|||
<pre> |
|||
</pre> |
|||
=={{header|EasyLang}}== |
|||
[https://easylang.dev/show/#cod=VYxLCoAwDET3PcWsFWqL4s7DaK0f0BZSEb29iRTBZDHJG2aSQwdrDCq0jZoi4QL1YfZGfgCC7j/iWTg1rEcfRpHrjd1o62xL6SKVH4hbpJo5b0Z7PD2nCiTHUZFskHeHwBJG2+8QUyutHg== Run it] |
|||
<syntaxhighlight lang="easylang"> |
|||
sc = 100 / 64 |
|||
for x range0 64 |
|||
for y range0 64 |
|||
h = bitand bitxor x y 63 |
|||
c = h / 63 |
|||
color3 c c c |
|||
move x * sc y * sc |
|||
rect sc + 0.1 sc + 0.1 |
|||
. |
|||
. |
|||
</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
Use the '''plot''' library, hsv->rgb ((x xor y) modulo m) as color table, and see the nice results here : http://www.echolalie.org/echolisp/help.html#bit-map . |
Use the '''plot''' library, hsv->rgb ((x xor y) modulo m) as color table, and see the nice results here : http://www.echolalie.org/echolisp/help.html#bit-map . |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'types) |
(lib 'types) |
||
(lib 'plot) |
(lib 'plot) |
||
Line 365: | Line 1,039: | ||
(plot-much) ;; ESC to see tge drawing |
(plot-much) ;; ESC to see tge drawing |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
|||
<lang freebasic>' version 03-11-2016 |
|||
' compile with: fbc -s gui |
|||
=={{header|Factor}}== |
|||
Dim As ULong x, y, r, w = 256 |
|||
<syntaxhighlight lang="factor">USING: accessors images images.loader kernel math sequences ; |
|||
IN: rosetta-code.munching-squares |
|||
: img-data ( -- seq ) 256 sq [ B{ 0 0 0 255 } ] replicate ; |
|||
ScreenRes w, w, 32 |
|||
: (munching) ( elt index -- elt' ) |
|||
For x = 0 To w -1 |
|||
256 /mod bitxor [ rest ] dip prefix ; |
|||
r =(x Xor y) And 255 |
|||
PSet(x, y), RGB(r, r , r) ' gray scale |
|||
' PSet(x, y), RGB(r, 255 - r, 0) ' red + green |
|||
' PSet(x, y), RGB(r, 0, 0) ' red |
|||
Next |
|||
Next |
|||
: munching ( -- seq ) |
|||
' empty keyboard buffer |
|||
img-data [ (munching) ] map-index B{ } concat-as ; |
|||
While Inkey <> "" : Wend |
|||
WindowTitle "Close window or hit any key to end program" |
|||
: <munching-img> ( -- img ) |
|||
Sleep |
|||
<image> |
|||
End</lang> |
|||
{ 256 256 } >>dim |
|||
BGRA >>component-order |
|||
ubyte-components >>component-type |
|||
munching >>bitmap ; |
|||
: main ( -- ) <munching-img> "munching.png" save-graphic-image ; |
|||
MAIN: main</syntaxhighlight> |
|||
Output image is identical to the Racket version. |
|||
{{out}} |
|||
[[File:munching-racket.png]] |
|||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Munching_squares}} |
|||
'''Solution''' |
|||
[[File:Fōrmulæ - Munching squares 01.png]] |
|||
'''Test case''' |
|||
[[File:Fōrmulæ - Munching squares 02.png]] |
|||
[[File:Fōrmulæ - Munching squares 03.png]] |
|||
=={{header|GLSL}}== |
=={{header|GLSL}}== |
||
This is an example that will work directly on shadertoy.com, Example [https://www.shadertoy.com/view/Mss3Rs] |
This is an example that will work directly on shadertoy.com, Example [https://www.shadertoy.com/view/Mss3Rs] |
||
< |
<syntaxhighlight lang="glsl">vec3 color; |
||
float c,p; |
float c,p; |
||
vec2 b; |
vec2 b; |
||
Line 433: | Line 1,125: | ||
gl_FragColor = vec4(color,1.0); |
gl_FragColor = vec4(color,1.0); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Gnuplot}}== |
=={{header|Gnuplot}}== |
||
< |
<syntaxhighlight lang="gnuplot">set pm3d map |
||
set size square |
set size square |
||
set isosamples 255,255 |
set isosamples 255,255 |
||
splot [0:255][0:255]-(floor(x)^floor(y))</ |
splot [0:255][0:255]-(floor(x)^floor(y))</syntaxhighlight> |
||
{{out}} [[Image:gnuplot_xor.png|Gnuplot output|200px]] |
{{out}} [[Image:gnuplot_xor.png|Gnuplot output|200px]] |
||
=={{header|Haskell}}== |
|||
<lang haskell>import Data.ByteString |
|||
import Data.Bits |
|||
main = Data.ByteString.writeFile "out.pgm" (pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [x `xor` y | x <- [0..255], y <- [0..255]])) |
|||
</lang> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 467: | Line 1,152: | ||
png.Encode(f, g) |
png.Encode(f, g) |
||
f.Close() |
f.Close() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
|||
<syntaxhighlight lang="haskell">import qualified Data.ByteString as BY (writeFile, pack) |
|||
import Data.Bits (xor) |
|||
main :: IO () |
|||
main = |
|||
BY.writeFile |
|||
"out.pgm" |
|||
(BY.pack |
|||
(fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ |
|||
[ x `xor` y |
|||
| x <- [0 .. 255] |
|||
, y <- [0 .. 255] ]))</syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
[[File:XORimage-unicon-GR512.png|thumb|right|512x512 bit green and red]] |
[[File:XORimage-unicon-GR512.png|thumb|right|512x512 bit green and red]] |
||
< |
<syntaxhighlight lang="icon">link printf |
||
procedure main(A) #: XOR graphic |
procedure main(A) #: XOR graphic |
||
Line 488: | Line 1,188: | ||
until Event() == &lpress # wait for left button to quit |
until Event() == &lpress # wait for left button to quit |
||
close(&window) |
close(&window) |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Icon Programming Library}} |
{{libheader|Icon Programming Library}} |
||
Line 494: | Line 1,194: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> require 'viewmat' |
||
viewmat ~:"1/&.#: ~ i.256</ |
viewmat ~:"1/&.#: ~ i.256</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{libheader|Swing}} |
{{libheader|Swing}} |
||
This example will repeat the pattern if you expand the window. |
This example will repeat the pattern if you expand the window. |
||
< |
<syntaxhighlight lang="java">import java.awt.Color; |
||
import java.awt.Graphics; |
import java.awt.Graphics; |
||
Line 530: | Line 1,230: | ||
new XorPattern(); |
new XorPattern(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
[[Image:Xor pattern Java.png|200px]] |
[[Image:Xor pattern Java.png|200px]] |
||
Line 536: | Line 1,236: | ||
{{works with|jq|1.4}} |
{{works with|jq|1.4}} |
||
The following is an adaptation of the Ruby entry, but generates an SVG image file: |
The following is an adaptation of the Ruby entry, but generates an SVG image file: |
||
< |
<syntaxhighlight lang="sh">jq -n -r -f Munching_squares.jq > Munching_squares.svg</syntaxhighlight> |
||
'''Part 1: Infrastructure''' |
'''Part 1: Infrastructure''' |
||
< |
<syntaxhighlight lang="jq"># Convert the input integer to an array of bits with lsb first |
||
def integer_to_lsb: |
def integer_to_lsb: |
||
[recurse(if . > 0 then ./2|floor else empty end) | . % 2] ; |
[recurse(if . > 0 then ./2|floor else empty end) | . % 2] ; |
||
Line 560: | Line 1,260: | ||
| reduce range(0;$length) as $i |
| reduce range(0;$length) as $i |
||
([]; . + [ lxor($s[$i]; $t[$i]) ] ) |
([]; . + [ lxor($s[$i]; $t[$i]) ] ) |
||
| lsb_to_integer;</ |
| lsb_to_integer;</syntaxhighlight> |
||
'''Part 2: SVG''' |
'''Part 2: SVG''' |
||
< |
<syntaxhighlight lang="jq">def rgb2rgb: |
||
def p: (. + 0.5) | floor; # to nearest integer |
def p: (. + 0.5) | floor; # to nearest integer |
||
"rgb(\(.red|p),\(.green|p),\(.blue|p))"; |
"rgb(\(.red|p),\(.green|p),\(.blue|p))"; |
||
Line 572: | Line 1,272: | ||
def pixel(x; y; color): |
def pixel(x; y; color): |
||
(color | if type == "string" then . else rgb2rgb end) as $c |
(color | if type == "string" then . else rgb2rgb end) as $c |
||
| "<circle r='1' cx='\(x)' cy='\(y)' fill='\($c)' />";</ |
| "<circle r='1' cx='\(x)' cy='\(y)' fill='\($c)' />";</syntaxhighlight> |
||
'''Part 3: xor pattern''' |
'''Part 3: xor pattern''' |
||
< |
<syntaxhighlight lang="jq"># rgb is a JSON object: { "red": _, "green": _, "blue": _} |
||
def xor_pattern(width; height; rgb1; rgb2): |
def xor_pattern(width; height; rgb1; rgb2): |
||
Line 590: | Line 1,290: | ||
| range(0;height) as $y |
| range(0;height) as $y |
||
| pixel($x; $y; $colours[ xor($x; $y) % $size] ) ) ), |
| pixel($x; $y; $colours[ xor($x; $y) % $size] ) ) ), |
||
"</svg>" ;</ |
"</svg>" ;</syntaxhighlight> |
||
'''Part 4: Example''' |
'''Part 4: Example''' |
||
< |
<syntaxhighlight lang="jq">def black: { "red": 0, "green": 0, "blue": 0}; |
||
def red: black + { "red": 255 }; |
def red: black + { "red": 255 }; |
||
def yellow: red + { "green": 255 }; |
def yellow: red + { "green": 255 }; |
||
xor_pattern(384; 384; red; yellow)</ |
xor_pattern(384; 384; red; yellow)</syntaxhighlight> |
||
=={{header| |
=={{header|Julia}}== |
||
<syntaxhighlight lang="julia">using Gtk, Cairo |
|||
<lang lb> |
|||
nomainwin |
|||
const can = @GtkCanvas() |
|||
w =512 |
|||
const win = GtkWindow(can, "Munching Squares", 512, 512) |
|||
' allow for title bar and window border |
|||
WindowWidth =w +2 |
|||
WindowHeight =w +34 |
|||
@guarded draw(can) do widget |
|||
open "XOR Pattern" for graphics_nsb_nf as #w |
|||
ctx = getgc(can) |
|||
for x in 0:255, y in 0:255 |
|||
set_source_rgb(ctx, abs(255 - x - y) / 255, ((255 - x) ⊻ y) / 255, (x ⊻ (255 - y)) / 255) |
|||
circle(ctx, 2x, 2y, 2) |
|||
fill(ctx) |
|||
end |
|||
end |
|||
show(can) |
|||
#w "trapclose quit" |
|||
const cond = Condition() |
|||
endit(w) = notify(cond) |
|||
signal_connect(endit, win, :destroy) |
|||
wait(cond) |
|||
</syntaxhighlight> |
|||
=={{header|Kotlin}}== |
|||
#w "down" |
|||
<syntaxhighlight lang="scala">// version 1.1.4-3 |
|||
import javax.swing.JFrame |
|||
for x =0 to w -1 |
|||
import javax.swing.JPanel |
|||
for y =0 to w -1 |
|||
import java.awt.Graphics |
|||
b =( x xor y) and 255 |
|||
import java.awt.Graphics2D |
|||
print b |
|||
import java.awt.Color |
|||
#w "color "; 255 -b; " "; b /2; " "; b |
|||
import java.awt.Dimension |
|||
#w "set "; x; " "; w -y -1 |
|||
import java.awt.BorderLayout |
|||
scan |
|||
import java.awt.RenderingHints |
|||
next y |
|||
import javax.swing.SwingUtilities |
|||
next x |
|||
class XorPattern : JPanel() { |
|||
#w "flush" |
|||
init { |
|||
preferredSize = Dimension(256, 256) |
|||
background = Color.white |
|||
} |
|||
override fun paint(gg: Graphics) { |
|||
sub quit j$ |
|||
super.paintComponent(gg) |
|||
close #w |
|||
val g = gg as Graphics2D |
|||
end |
|||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, |
|||
end sub |
|||
RenderingHints.VALUE_ANTIALIAS_ON) |
|||
</lang> |
|||
for (y in 0 until width) { |
|||
Image available at [[http://www.diga.me.uk/xorRC.gif]] |
|||
for (x in 0 until height) { |
|||
g.color = Color(0, (x xor y) % 256, 255) |
|||
g.drawLine(x, y, x, y) |
|||
} |
|||
} |
|||
} |
|||
} |
|||
fun main(args: Array<String>) { |
|||
SwingUtilities.invokeLater { |
|||
val f = JFrame() |
|||
with (f) { |
|||
defaultCloseOperation = JFrame.EXIT_ON_CLOSE |
|||
title = "Munching squares" |
|||
isResizable = false |
|||
add(XorPattern(), BorderLayout.CENTER) |
|||
pack() |
|||
setLocationRelativeTo(null) |
|||
isVisible = true |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|Lua}}== |
|||
{{works with|LÖVE|11.0 or higher}} |
|||
<syntaxhighlight lang="lua">local clr = {} |
|||
function drawMSquares() |
|||
local points = {} |
|||
for y = 0, hei-1 do |
|||
for x = 0, wid-1 do |
|||
local idx = bit.bxor(x, y)%256 |
|||
local r, g, b = clr[idx][1], clr[idx][2], clr[idx][3] |
|||
local point = {x+1, y+1, r/255, g/255, b/255, 1} |
|||
table.insert (points, point) |
|||
end |
|||
end |
|||
love.graphics.points(points) |
|||
end |
|||
function createPalette() |
|||
for i = 0, 255 do |
|||
clr[i] = {i*2.8%256, i*3.2%256, i*1.5%256} |
|||
end |
|||
end |
|||
function love.load() |
|||
wid, hei = 256, 256 |
|||
love.window.setMode(wid, hei) |
|||
canvas = love.graphics.newCanvas() |
|||
love.graphics.setCanvas(canvas) |
|||
createPalette() |
|||
drawMSquares() |
|||
love.graphics.setCanvas() |
|||
end |
|||
function love.draw() |
|||
love.graphics.setColor(1,1,1) |
|||
love.graphics.draw(canvas) |
|||
end</syntaxhighlight> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">ListDensityPlot[ |
||
Table[Table[ |
Table[Table[ |
||
FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]], |
FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]], |
||
2], {x, 0, 255}], {y, 0, 255}]]</ |
2], {x, 0, 255}], {y, 0, 255}]]</syntaxhighlight> |
||
{{out|Output #1}} |
{{out|Output #1}} |
||
[[File:xorpattern3.png|Mathematica output #1|200px]] |
[[File:xorpattern3.png|Mathematica output #1|200px]] |
||
< |
<syntaxhighlight lang="mathematica">ArrayPlot[Array[BitXor, {511, 511}]]</syntaxhighlight> |
||
{{out|Output #2}} |
{{out|Output #2}} |
||
[[File:xorpattern4.png|Mathematica output #2|200px]] |
[[File:xorpattern4.png|Mathematica output #2|200px]] |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">size = 256; |
||
[x,y] = meshgrid([0:size-1]); |
[x,y] = meshgrid([0:size-1]); |
||
Line 654: | Line 1,426: | ||
colormap bone(size); |
colormap bone(size); |
||
image(c); |
image(c); |
||
axis equal;</ |
axis equal;</syntaxhighlight> |
||
{{out}} [[File:matlab_xor.png|MATLAB output|200px]] |
{{out}} [[File:matlab_xor.png|MATLAB output|200px]] |
||
=={{header|MiniScript}}== |
|||
This version runs in Mini Micro (for the graphics, and the bitXor intrinsic). |
|||
<syntaxhighlight lang="miniscript">for x in range(0,255) |
|||
for y in range(0,255) |
|||
gfx.setPixel x, y, color.rgb(0, bitXor(x,y), 0) |
|||
end for |
|||
end for</syntaxhighlight> |
|||
{{out}} |
|||
[[File:xor_pattern_miniscript.png|MiniScript output|254px]] |
|||
=={{header|Nim}}== |
|||
{{libheader|imageman}} |
|||
<syntaxhighlight lang="nim">import random |
|||
import imageman |
|||
randomize() |
|||
# Build a color table. |
|||
var colors: array[256, ColorRGBU] |
|||
for color in colors.mitems: |
|||
color = ColorRGBU [byte rand(255), byte rand(255), byte rand(255)] |
|||
var image = initImage[ColorRGBU](256, 256) |
|||
for i in 0..255: |
|||
for j in 0..255: |
|||
image[i, j] = colors[i xor j] |
|||
image.savePNG("munching_squares.png")</syntaxhighlight> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">open Graphics |
||
let () = |
let () = |
||
Line 671: | Line 1,476: | ||
done; |
done; |
||
done; |
done; |
||
ignore(read_key())</ |
ignore(read_key())</syntaxhighlight> |
||
Run with: |
Run with: |
||
Line 680: | Line 1,485: | ||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">size = 256; |
||
[x,y] = meshgrid([0:size-1]); |
[x,y] = meshgrid([0:size-1]); |
||
Line 687: | Line 1,492: | ||
colormap(jet(size)); |
colormap(jet(size)); |
||
image(c); |
image(c); |
||
axis equal;</ |
axis equal;</syntaxhighlight> |
||
{{out}} [[File:Xor_pattern_octave.png|Octave output|320px]] |
{{out}} [[File:Xor_pattern_octave.png|Octave output|320px]] |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use GD; |
||
my $img = |
my $img = GD::Image->new(256, 256, 1); |
||
for my $y(0..255) { |
for my $y (0..255) { |
||
for my $x(0..255) { |
for my $x (0..255) { |
||
my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y)); |
my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y)); |
||
$img->setPixel($x, $y, $color); |
$img->setPixel($x, $y, $color); |
||
Line 702: | Line 1,507: | ||
} |
} |
||
print $img->png</ |
print $img->png</syntaxhighlight> |
||
{{out}} [[File:perl_xor_pattern.png|Perl output|200px]] |
{{out}} [[File:perl_xor_pattern.png|Perl output|200px]] |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/pGUI}} |
|||
Here's one simple way: |
|||
{{libheader|Phix/online}} |
|||
You can run this online [http://phix.x10.mx/p2js/Munching_squares.htm here]. |
|||
<lang perl6>my $ppm = open("munching.ppm", :w, :bin) or |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
die "Can't create munching.ppm: $!"; |
|||
<span style="color: #000080;font-style:italic;">-- |
|||
-- demo\rosetta\Munching_squares.exw |
|||
$ppm.print(q :to 'EOT'); |
|||
-- ================================= |
|||
P3 |
|||
--</span> |
|||
256 256 |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
255 |
|||
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> |
|||
EOT |
|||
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span> |
|||
for 0 .. 255 -> $row { |
|||
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span> |
|||
for 0 .. 255 -> $col { |
|||
my $color = $row +^ $col; |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span> |
|||
$ppm.print("0 $color 0 "); |
|||
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span> |
|||
} |
|||
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span> |
|||
$ppm.say(); |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span> |
|||
} |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #7060A8;">cdCanvasPixel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">))</span> |
|||
$ppm.close(); |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
</lang> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span> |
|||
Another way: |
|||
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<lang perl6>my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b }, |
|||
map -> $x { floor ($x/256) ** 3 * 256 }, |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span> |
|||
(flat (0...255) Z |
|||
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span> |
|||
(255...0) Z |
|||
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span> |
|||
flat (0,2...254),(254,252...0)); |
|||
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_WHITE</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_RED</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> |
|||
my $PPM = open "munching.ppm", :w, :bin or die "Can't create munching.ppm: $!"; |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
$PPM.print: qq:to/EOH/; |
|||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span> |
|||
P6 |
|||
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span> |
|||
# munching.pgm |
|||
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RASTERSIZE=250x250"</span><span style="color: #0000FF;">)</span> |
|||
256 256 |
|||
<span style="color: #7060A8;">IupSetCallbacks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">),</span> |
|||
255 |
|||
<span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">)})</span> |
|||
EOH |
|||
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`TITLE="Munching squares",RESIZE=NO`</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span> |
|||
$PPM.write: @colors[$_] for ^256 X+^ ^256; |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> |
|||
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span> |
|||
$PPM.close;</lang> |
|||
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span> |
|||
[[File:perl_6_xor_pattern.png|Perl 6 output|200px]] |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
|||
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">header("Content-Type: image/png"); |
||
$w = 256; |
$w = 256; |
||
Line 775: | Line 1,585: | ||
imagepng($im); |
imagepng($im); |
||
imagedestroy($im);</ |
imagedestroy($im);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[[File:xor_pattern_php.png|PHP output|200px]] |
[[File:xor_pattern_php.png|PHP output|200px]] |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i">munch: procedure options (main); /* 21 May 2014 */ |
||
declare screen (0:255, 0:255) bit(24) aligned; |
declare screen (0:255, 0:255) bit(24) aligned; |
||
Line 793: | Line 1,603: | ||
end; |
end; |
||
call writeppm(screen); |
call writeppm(screen); |
||
end munch;</ |
end munch;</syntaxhighlight> |
||
=={{header|Processing}}== |
|||
Renders grayscale image, the larger the window the more the squares will repeat along the main diagonal from top left to bottom right. |
|||
<syntaxhighlight lang="java"> |
|||
//Aamrun, 26th June 2022 |
|||
size(1200,720); |
|||
loadPixels(); |
|||
for(int i=0;i<height;i++){ |
|||
for(int j=0;j<width;j++){ |
|||
pixels[j + i*width] = color(i^j); |
|||
} |
|||
} |
|||
updatePixels(); |
|||
</syntaxhighlight> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Works with SWI-Prolog and his GUI XPCE. |
Works with SWI-Prolog and his GUI XPCE. |
||
< |
<syntaxhighlight lang="prolog">xor_pattern :- |
||
new(D, window('XOR Pattern')), |
new(D, window('XOR Pattern')), |
||
send(D, size, size(512,512)), |
send(D, size, size(512,512)), |
||
Line 815: | Line 1,644: | ||
send(D, display, Bmp, point(0,0)), |
send(D, display, Bmp, point(0,0)), |
||
send(D, open). |
send(D, open). |
||
</syntaxhighlight> |
|||
</lang> |
|||
[[File:Prolog_xor_pattern.png|200px]] |
[[File:Prolog_xor_pattern.png|200px]] |
||
=={{header|PureBasic}}== |
|||
<lang purebasic>#palletteSize = 128 |
|||
Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values |
|||
Protected result = x ! y |
|||
ProcedureReturn Mod(result, #palletteSize) / #palletteSize |
|||
EndProcedure |
|||
Procedure drawPattern() |
|||
StartDrawing(ImageOutput(0)) |
|||
DrawingMode(#PB_2DDrawing_Gradient) |
|||
CustomGradient(@XorPattern()) |
|||
;specify a gradient pallette from which only specific indexes will be used |
|||
For i = 1 To #palletteSize |
|||
GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD |
|||
Next |
|||
Box(0, 0, ImageWidth(0), ImageHeight(0)) |
|||
StopDrawing() |
|||
EndProcedure |
|||
If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu) |
|||
CreateImage(0, WindowWidth(0), WindowHeight(0)) |
|||
drawPattern() |
|||
ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0)) |
|||
Repeat |
|||
event = WaitWindowEvent(20) |
|||
Until event = #PB_Event_CloseWindow |
|||
EndIf</lang> |
|||
[[File:PureBasic_XOR_Pattern.png|Sample display of PureBasic solution|200px]] |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{libheader|PIL}} |
{{libheader|PIL}} |
||
< |
<syntaxhighlight lang="python">import Image, ImageDraw |
||
image = Image.new("RGB", (256, 256)) |
image = Image.new("RGB", (256, 256)) |
||
Line 859: | Line 1,659: | ||
del drawingTool |
del drawingTool |
||
image.save("xorpic.png", "PNG")</ |
image.save("xorpic.png", "PNG")</syntaxhighlight> |
||
[[File:PythonXORPic.png|Sample produced by the above code|200px]] |
[[File:PythonXORPic.png|Sample produced by the above code|200px]] |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
[[File:munching-racket.png|thumb|right]] |
[[File:munching-racket.png|thumb|right]] |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require racket/draw) |
(require racket/draw) |
||
Line 874: | Line 1,674: | ||
(send dc set-pixel x y c)) |
(send dc set-pixel x y c)) |
||
bm |
bm |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
Here's one simple way: |
|||
<syntaxhighlight lang="raku" line>my $ppm = open("munching0.ppm", :w) orelse .die; |
|||
$ppm.print(q :to 'EOT'); |
|||
P3 |
|||
256 256 |
|||
255 |
|||
EOT |
|||
for 0 .. 255 -> $row { |
|||
for 0 .. 255 -> $col { |
|||
my $color = $row +^ $col; |
|||
$ppm.print("0 $color 0 "); |
|||
} |
|||
$ppm.say(); |
|||
} |
|||
$ppm.close(); |
|||
</syntaxhighlight> |
|||
Another way: |
|||
<syntaxhighlight lang="raku" line>my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b }, |
|||
map -> $x { floor ($x/256) ** 3 * 256 }, |
|||
(flat (0...255) Z |
|||
(255...0) Z |
|||
flat (0,2...254),(254,252...0)); |
|||
my $PPM = open "munching1.ppm", :w orelse .die; |
|||
$PPM.print: qq:to/EOH/; |
|||
P6 |
|||
# munching.pgm |
|||
256 256 |
|||
255 |
|||
EOH |
|||
$PPM.write: @colors[$_] for ^256 X+^ ^256; |
|||
$PPM.close;</syntaxhighlight> |
|||
[[File:perl_6_xor_pattern.png|Raku output|200px]] |
|||
=={{header|REXX}}== |
|||
{{trans|Burlesque}} |
|||
<syntaxhighlight lang="rexx">/*REXX program renders a graphical pattern by coloring each pixel with x XOR y */ |
|||
/*───────────────────────────────────────── from an arbitrary constructed color table. */ |
|||
rows= 2 /*the number of rows in the color table*/ |
|||
cols= 5 /* " " " cols " " " " */ |
|||
do row =0 for rows*3 /*construct a color table, size 25x50.*/ |
|||
do col=0 for cols*3 |
|||
$= (row+col) // 255 |
|||
@.row.col= x2b( d2x($+0, 2) ) ||, /*ensure $ is converted──►2 hex nibbles*/ |
|||
x2b( d2x($+1, 2) ) ||, |
|||
x2b( d2x($+2, 2) ) |
|||
end /*col*/ /* [↑] construct a three-byte pixel. */ |
|||
end /*row*/ |
|||
do x=0 for cols /*create a graphical pattern with XORs.*/ |
|||
do y=0 for rows |
|||
@.x.y= bitxor(@.x, @.y) /*renders 3 bytes (a pixel) at a time. */ |
|||
end /*y*/ |
|||
end /*x*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
|||
Must be converted to an image with a separate program. <br><br> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
# Project : Munching squares |
|||
load "guilib.ring" |
|||
paint = null |
|||
new qapp |
|||
{ |
|||
win1 = new qwidget() { |
|||
setwindowtitle("Archimedean spiral") |
|||
setgeometry(100,100,500,600) |
|||
label1 = new qlabel(win1) { |
|||
setgeometry(10,10,400,400) |
|||
settext("") |
|||
} |
|||
new qpushbutton(win1) { |
|||
setgeometry(150,500,100,30) |
|||
settext("draw") |
|||
setclickevent("draw()") |
|||
} |
|||
show() |
|||
} |
|||
exec() |
|||
} |
|||
func draw |
|||
p1 = new qpicture() |
|||
color = new qcolor() { |
|||
setrgb(0,0,255,255) |
|||
} |
|||
pen = new qpen() { |
|||
setcolor(color) |
|||
setwidth(1) |
|||
} |
|||
paint = new qpainter() { |
|||
begin(p1) |
|||
setpen(pen) |
|||
w = 100 |
|||
for x = 0 to w |
|||
for y = 0 to w |
|||
b = (x ^ y) |
|||
color = new qcolor() |
|||
color.setrgb(255 -b,b /2,b,255) |
|||
pen.setcolor(color) |
|||
setpen(pen) |
|||
drawpoint(x,w -y -1) |
|||
next |
|||
next |
|||
endpaint() |
|||
} |
|||
label1 { setpicture(p1) show() } |
|||
return |
|||
</syntaxhighlight> |
|||
Output: |
|||
https://www.dropbox.com/s/wvdqyihtxralviz/Squares.jpg?dl=0 |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Uses [[Raster graphics operations/Ruby]] |
Uses [[Raster graphics operations/Ruby]] |
||
[[File:xorpattern_rb.png|thumb|right|Sample output from Ruby program]] |
[[File:xorpattern_rb.png|thumb|right|Sample output from Ruby program]] |
||
< |
<syntaxhighlight lang="ruby">load 'raster_graphics.rb' |
||
class Pixmap |
class Pixmap |
||
Line 903: | Line 1,833: | ||
img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW) |
img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW) |
||
img.save_as_png('xorpattern.png')</ |
img.save_as_png('xorpattern.png')</syntaxhighlight> |
||
=={{header| |
=={{header|Rust}}== |
||
<syntaxhighlight lang="rust">extern crate image; |
|||
<lang runbasic>w = 100 |
|||
graphic #g, w,w |
|||
use image::{ImageBuffer, Pixel, Rgb}; |
|||
for x = 0 to w |
|||
for y = 0 to w |
|||
fn main() { |
|||
b = (x xor y) and 255 |
|||
let mut img = ImageBuffer::new(256, 256); |
|||
#g color(255 -b,b /2,b) |
|||
#g "set "; x; " "; w -y -1 |
|||
for x in 0..256 { |
|||
next y |
|||
for y in 0..256 { |
|||
next x |
|||
let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0); |
|||
render #g |
|||
img.put_pixel(x, y, pixel); |
|||
#g "flush"</lang> |
|||
} |
|||
} |
|||
let _ = img.save("output.png"); |
|||
}</syntaxhighlight> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
===Scala Swing=== |
|||
{{libheader|Scala}} |
|||
{{libheader|org.scala-lang.modules scala-swing}} |
|||
<syntaxhighlight lang="scala">import scala.swing.Swing.pair2Dimension |
|||
import scala.swing.{ Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication } |
|||
import scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication} |
|||
object XorPattern extends SimpleSwingApplication { |
object XorPattern extends SimpleSwingApplication { |
||
def top = new MainFrame { |
|||
preferredSize = (300, 300) |
|||
title = "Rosetta Code >>> Task: Munching squares | Language: Scala" |
|||
contents = new Panel { |
|||
override def paintComponent(g: Graphics2D) = { |
protected override def paintComponent(g: Graphics2D) = { |
||
super.paintComponent(g) |
super.paintComponent(g) |
||
for { |
for { |
||
y <- 0 until size.getHeight |
y <- 0 until size.getHeight.toInt |
||
x <- 0 until size.getWidth |
x <- 0 until size.getWidth.toInt |
||
} { |
} { |
||
g.setColor(new Color(0, (x ^ y) % 256, 0)) |
g.setColor(new Color(0, (x ^ y) % 256, 0)) |
||
g.drawLine(x, y, x, y) |
g.drawLine(x, y, x, y) |
||
} |
|||
} |
} |
||
} |
} |
||
} |
|||
def top = new MainFrame { |
|||
preferredSize = (300, 300) |
|||
title = "Rosetta Code >>> Task: Munching squares | Language: Scala" |
|||
contents = ui |
|||
centerOnScreen() |
centerOnScreen() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang="ruby">require('Imager') |
||
var img = % |
var img = %O<Imager>.new(xsize => 256, ysize => 256) |
||
for y |
for y=(^256), x=(^256) { |
||
var |
var rgb = [(255 - x - y).abs, (255-x)^y, x^(255-y)] |
||
img. |
img.setpixel(x => x, y => y, color => rgb) |
||
} |
} |
||
img.write(file => 'xor.png')</syntaxhighlight> |
|||
Output image: [https://github.com/trizen/rc/blob/master/img/munching-squares-sidef.png Munching squares] |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{libheader|Tk}}< |
{{libheader|Tk}}<syntaxhighlight lang="tcl">package require Tk |
||
proc xorImage {img table} { |
proc xorImage {img table} { |
||
Line 987: | Line 1,923: | ||
set img [image create photo -width 512 -height 512] |
set img [image create photo -width 512 -height 512] |
||
xorImage $img [mkTable 0 255 64 192 255 0] |
xorImage $img [mkTable 0 255 64 192 255 0] |
||
pack [label .l -image $img]</ |
pack [label .l -image $img]</syntaxhighlight> |
||
=={{header| |
=={{header|Wren}}== |
||
{{trans|D}} |
|||
Due to the TI-83's 1 bit black and white display, this program uses the home screen and a |
|||
{{libheader|DOME}} |
|||
gradient of characters. Since the TI-83 does not use a standard encoding, |
|||
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color |
|||
the first Sto→ to Str1 may be subjectively interpreted. |
|||
import "dome" for Window |
|||
class Game { |
|||
static init() { |
|||
Window.title = "Munching squares" |
|||
var w = 512 |
|||
var h = 512 |
|||
Window.resize(w, h) |
|||
Canvas.resize(w, h) |
|||
for (x in 0...w) { |
|||
for (y in 0...h) { |
|||
var c = (x ^ y) & 255 |
|||
Canvas.pset(x, y, Color.rgb(255-c, (c/2).floor, c)) |
|||
} |
|||
} |
|||
} |
|||
static update() {} |
|||
<lang ti-83b>PROGRAM:XORPATT |
|||
" •.-,+-°-1+o*:πOX"→Str1 |
|||
static draw(alpha) {} |
|||
ClrHome |
|||
}</syntaxhighlight> |
|||
{0,0,0,0}→L1 |
|||
{0,0,0,0)→L2 |
|||
For(I,1,8,1) |
|||
For(J,1,16,1) |
|||
J→A |
|||
I→B |
|||
If A>8 |
|||
Then |
|||
A-8→A |
|||
1→L1(1) |
|||
Else |
|||
0→L1(1) |
|||
End |
|||
If A>4 |
|||
Then |
|||
A-4→A |
|||
1→L1(2) |
|||
Else |
|||
0→L1(2) |
|||
End |
|||
If A>2 |
|||
Then |
|||
A-2→A |
|||
1→L1(3) |
|||
Else |
|||
0→L1(3) |
|||
End |
|||
If A>1 |
|||
Then |
|||
1→L1(4) |
|||
Else |
|||
0→L1(4) |
|||
End |
|||
0→L2(1) |
|||
If B>4 |
|||
Then |
|||
B-4→B |
|||
1→L2(2) |
|||
Else |
|||
0→L2(2) |
|||
End |
|||
If B>2 |
|||
Then |
|||
B-2→B |
|||
1→L2(3) |
|||
Else |
|||
0→L2(3) |
|||
End |
|||
If B>1 |
|||
Then |
|||
1→L2(4) |
|||
Else |
|||
0→L2(4) |
|||
End |
|||
L1≠L2→L3 |
|||
8L3(1)+4L3(2)+2L3(3)+L3(4)→C |
|||
Output(I,J,sub(Str1,C+1,1)) |
|||
End |
|||
End |
|||
Pause |
|||
</lang> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
int X, Y; |
int X, Y; |
||
[SetVid($101); \set 640x480 graphics with 8-bit color |
[SetVid($101); \set 640x480 graphics with 8-bit color |
||
Line 1,088: | Line 1,966: | ||
X:= ChIn(1); \wait for keystroke |
X:= ChIn(1); \wait for keystroke |
||
SetVid(3); \restore normal text mode |
SetVid(3); \restore normal text mode |
||
]</ |
]</syntaxhighlight> |
||
{{out}} [[File:MunchXPL0.png]] |
{{out}} [[File:MunchXPL0.png]] |
||
Line 1,095: | Line 1,973: | ||
{{trans|XPL0}} |
{{trans|XPL0}} |
||
For a kaleidoscopic image, play with coolness. |
For a kaleidoscopic image, play with coolness. |
||
< |
<syntaxhighlight lang="zkl">fcn muncher{ |
||
bitmap:=PPM(256,256); |
bitmap:=PPM(256,256); |
||
coolness:=(1).random(0x10000); // 55379, 18180, 40, 51950, 57619, 43514, 65465 |
coolness:=(1).random(0x10000); // 55379, 18180, 40, 51950, 57619, 43514, 65465 |
||
Line 1,106: | Line 1,984: | ||
} |
} |
||
bitmap.write(File("foo.ppm","wb")); |
bitmap.write(File("foo.ppm","wb")); |
||
}();</ |
}();</syntaxhighlight> |
||
For a cheap slide show (on Linux): |
For a cheap slide show (on Linux): |
||
< |
<syntaxhighlight lang="zkl">while(1){ muncher(); Atomic.sleep(3); }</syntaxhighlight> |
||
run ImageViewer on foo.ppm and watch it [auto] update as the image changes. |
run ImageViewer on foo.ppm and watch it [auto] update as the image changes. |
||
{{out}} |
{{out}} |
Latest revision as of 14:53, 4 January 2024
You are encouraged to solve this task according to the task description, using any language you may know.
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
Action!
PROC PutBigPixel(BYTE x,y,c)
BYTE i
Color=c
x=x*3+16
y=y*12
FOR i=0 TO 11
DO
Plot(x,y+i)
DrawTo(x+2,y+i)
OD
RETURN
PROC Main()
BYTE
CH=$02FC, ;Internal hardware value for last key pressed
x,y
Graphics(9)
FOR y=0 TO 15
DO
FOR x=0 TO 15
DO
PutBigPixel(x,y,x!y)
OD
OD
DO UNTIL CH#$FF OD
CH=$FF
RETURN
- Output:
Screenshot from Atari 8-bit computer
Ada
Uses the Cairo component of GtkAda to create and save as png
with Cairo; use Cairo;
with Cairo.Png; use Cairo.Png;
with Cairo.Image_Surface; use Cairo.Image_Surface;
procedure XorPattern is
type xorable is mod 256;
Surface : Cairo_Surface;
Data : RGB24_Array_Access;
Status : Cairo_Status;
Num : Byte;
begin
Data := new RGB24_Array(0..256*256-1);
for x in Natural range 0..255 loop
for y in Natural range 0..255 loop
Num := Byte(xorable(x) xor xorable(y));
Data(x+256*y) := RGB24_Data'(Num,0,Num);
end loop;
end loop;
Surface := Create_For_Data_RGB24(Data, 256, 256);
Status := Write_To_Png (Surface, "AdaXorPattern.png");
pragma Assert (Status = Cairo_Status_Success);
end XorPattern;
- Output:
ATS
#include "share/atspre_staload.hats"
(* uint2uchar0 seems to have a definition in the prelude, but no
implementation. Such incompletenesses are common, but usually
easily overcome. Here I simply redefine uint2uchar0 locally,
letting C do the casting. *)
extern castfn uint2uchar0 : uint -<> uchar
(* write_pam writes a Portable Arbitrary Map to standard output. It
XORs the positions of colors in a palette of size equal to a power
of two, containing RGB colors in the usual hex format. The palette
is otherwise arbitrary. *)
fn
write_pam {expnt : nat}
{numcolors : nat}
(* The palette size must be proven to be a power of two. *)
(pf : EXP2 (expnt, numcolors) |
palette : &array (uint, numcolors),
numcolors : uint numcolors) : void =
let
fun
loop {x, y : nat | x <= numcolors; y <= numcolors}
.<numcolors - y, numcolors - x>.
(palette : &array (uint, numcolors),
x : uint x,
y : uint y) : void =
if y = numcolors then
()
else if x = numcolors then
loop (palette, 0u, succ y)
else
let
val i = g1ofg0 (x lxor y)
(* Prove that the index is non-negative. *)
prval () = lemma_g1uint_param i
(* Test that the index is not out of bounds high. This could
be proven without a runtime check, but doing that is left
as an exercise for an advanced reader. For one thing, you
will need a more complicated version of lxor. Then you
will need to prove, or provide as an axiom, that the XOR
of two numbers of the same number of significant bits is
itself restricted to that number of bits. *)
val () = assertloc (i < numcolors)
val color = palette[i]
val r = uint2uchar0 (color >> 16)
and g = uint2uchar0 ((color >> 8) land 0xFFu)
and b = uint2uchar0 (color land 0xFFu)
in
print! (r, g, b);
loop (palette, succ x, y)
end
in
println! ("P7");
println! ("WIDTH ", numcolors);
println! ("HEIGHT ", numcolors);
println! ("DEPTH 3");
println! ("MAXVAL 255");
println! ("TUPLTYPE RGB");
println! ("ENDHDR");
loop (palette, 0u, 0u)
end
prfn (* Produces a proof that 2**7 = 128. *)
exp2_of_7_is_128 () :<prf> EXP2 (7, 128) =
EXP2ind (EXP2ind (EXP2ind (EXP2ind
(EXP2ind (EXP2ind (EXP2ind (EXP2bas ())))))))
implement
main0 () =
let
(* 128 RGB colors borrowed from
https://github.com/yeun/open-color *)
var palette : array (uint, 128) =
@[uint][128]
(0xe9ecefu, 0xdee2e6u, 0xced4dau, 0xadb5bdu, 0x868e96u, 0x495057u,
0x343a40u, 0x212529u, 0xfff5f5u, 0xffe3e3u, 0xffc9c9u, 0xffa8a8u,
0xff8787u, 0xff6b6bu, 0xfa5252u, 0xf03e3eu, 0xe03131u, 0xc92a2au,
0xfff0f6u, 0xffdeebu, 0xfcc2d7u, 0xfaa2c1u, 0xf783acu, 0xf06595u,
0xe64980u, 0xd6336cu, 0xc2255cu, 0xa61e4du, 0xf8f0fcu, 0xf3d9fau,
0xeebefau, 0xe599f7u, 0xda77f2u, 0xcc5de8u, 0xbe4bdbu, 0xae3ec9u,
0x9c36b5u, 0x862e9cu, 0xf3f0ffu, 0xe5dbffu, 0xd0bfffu, 0xb197fcu,
0x9775fau, 0x845ef7u, 0x7950f2u, 0x7048e8u, 0x6741d9u, 0x5f3dc4u,
0xedf2ffu, 0xdbe4ffu, 0xbac8ffu, 0x91a7ffu, 0x748ffcu, 0x5c7cfau,
0x4c6ef5u, 0x4263ebu, 0x3b5bdbu, 0x364fc7u, 0xe7f5ffu, 0xd0ebffu,
0xa5d8ffu, 0x74c0fcu, 0x4dabf7u, 0x339af0u, 0x228be6u, 0x1c7ed6u,
0x1971c2u, 0x1864abu, 0xe3fafcu, 0xc5f6fau, 0x99e9f2u, 0x66d9e8u,
0x3bc9dbu, 0x22b8cfu, 0x15aabfu, 0x1098adu, 0x0c8599u, 0x0b7285u,
0xe6fcf5u, 0xc3fae8u, 0x96f2d7u, 0x63e6beu, 0x38d9a9u, 0x20c997u,
0x12b886u, 0x0ca678u, 0x099268u, 0x087f5bu, 0xebfbeeu, 0xd3f9d8u,
0xb2f2bbu, 0x8ce99au, 0x69db7cu, 0x51cf66u, 0x40c057u, 0x37b24du,
0x2f9e44u, 0x2b8a3eu, 0xf4fce3u, 0xe9fac8u, 0xd8f5a2u, 0xc0eb75u,
0xa9e34bu, 0x94d82du, 0x82c91eu, 0x74b816u, 0x66a80fu, 0x5c940du,
0xfff9dbu, 0xfff3bfu, 0xffec99u, 0xffe066u, 0xffd43bu, 0xfcc419u,
0xfab005u, 0xf59f00u, 0xf08c00u, 0xe67700u, 0xfff4e6u, 0xffe8ccu,
0xffd8a8u, 0xffc078u, 0xffa94du, 0xff922bu, 0xfd7e14u, 0xf76707u,
0xe8590cu, 0xd9480fu)
in
write_pam (exp2_of_7_is_128 () | palette, 128u)
end
Here I use Netpbm to make a PNG, but you could use, for instance, ImageMagick instead. (Then I generally run my PNGs through optipng before posting them.)
patscc -std=gnu2x -g -O2 munching_squares.dats && ./a.out | pamtopng > image.png
- Output:
AWK
This program generates a PPM image, that you can view/convert using The GIMP or ImageMagick
BEGIN {
# square size
s = 256
# the PPM image header needs 3 lines:
# P3
# width height
# max colors number (per channel)
print("P3\n", s, s, "\n", s - 1)
# and now we generate pixels as a RGB pair in a relaxed
# form "R G B\n"
for (x = 0; x < s; x++) {
for (y = 0; y < s; y++) {
p = xor(x, y)
print(0, p, p)
}
}
}
BASIC
Applesoft BASIC
100 DATA 0,2, 6,10,5, 6, 7,15
110 DATA 0,1, 3,10,5, 3,11,15
120 DATA 0,8, 9,10,5, 9,13,15
130 DATA 0,4,12,10,5,12,14,15
140 LET C = 7
150 POKE 768,169: REM LDA #
160 POKE 770,073: REM EOR #
170 POKE 772,133: REM STA
180 POKE 773,235: REM $EB
190 POKE 774,096: REM RTS
200 GR
210 FOR H = 0 TO 1
220 FOR W = 0 TO 1
230 FOR S = 0 TO C
240 READ C(S)
250 NEXT S
260 FOR Y = 0 TO C
270 POKE 769,Y
280 LET Y1 = H * S * 2 + Y * 2
290 FOR X = 0 TO C
300 POKE 771,X
310 CALL 768
320 COLOR= C( PEEK (235))
330 VLIN Y1,Y1 + 1 AT W * S + X
340 NEXT X,Y,W,H
BBC BASIC
size% = 256
VDU 23,22,size%;size%;8,8,16,0
OFF
DIM coltab%(size%-1)
FOR I% = 0 TO size%-1
coltab%(I%) = ((I% AND &FF) * &010101) EOR &FF0000
NEXT
GCOL 1
FOR I% = 0 TO size%-1
FOR J% = 0 TO size%-1
C% = coltab%(I% EOR J%)
COLOUR 1, C%, C%>>8, C%>>16
PLOT I%*2, J%*2
NEXT
NEXT I%
REPEAT WAIT 1 : UNTIL FALSE
Commodore BASIC
The TED machines (C-16, Plus/4) are the only Commodore 8-bits with a large- or structured- enough color palette to make this interesting. Here's an extremely low-res version (40x25 character-sized "pixels"):
100 FOR I=0 TO 24
110 : Y=INT(I*127/24)
120 : FOR J=0 TO 39
130 : X=INT(J*127/39)
140 : HL = (X OR Y) AND NOT (X AND Y)
150 : H = INT(HL / 8)
160 : L = HL - 8 * H
170 : POKE 2048+I*40+J,L*16+H
180 : POKE 3072+I*40+J,160
190 : NEXT J
210 NEXT I
220 GETKEY K$
- Output:
Craft Basic
let s = 255
for y = 0 to s
for x = 0 to s
let r = x ~ y
fgcolor r, r * 2, r * 3
dot x, y
wait
next x
next y
FreeBASIC
' version 03-11-2016
' compile with: fbc -s gui
Dim As ULong x, y, r, w = 256
ScreenRes w, w, 32
For x = 0 To w -1
For y = 0 To w -1
r =(x Xor y) And 255
PSet(x, y), RGB(r, r , r) ' gray scale
' PSet(x, y), RGB(r, 255 - r, 0) ' red + green
' PSet(x, y), RGB(r, 0, 0) ' red
Next
Next
' empty keyboard buffer
While Inkey <> "" : Wend
WindowTitle "Close window or hit any key to end program"
Sleep
End
Liberty BASIC
nomainwin
w =512
' allow for title bar and window border
WindowWidth =w +2
WindowHeight =w +34
open "XOR Pattern" for graphics_nsb_nf as #w
#w "trapclose quit"
#w "down"
for x =0 to w -1
for y =0 to w -1
b =( x xor y) and 255
print b
#w "color "; 255 -b; " "; b /2; " "; b
#w "set "; x; " "; w -y -1
scan
next y
next x
#w "flush"
wait
sub quit j$
close #w
end
end sub
Image available at [[1]]
Microsoft Small Basic
' Munching squares - smallbasic - 27/07/2018
size=256
GraphicsWindow.Width=size
GraphicsWindow.Height=size
For i=0 To size-1
For j=0 To size-1
BitXor() 'color=i Xor j
GraphicsWindow.SetPixel(i,j,GraphicsWindow.GetColorFromRGB(0,color,color))
EndFor
EndFor
Sub BitXor '(i,j)->color
n=i
Int2Bit()
ib=ret
n=j
Int2Bit()
jb=ret
color=0
For k=1 to 8
ki=Text.GetSubText(ib,k,1)
kj=Text.GetSubText(jb,k,1)
If ki="1" Or kj="1" Then
kk="1"
Else
kk="0"
EndIf
If ki="1" And kj="1" Then
kk="0"
EndIf
color=2*color+kk
EndFor
EndSub
Sub Int2Bit 'n->ret
x=n
ret=""
For k=1 to 8
t=Math.Floor(x/2)
r=Math.Remainder(x,2)
ret=Text.Append(r,ret)
x=t
EndFor
EndSub
- Output:
PureBasic
#palletteSize = 128
Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values
Protected result = x ! y
ProcedureReturn Mod(result, #palletteSize) / #palletteSize
EndProcedure
Procedure drawPattern()
StartDrawing(ImageOutput(0))
DrawingMode(#PB_2DDrawing_Gradient)
CustomGradient(@XorPattern())
;specify a gradient pallette from which only specific indexes will be used
For i = 1 To #palletteSize
GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD
Next
Box(0, 0, ImageWidth(0), ImageHeight(0))
StopDrawing()
EndProcedure
If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu)
CreateImage(0, WindowWidth(0), WindowHeight(0))
drawPattern()
ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0))
Repeat
event = WaitWindowEvent(20)
Until event = #PB_Event_CloseWindow
EndIf
QBasic
w = 254
SCREEN 13
VIEW (0, 0)-(w / 2, w / 2), , 0
FOR x = 0 TO w
FOR y = 0 TO w
COLOR ((x XOR y) AND 255)
PSET (x, y)
NEXT y
NEXT x
RapidQ
'Munching squares
DECLARE SUB PaintCanvas
CREATE Form AS QForm
ClientWidth = 256
ClientHeight = 256
CREATE Canvas AS QCanvas
Height = Form.ClientHeight
Width = Form.ClientWidth
OnPaint = PaintCanvas
END CREATE
END CREATE
SUB PaintCanvas
FOR X = 0 TO Canvas.Width - 1
FOR Y = 0 TO Canvas.Width - 1
R = (X XOR Y) AND 255
Canvas.Pset(X, Y, RGB(R, R, R)) ' gray scale
'Canvas.Pset(X, Y, RGB(R, 255 - R, 0)) ' red + green
'Canvas.Pset(X, Y, RGB(R, 0, 0)) ' red
NEXT Y
NEXT X
END SUB
Form.ShowModal
Run BASIC
w = 100
graphic #g, w,w
for x = 0 to w
for y = 0 to w
b = (x xor y) and 255
#g color(255 -b,b /2,b)
#g "set "; x; " "; w -y -1
next y
next x
render #g
#g "flush"
TI-83 BASIC
Due to the TI-83's 1 bit black and white display, this program uses the home screen and a gradient of characters. Since the TI-83 does not use a standard encoding, the first Sto→ to Str1 may be subjectively interpreted.
PROGRAM:XORPATT
" •.-,+-°-1+o*:πOX"→Str1
ClrHome
{0,0,0,0}→L1
{0,0,0,0)→L2
For(I,1,8,1)
For(J,1,16,1)
J→A
I→B
If A>8
Then
A-8→A
1→L1(1)
Else
0→L1(1)
End
If A>4
Then
A-4→A
1→L1(2)
Else
0→L1(2)
End
If A>2
Then
A-2→A
1→L1(3)
Else
0→L1(3)
End
If A>1
Then
1→L1(4)
Else
0→L1(4)
End
0→L2(1)
If B>4
Then
B-4→B
1→L2(2)
Else
0→L2(2)
End
If B>2
Then
B-2→B
1→L2(3)
Else
0→L2(3)
End
If B>1
Then
1→L2(4)
Else
0→L2(4)
End
L1≠L2→L3
8L3(1)+4L3(2)+2L3(3)+L3(4)→C
Output(I,J,sub(Str1,C+1,1))
End
End
Pause
Visual Basic .NET
' Munching squares - 27/07/2018
Public Class MunchingSquares
Const xsize = 256
Dim BMP As New Drawing.Bitmap(xsize, xsize)
Dim GFX As Graphics = Graphics.FromImage(BMP)
Private Sub MunchingSquares_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
'draw
Dim MyGraph As Graphics = Me.CreateGraphics
Dim nColor As Color
Dim i, j, cp As Integer
xPictureBox.Image = BMP
For i = 0 To xsize - 1
For j = 0 To xsize - 1
cp = i Xor j
nColor = Color.FromArgb(cp, 0, cp)
BMP.SetPixel(i, j, nColor)
Next j
Next i
End Sub 'Paint
End Class
- Output:
Yabasic
w = 256
open window w, w
For x = 0 To w-1
For y = 0 To w-1
r =and(xor(x, y), 255)
color r, and(r*2, 255), and(r*3, 255)
dot x, y
Next
Next
Befunge
Writes the image to stdout using the PPM format.
55+::"3P",,,28*:*::..\,:.\,:v
>2%*28*:**-2/\1-:v<:8:-1<_@ v
^\-1*2%2/*:*82::\_$0.0..:^:*<
BQN
Outputs a string that represents a PPM image.
BQN uses the •bit
namespace for native bitwise operations, including casting. An input bit width and output bit width have to be given.
nl←@+10
XORppm ← {
g←⥊(0∾∾˜)¨((↕𝕩)16‿16•bit._xor⊢)˘↕𝕩
s←•Repr 𝕩
h←"P3"∾nl∾s∾" "∾s∾nl∾(•Repr 𝕩-1)∾nl
h∾∾∾⟜nl¨{¯1↓∾∾⟜' '¨•Repr¨𝕩}¨g
}
Example usage:
"xor.ppm" •FChars XORppm 256
Burlesque
blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16 19 18 21 20 23 22 25 24
2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13 18 19 16 17 22 23 20 21 26 27
3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 19 18 17 16 23 22 21 20 27 26
4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11 20 21 22 23 16 17 18 19 28 29
5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10 21 20 23 22 17 16 19 18 29 28
6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9 22 23 20 21 18 19 16 17 30 31
7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 23 22 21 20 19 18 17 16 31 30
8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 24 25 26 27 28 29 30 31 16 17
9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6 25 24 27 26 29 28 31 30 17 16
10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5 26 27 24 25 30 31 28 29 18 19
11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4 27 26 25 24 31 30 29 28 19 18
12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3 28 29 30 31 24 25 26 27 20 21
13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2 29 28 31 30 25 24 27 26 21 20
14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1 30 31 28 29 26 27 24 25 22 23
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 23 22
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8 9
17 16 19 18 21 20 23 22 25 24 27 26 29 28 31 30 1 0 3 2 5 4 7 6 9 8
18 19 16 17 22 23 20 21 26 27 24 25 30 31 28 29 2 3 0 1 6 7 4 5 10 11
19 18 17 16 23 22 21 20 27 26 25 24 31 30 29 28 3 2 1 0 7 6 5 4 11 10
20 21 22 23 16 17 18 19 28 29 30 31 24 25 26 27 4 5 6 7 0 1 2 3 12 13
21 20 23 22 17 16 19 18 29 28 31 30 25 24 27 26 5 4 7 6 1 0 3 2 13 12
22 23 20 21 18 19 16 17 30 31 28 29 26 27 24 25 6 7 4 5 2 3 0 1 14 15
23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24 7 6 5 4 3 2 1 0 15 14
24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23 8 9 10 11 12 13 14 15 0 1
25 24 27 26 29 28 31 30 17 16 19 18 21 20 23 22 9 8 11 10 13 12 15 14 1 0
Must be converted to an image with a seperate program.
C
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
void hue_to_rgb(double hue, double sat, unsigned char *p)
{
double x;
int c = 255 * sat;
hue /= 60;
x = (1 - fabs(fmod(hue, 2) - 1)) * 255;
switch((int)hue) {
case 0: p[0] = c; p[1] = x; p[2] = 0; return;
case 1: p[0] = x; p[1] = c; p[2] = 0; return;
case 2: p[0] = 0; p[1] = c; p[2] = x; return;
case 3: p[0] = 0; p[1] = x; p[2] = c; return;
case 4: p[0] = x; p[1] = 0; p[2] = c; return;
case 5: p[0] = c; p[1] = 0; p[2] = x; return;
}
}
int main(void)
{
const int size = 512;
int i, j;
unsigned char *colors = malloc(size * 3);
unsigned char *pix = malloc(size * size * 3), *p;
FILE *fp;
for (i = 0; i < size; i++)
hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i);
for (i = 0, p = pix; i < size; i++)
for (j = 0; j < size; j++, p += 3)
memcpy(p, colors + (i ^ j) * 3, 3);
fp = fopen("xor.ppm", "wb");
fprintf(fp, "P6\n%d %d\n255\n", size, size);
fwrite(pix, size * size * 3, 1, fp);
fclose(fp);
return 0;
}
- Output:
C#
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
class XORPattern
{
static void Main()
{
var size = 0x100;
var black = Color.Black.ToArgb();
var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray();
using (var image = new Bitmap(size, size))
{
for (var x = 0; x < size; x++)
{
for (var y = 0; y < size; y++)
{
image.SetPixel(x, y, palette[x ^ y]);
}
}
image.Save("XORPatternCSharp.png", ImageFormat.Png);
}
}
}
- Output:
C++
#include <windows.h>
#include <string>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int BMP_SIZE = 512;
//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
//--------------------------------------------------------------------------------------------------
class mSquares
{
public:
mSquares()
{
bmp.create( BMP_SIZE, BMP_SIZE );
createPallete();
}
void draw()
{
HDC dc = bmp.getDC();
for( int y = 0; y < BMP_SIZE; y++ )
for( int x = 0; x < BMP_SIZE; x++ )
{
int c = ( x ^ y ) % 256;
SetPixel( dc, x, y, clrs[c] );
}
BitBlt( GetDC( GetConsoleWindow() ), 30, 30, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
//bmp.saveBitmap( "f:\\rc\\msquares_cpp.bmp" );
}
private:
void createPallete()
{
for( int x = 0; x < 256; x++ )
clrs[x] = RGB( x<<1, x, x<<2 );//rand() % 180 + 50, rand() % 200 + 50, rand() % 180 + 50 );
}
unsigned int clrs[256];
myBitmap bmp;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
srand( GetTickCount() );
mSquares s; s.draw();
return system( "pause" );
}
//--------------------------------------------------------------------------------------------------
Clojure
The fun part of munching squares isn't color tables, it's watching them munch:
(let [n 16]
(loop [i 0]
(print "\033[0;0f\033[2J")
(doseq [y (range n)]
(doseq [x (range n)]
(print (if (< (bit-xor x y) i) "█" " ")))
(print "\n"))
(flush)
(Thread/sleep 150)
(recur (mod (inc i) (inc n)))))
Evaldraw
Since all variables in Evaldraw are doubles, convert to binary and do a custom per bit xor operation.
enum{NUMBITS=7, MAXNUMS=3}
static binary[MAXNUMS][NUMBITS];
() {
cls(0);
t = 100*klock();
for(y = 0; y < 128; y++) {
decToBin(y,1);
for(x = 0; x < 128; x++) {
decToBin(x,0);
xor(0,1,2);
c = binToDec(2);
setcol(hsv_to_rgb( (t+c*1)%360,.8,1) );
setpix(x,y);
}
}
}
binToDec(id) {
num = 0;
for(i=0; i<NUMBITS; i++) {
if( binary[id][i] == 1) {
num += 2^(NUMBITS-i-1);
}
}
return num;
}
decToBin(num,id) {
for(i=0; i<NUMBITS; i++) binary[id][i] = 0;
bitpos = NUMBITS-1;
while( num > 0 && bitpos >= 0) {
binary[id][bitpos] = num % 2 == 1;
bitpos--; // ready for next bit
num = int(num/2);
}
}
xor(num1,num2,store) {
for(i=0; i<NUMBITS; i++)
if(binary[num1][i] == binary[num2][i]) binary[store][i] = 0; else binary[store][i] = 1;
}
D
void main() {
import std.stdio;
enum width = 512, height = 512;
auto f = File("xor_pattern.ppm", "wb");
f.writefln("P6\n%d %d\n255", width, height);
foreach (immutable y; 0 .. height)
foreach (immutable x; 0 .. width) {
immutable c = (x ^ y) & ubyte.max;
immutable ubyte[3] u3 = [255 - c, c / 2, c];
f.rawWrite(u3);
}
}
Delphi
procedure MunchingSquares(Image: TImage);
{XOR's X and Y to select an RGB level}
var W,H,X,Y: integer;
begin
W:=Image.Width;
H:=Image.Height;
for Y:=0 to Image.Height-1 do
for X:=0 to Image.Width-1 do
begin
Image.Canvas.Pixels[X,Y]:=RGB(0,X xor Y,0);
end;
end;
- Output:
EasyLang
sc = 100 / 64
for x range0 64
for y range0 64
h = bitand bitxor x y 63
c = h / 63
color3 c c c
move x * sc y * sc
rect sc + 0.1 sc + 0.1
.
.
EchoLisp
Use the plot library, hsv->rgb ((x xor y) modulo m) as color table, and see the nice results here : http://www.echolalie.org/echolisp/help.html#bit-map .
(lib 'types)
(lib 'plot)
(plot-size 512 512) ;; for example
;; use m = 16, 32, 44, .. to change the definition (number of losanges)
(define (plot-munch (m 256))
(define PIX (pixels->int32-vector)) ;; get canvas image
(define (pcolor x y) ;; color at (x,y)
(hsv->rgb
(// (bitwise-xor (modulo x m) (modulo y m)) m)
0.9
0.9))
(pixels-map pcolor PIX)
(vector->pixels PIX)) ;; draw canvas image
(plot-much) ;; ESC to see tge drawing
Factor
USING: accessors images images.loader kernel math sequences ;
IN: rosetta-code.munching-squares
: img-data ( -- seq ) 256 sq [ B{ 0 0 0 255 } ] replicate ;
: (munching) ( elt index -- elt' )
256 /mod bitxor [ rest ] dip prefix ;
: munching ( -- seq )
img-data [ (munching) ] map-index B{ } concat-as ;
: <munching-img> ( -- img )
<image>
{ 256 256 } >>dim
BGRA >>component-order
ubyte-components >>component-type
munching >>bitmap ;
: main ( -- ) <munching-img> "munching.png" save-graphic-image ;
MAIN: main
Output image is identical to the Racket version.
- Output:
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Test case
GLSL
This is an example that will work directly on shadertoy.com, Example [2]
vec3 color;
float c,p;
vec2 b;
void main(void)
{
vec2 uv = gl_FragCoord.xy / iResolution.xy;
float scale = iResolution.x / iResolution.y;
uv = uv-0.5;
uv.y/=scale;
b = uv*256.0+256.0;
c = 0.0;
for(float i=16.0;i>=1.0;i-=1.0)
{
p = pow(2.0,i);
if((p < b.x) ^^
(p < b.y))
{
c += p;
}
if(p < b.x)
{
b.x -= p;
}
if(p < b.y)
{
b.y -= p;
}
}
c=mod(c/128.0,1.0);
color = vec3(sin(c+uv.x*cos(uv.y*1.2)), tan(c+uv.y-0.3)*1.1, cos(c-uv.y+0.9));
gl_FragColor = vec4(color,1.0);
}
Gnuplot
set pm3d map
set size square
set isosamples 255,255
splot [0:255][0:255]-(floor(x)^floor(y))
- Output:
Go
package main
import (
"image"
"image/png"
"os"
)
func main() {
g := image.NewGray(image.Rect(0, 0, 256, 256))
for i := range g.Pix {
g.Pix[i] = uint8(i>>8 ^ i)
}
f, _ := os.Create("xor.png")
png.Encode(f, g)
f.Close()
}
Haskell
import qualified Data.ByteString as BY (writeFile, pack)
import Data.Bits (xor)
main :: IO ()
main =
BY.writeFile
"out.pgm"
(BY.pack
(fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++
[ x `xor` y
| x <- [0 .. 255]
, y <- [0 .. 255] ]))
Icon and Unicon
printf.icn provides formatting
J
require 'viewmat'
viewmat ~:"1/&.#: ~ i.256
Java
This example will repeat the pattern if you expand the window.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class XorPattern extends JFrame{
private JPanel xorPanel;
public XorPattern(){
xorPanel = new JPanel(){
@Override
public void paint(Graphics g) {
for(int y = 0; y < getHeight();y++){
for(int x = 0; x < getWidth();x++){
g.setColor(new Color(0, (x ^ y) % 256, 0));
g.drawLine(x, y, x, y);
}
}
}
};
add(xorPanel);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new XorPattern();
}
}
jq
The following is an adaptation of the Ruby entry, but generates an SVG image file:
jq -n -r -f Munching_squares.jq > Munching_squares.svg
Part 1: Infrastructure
# Convert the input integer to an array of bits with lsb first
def integer_to_lsb:
[recurse(if . > 0 then ./2|floor else empty end) | . % 2] ;
# input array of bits (with lsb first) is converted to an integer
def lsb_to_integer:
reduce .[] as $bit
# state: [power, ans]
([1,0]; (.[0] * 2) as $b | [$b, .[1] + (.[0] * $bit)])
| .[1];
def xor(x;y):
def lxor(a;b): # a and/or b may be null
if a == 1 then if b==1 then 0 else 1 end
elif b==1 then if a==1 then 0 else 1 end
else 0
end;
(x|integer_to_lsb) as $s
| (y|integer_to_lsb) as $t
| ([$s|length, $t|length] | max) as $length
| reduce range(0;$length) as $i
([]; . + [ lxor($s[$i]; $t[$i]) ] )
| lsb_to_integer;
Part 2: SVG
def rgb2rgb:
def p: (. + 0.5) | floor; # to nearest integer
"rgb(\(.red|p),\(.green|p),\(.blue|p))";
def svg(width; height):
"<svg width='\(width // "100%")' height='\(height // "100%")'
xmlns='http://www.w3.org/2000/svg'>";
def pixel(x; y; color):
(color | if type == "string" then . else rgb2rgb end) as $c
| "<circle r='1' cx='\(x)' cy='\(y)' fill='\($c)' />";
Part 3: xor pattern
# rgb is a JSON object: { "red": _, "green": _, "blue": _}
def xor_pattern(width; height; rgb1; rgb2):
# create colour table
256 as $size
| (reduce range(0;$size) as $i
([]; . + [
{"red": (rgb1.red + (rgb2.red - rgb1.red) * $i / $size),
"green": (rgb1.green + (rgb2.green - rgb1.green) * $i / $size),
"blue": (rgb1.blue + (rgb2.blue - rgb1.blue) * $i / $size) }])
) as $colours
# create the image
| svg(width; height),
( (range(0;width) as $x
| range(0;height) as $y
| pixel($x; $y; $colours[ xor($x; $y) % $size] ) ) ),
"</svg>" ;
Part 4: Example
def black: { "red": 0, "green": 0, "blue": 0};
def red: black + { "red": 255 };
def yellow: red + { "green": 255 };
xor_pattern(384; 384; red; yellow)
Julia
using Gtk, Cairo
const can = @GtkCanvas()
const win = GtkWindow(can, "Munching Squares", 512, 512)
@guarded draw(can) do widget
ctx = getgc(can)
for x in 0:255, y in 0:255
set_source_rgb(ctx, abs(255 - x - y) / 255, ((255 - x) ⊻ y) / 255, (x ⊻ (255 - y)) / 255)
circle(ctx, 2x, 2y, 2)
fill(ctx)
end
end
show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
wait(cond)
Kotlin
// version 1.1.4-3
import javax.swing.JFrame
import javax.swing.JPanel
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Color
import java.awt.Dimension
import java.awt.BorderLayout
import java.awt.RenderingHints
import javax.swing.SwingUtilities
class XorPattern : JPanel() {
init {
preferredSize = Dimension(256, 256)
background = Color.white
}
override fun paint(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
for (y in 0 until width) {
for (x in 0 until height) {
g.color = Color(0, (x xor y) % 256, 255)
g.drawLine(x, y, x, y)
}
}
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with (f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Munching squares"
isResizable = false
add(XorPattern(), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
Lua
local clr = {}
function drawMSquares()
local points = {}
for y = 0, hei-1 do
for x = 0, wid-1 do
local idx = bit.bxor(x, y)%256
local r, g, b = clr[idx][1], clr[idx][2], clr[idx][3]
local point = {x+1, y+1, r/255, g/255, b/255, 1}
table.insert (points, point)
end
end
love.graphics.points(points)
end
function createPalette()
for i = 0, 255 do
clr[i] = {i*2.8%256, i*3.2%256, i*1.5%256}
end
end
function love.load()
wid, hei = 256, 256
love.window.setMode(wid, hei)
canvas = love.graphics.newCanvas()
love.graphics.setCanvas(canvas)
createPalette()
drawMSquares()
love.graphics.setCanvas()
end
function love.draw()
love.graphics.setColor(1,1,1)
love.graphics.draw(canvas)
end
Mathematica/Wolfram Language
ListDensityPlot[
Table[Table[
FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]],
2], {x, 0, 255}], {y, 0, 255}]]
- Output #1:
ArrayPlot[Array[BitXor, {511, 511}]]
- Output #2:
MATLAB
size = 256;
[x,y] = meshgrid([0:size-1]);
c = bitxor(x,y);
colormap bone(size);
image(c);
axis equal;
- Output:
MiniScript
This version runs in Mini Micro (for the graphics, and the bitXor intrinsic).
for x in range(0,255)
for y in range(0,255)
gfx.setPixel x, y, color.rgb(0, bitXor(x,y), 0)
end for
end for
- Output:
Nim
import random
import imageman
randomize()
# Build a color table.
var colors: array[256, ColorRGBU]
for color in colors.mitems:
color = ColorRGBU [byte rand(255), byte rand(255), byte rand(255)]
var image = initImage[ColorRGBU](256, 256)
for i in 0..255:
for j in 0..255:
image[i, j] = colors[i xor j]
image.savePNG("munching_squares.png")
OCaml
open Graphics
let () =
open_graph "";
resize_window 256 256;
for y = 0 to pred (size_y()) do
for x = 0 to pred (size_x()) do
let v = (x lxor y) land 0xFF in
set_color (rgb v (255 - v) 0);
plot x y
done;
done;
ignore(read_key())
Run with:
$ ocaml graphics.cma xor_pattern.ml
- Output:
Octave
size = 256;
[x,y] = meshgrid([0:size-1]);
c = bitxor(x,y);
colormap(jet(size));
image(c);
axis equal;
- Output:
Perl
use GD;
my $img = GD::Image->new(256, 256, 1);
for my $y (0..255) {
for my $x (0..255) {
my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y));
$img->setPixel($x, $y, $color);
}
}
print $img->png
- Output:
Phix
You can run this online here.
-- -- demo\rosetta\Munching_squares.exw -- ================================= -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) for y=0 to height-1 do for x=0 to width-1 do cdCanvasPixel(cddbuffer, x, y, xor_bits(x,y)) end for end for cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_RED) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=250x250") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas, `TITLE="Munching squares",RESIZE=NO`) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
PHP
header("Content-Type: image/png");
$w = 256;
$h = 256;
$im = imagecreate($w, $h)
or die("Cannot Initialize new GD image stream");
$color = array();
for($i=0;$i<256;$i++)
{
array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i));
}
for($i=0;$i<$w;$i++)
{
for($j=0;$j<$h;$j++)
{
imagesetpixel($im,$i,$j,$color[$i^$j]);
}
}
imagepng($im);
imagedestroy($im);
- Output:
PL/I
munch: procedure options (main); /* 21 May 2014 */
declare screen (0:255, 0:255) bit(24) aligned;
declare b bit(8) aligned;
declare (x, y) unsigned fixed binary (8);
do x = 0 upthru hbound(screen,2);
do y = 0 upthru hbound(screen,1);
b = unspec(x) ^ unspec(y);
screen(x,y) = b;
end;
end;
call writeppm(screen);
end munch;
Processing
Renders grayscale image, the larger the window the more the squares will repeat along the main diagonal from top left to bottom right.
//Aamrun, 26th June 2022
size(1200,720);
loadPixels();
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
pixels[j + i*width] = color(i^j);
}
}
updatePixels();
Prolog
Works with SWI-Prolog and his GUI XPCE.
xor_pattern :-
new(D, window('XOR Pattern')),
send(D, size, size(512,512)),
new(Img, image(@nil, width := 512, height := 512 , kind := pixmap)),
forall(between(0,511, I),
( forall(between(0,511, J),
( V is I xor J,
R is (V * 1024) mod 65536,
G is (65536 - V * 1024) mod 65536,
( V mod 2 =:= 0
-> B is (V * 4096) mod 65536
; B is (65536 - (V * 4096)) mod 65536),
send(Img, pixel(I, J, colour(@default, R, G, B))))))),
new(Bmp, bitmap(Img)),
send(D, display, Bmp, point(0,0)),
send(D, open).
Python
import Image, ImageDraw
image = Image.new("RGB", (256, 256))
drawingTool = ImageDraw.Draw(image)
for x in range(256):
for y in range(256):
drawingTool.point((x, y), (0, x^y, 0))
del drawingTool
image.save("xorpic.png", "PNG")
Racket
#lang racket
(require racket/draw)
(define palette (for/vector ([x 256]) (make-object color% 0 0 x)))
(define bm (make-object bitmap% 256 256))
(define dc (new bitmap-dc% [bitmap bm]))
(for* ([x 256] [y 256])
(define c (vector-ref palette (bitwise-xor x y)))
(send dc set-pixel x y c))
bm
Raku
(formerly Perl 6)
Here's one simple way:
my $ppm = open("munching0.ppm", :w) orelse .die;
$ppm.print(q :to 'EOT');
P3
256 256
255
EOT
for 0 .. 255 -> $row {
for 0 .. 255 -> $col {
my $color = $row +^ $col;
$ppm.print("0 $color 0 ");
}
$ppm.say();
}
$ppm.close();
Another way:
my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b },
map -> $x { floor ($x/256) ** 3 * 256 },
(flat (0...255) Z
(255...0) Z
flat (0,2...254),(254,252...0));
my $PPM = open "munching1.ppm", :w orelse .die;
$PPM.print: qq:to/EOH/;
P6
# munching.pgm
256 256
255
EOH
$PPM.write: @colors[$_] for ^256 X+^ ^256;
$PPM.close;
REXX
/*REXX program renders a graphical pattern by coloring each pixel with x XOR y */
/*───────────────────────────────────────── from an arbitrary constructed color table. */
rows= 2 /*the number of rows in the color table*/
cols= 5 /* " " " cols " " " " */
do row =0 for rows*3 /*construct a color table, size 25x50.*/
do col=0 for cols*3
$= (row+col) // 255
@.row.col= x2b( d2x($+0, 2) ) ||, /*ensure $ is converted──►2 hex nibbles*/
x2b( d2x($+1, 2) ) ||,
x2b( d2x($+2, 2) )
end /*col*/ /* [↑] construct a three-byte pixel. */
end /*row*/
do x=0 for cols /*create a graphical pattern with XORs.*/
do y=0 for rows
@.x.y= bitxor(@.x, @.y) /*renders 3 bytes (a pixel) at a time. */
end /*y*/
end /*x*/ /*stick a fork in it, we're all done. */
Must be converted to an image with a separate program.
Ring
# Project : Munching squares
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Archimedean spiral")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
w = 100
for x = 0 to w
for y = 0 to w
b = (x ^ y)
color = new qcolor()
color.setrgb(255 -b,b /2,b,255)
pen.setcolor(color)
setpen(pen)
drawpoint(x,w -y -1)
next
next
endpaint()
}
label1 { setpicture(p1) show() }
return
Output:
https://www.dropbox.com/s/wvdqyihtxralviz/Squares.jpg?dl=0
Ruby
Uses Raster graphics operations/Ruby
load 'raster_graphics.rb'
class Pixmap
def self.xor_pattern(width, height, rgb1, rgb2)
# create colour table
size = 256
colours = Array.new(size) do |i|
RGBColour.new(
(rgb1.red + (rgb2.red - rgb1.red) * i / size),
(rgb1.green + (rgb2.green - rgb1.green) * i / size),
(rgb1.blue + (rgb2.blue - rgb1.blue) * i / size),
)
end
# create the image
pixmap = new(width, height)
pixmap.each_pixel do |x, y|
pixmap[x,y] = colours[(x^y)%size]
end
pixmap
end
end
img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW)
img.save_as_png('xorpattern.png')
Rust
extern crate image;
use image::{ImageBuffer, Pixel, Rgb};
fn main() {
let mut img = ImageBuffer::new(256, 256);
for x in 0..256 {
for y in 0..256 {
let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0);
img.put_pixel(x, y, pixel);
}
}
let _ = img.save("output.png");
}
Scala
Scala Swing
import scala.swing.Swing.pair2Dimension
import scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication}
object XorPattern extends SimpleSwingApplication {
def top = new MainFrame {
preferredSize = (300, 300)
title = "Rosetta Code >>> Task: Munching squares | Language: Scala"
contents = new Panel {
protected override def paintComponent(g: Graphics2D) = {
super.paintComponent(g)
for {
y <- 0 until size.getHeight.toInt
x <- 0 until size.getWidth.toInt
} {
g.setColor(new Color(0, (x ^ y) % 256, 0))
g.drawLine(x, y, x, y)
}
}
}
centerOnScreen()
}
}
Sidef
require('Imager')
var img = %O<Imager>.new(xsize => 256, ysize => 256)
for y=(^256), x=(^256) {
var rgb = [(255 - x - y).abs, (255-x)^y, x^(255-y)]
img.setpixel(x => x, y => y, color => rgb)
}
img.write(file => 'xor.png')
Output image: Munching squares
Tcl
package require Tk
proc xorImage {img table} {
set data {}
set h [image height $img]
set w [image width $img]
for {set y 0} {$y < $h} {incr y} {
set row {}
for {set x 0} {$x < $w} {incr x} {
lappend row [lindex $table [expr {($x^$y) % [llength $table]}]]
}
lappend data $row
}
$img put $data
}
proc inRange {i f t} {expr {$f + ($t-$f)*$i/255}}
proc mkTable {rf rt gf gt bf bt} {
for {set i 0} {$i < 256} {incr i} {
lappend tbl [format "#%02x%02x%02x" \
[inRange $i $rf $rt] [inRange $i $gf $gt] [inRange $i $bf $bt]]
}
return $tbl
}
set img [image create photo -width 512 -height 512]
xorImage $img [mkTable 0 255 64 192 255 0]
pack [label .l -image $img]
Wren
import "graphics" for Canvas, Color
import "dome" for Window
class Game {
static init() {
Window.title = "Munching squares"
var w = 512
var h = 512
Window.resize(w, h)
Canvas.resize(w, h)
for (x in 0...w) {
for (y in 0...h) {
var c = (x ^ y) & 255
Canvas.pset(x, y, Color.rgb(255-c, (c/2).floor, c))
}
}
}
static update() {}
static draw(alpha) {}
}
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y;
[SetVid($101); \set 640x480 graphics with 8-bit color
port($3C8):= 0; \set color registers with beautiful shades
for X:= 0 to 256-1 do
[port($3C9):= X>>1; \red
port($3C9):= X>>3; \green
port($3C9):= X; \blue
];
for Y:= 0 to 256-1 do \"color table" is array of 256 registers
for X:= 0 to 256-1 do
Point(X, Y, X|Y); \"|" = XOR, not OR which is "!"
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]
- Output:
zkl
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
For a kaleidoscopic image, play with coolness.
fcn muncher{
bitmap:=PPM(256,256);
coolness:=(1).random(0x10000); // 55379, 18180, 40, 51950, 57619, 43514, 65465
foreach y,x in ([0 .. 255],[0 .. 255]){
b:=x.bitXor(y); // shades of blue
// rgb:=b*coolness; // kaleidoscopic image
// rgb:=(b*coolness + b)*coolness + b; // more coolness
rgb:=(b*0x10000 + b)*0x10000 + b; // copy ADA image
bitmap[x,y]=rgb;
}
bitmap.write(File("foo.ppm","wb"));
}();
For a cheap slide show (on Linux):
while(1){ muncher(); Atomic.sleep(3); }
run ImageViewer on foo.ppm and watch it [auto] update as the image changes.
- Output:
- Programming Tasks
- Raster graphics operations
- Graphics algorithms
- GUISS/Omit
- Lilypond/Omit
- Action!
- Ada
- GtkAda
- ATS
- AWK
- BASIC
- Applesoft BASIC
- BBC BASIC
- Commodore BASIC
- Craft Basic
- FreeBASIC
- Liberty BASIC
- Microsoft Small Basic
- PureBasic
- QBasic
- RapidQ
- Run BASIC
- TI-83 BASIC
- Visual Basic .NET
- Yabasic
- Befunge
- BQN
- Burlesque
- C
- C sharp
- C++
- Clojure
- Evaldraw
- D
- Delphi
- Windows,Types,ExtCtrls,Graphics
- EasyLang
- EchoLisp
- Factor
- Fōrmulæ
- GLSL
- Gnuplot
- Go
- Haskell
- Icon
- Unicon
- Icon Programming Library
- J
- Java
- Swing
- Jq
- Julia
- Kotlin
- Lua
- Mathematica
- Wolfram Language
- MATLAB
- MiniScript
- Nim
- Imageman
- OCaml
- Octave
- Perl
- Phix
- Phix/pGUI
- Phix/online
- PHP
- PL/I
- Processing
- Prolog
- Python
- PIL
- Racket
- Raku
- REXX
- Ring
- Ruby
- Rust
- Scala
- Org.scala-lang.modules scala-swing
- Sidef
- Tcl
- Tk
- Wren
- DOME
- XPL0
- Zkl