Chaos game: Difference between revisions

66,504 bytes added ,  1 month ago
m (→‎{{header|REXX}}: re-aligned statements and added whitespace., added wording to the output section about a BIF.)
 
(85 intermediate revisions by 33 users not shown)
Line 1:
{{task}}
 
The [[wp:Chaos_game|Chaos Game]] is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
 
<br><br>
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
 
 
;Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. &nbsp; Add a starting point at random (preferably inside the triangle). &nbsp; Then add the next point halfway between the starting point and one of the reference points. &nbsp; This reference point is chosen at random.
 
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
 
<br><br>
 
;See also
* [http://www.geoastro.de/ChaosSpiel/ChaosEnglish.html The Game of Chaos]
<br><br>
=={{header|8086 Assembly}}==
{{trans|BASIC}}
 
This program will run on a PC with CGA-compatible graphics. It will keep running until a key is pressed.
 
<syntaxhighlight lang="asm"> cpu 8086
bits 16
vmode: equ 0Fh ; Get current video mode
time: equ 2Ch ; Get current system time
CGALO: equ 4 ; Low-res (4-color) CGA mode
MDA: equ 7 ; MDA text mode
section .text
org 100h
mov ah,vmode ; Get current video mode
int 10h
cmp al,MDA ; If MDA mode, no CGA supported, so stop
jne gr_ok
ret
gr_ok: push ax ; Store old video mode on stack
mov ax,CGALO ; Switch to low-resolution CGA mode
int 10h
mov ah,time ; Get system time
int 21h
mov di,cx ; Store as RNG seed
mov bp,dx
genX: call random ; Generate random X coordinate
cmp al,200
jae genX
mov dh,al ; DH = X
genY: call random ; Generate random Y coordinate
cmp al,173
jae genY
mov dl,al ; DL = Y
mloop: mov ah,1 ; Is a key pressed?
int 16h
jz point ; If not, calculate another point
pop ax ; But if so, restore the old video mode
cbw
int 10h
ret ; And quit
point: call random ; Generate random direction
and al,3
cmp al,3
je point
mov ah,al ; Keep direction (for color later)
dec al ; Select direction
jz d2
dec al
jz d3
shr dh,1 ; X /= 2
shr dl,1 ; Y /= 2
jmp plot
d2: mov cl,ah ; Keep color in CL
mov si,100 ; X = 100+(100-X)/2
xor ax,ax ; (doing intermediate math in 16 bits)
mov al,dh
neg ax
add ax,si
shr ax,1
add ax,si
mov dh,al
mov si,173 ; Y = 173-(173-Y)/2
xor ax,ax ; (doing intermediate math in 16 bits)
mov al,dl
neg ax
add ax,si
shr ax,1
neg ax
add ax,si
mov dl,al
mov ah,cl ; Restore color
jmp plot
d3: mov cl,ah ; Keep color
mov si,200 ; X = 200-(200-X)/2
xor ax,ax ; (doing intermediate math in 16 bits)
mov al,dh
neg ax
add ax,si
shr ax,1
neg ax
add ax,si
mov dh,al
mov ah,cl ; Restore color
shr dl,1 ; Y /= 2
plot: mov cl,dl ; There's a plot function in the BIOS, but it's
clc ; behind an INT and needs all the registers,
rcr cl,1 ; so we'll do it by hand.
sbb bh,bh ; The even rows are at B800:NNNN, odd at BA00,
xor bl,bl ; CL (Y coord) is divided by two, and if odd
and bh,2 ; we add 2(00) to B8(00) to get the right
add bh,0B8h ; segment.
mov ds,bx ; We can safely stick it in DS since we're not
xor bx,bx ; using any RAM otherwise. 80 bytes per line,
mov bl,cl ; so BX=Y * 80,
xor ch,ch
shl bx,1
shl bx,1
add bx,cx
mov cl,4
shl bx,cl
mov cl,dh ; and 4 pixels per byte, so BX += Y/4
shr cl,1
shr cl,1
add bx,cx
inc ah ; Add 1 to direction to get 1 of 3 colors
mov ch,dh ; See which pixel within the byte we're
and ch,3 ; looking at
mov cl,3 ; Leftmost pixel is in highest bits
sub cl,ch
shl cl,1 ; Pixels are 2 bits wide
shl ah,cl ; Shift AH into place
or [bx],ah ; Set the pixel in video memory
jmp mloop ; Next pixel
random: xchg bx,bp ; Load RNG state into byte-addressable
xchg cx,di ; registers.
inc bl ; X++
xor bh,ch ; A ^= C
xor bh,bl ; A ^= X
add cl,bh ; B += A
mov al,cl ; C' = B
shr al,1 ; C' >>= 1
add al,ch ; C' += C
xor al,bh ; C' ^= A
mov ch,al ; C = C'
xchg bx,bp ; Restore the registers
xchg cx,di
ret</syntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
INT x,w=[220],h=[190]
BYTE y,i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
 
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
 
x=Rand(w)
y=Rand(h)
DO
i=Rand(3)
IF i=0 THEN
x==/2
y==/2
ELSEIF i=1 THEN
x=w/2+(w/2-x)/2
y=h-(h-y)/2
ELSE
x=w-(w-x)/2
y=y/2
FI
Plot((320-w)/2+x,191-y)
UNTIL CH#$FF
OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Chaos_game.png Screenshot from Atari 8-bit computer]
=={{header|Amazing Hopper}}==
{{trans|BASIC256}}
<p>Considerar que Hopper no usa modos gráficos, y solo imprime el caracter ascii 219 achicando el tamaño de caracteres de la terminal, dado la ilusión de un modo gráfico "arcaico".</p>
<syntaxhighlight lang="amazing hopper">
/* Chaos game - JAMBO hopper */
 
#include <jambo.h>
 
#define LIMITE 50000
 
Main
ancho = 700, alto = 150
x=0,y=0,color=0
vertice=0,
c=0, Let( c := Utf8(Chr(219)))
Let(x := Int(Rand(ancho)))
Let(y := Int(Rand(alto)))
 
mid ancho=0, Let( mid ancho:= Div(ancho,2))
 
Cls
i=LIMITE
Void(pixeles)
 
Loop
Ceil(Rand(3)), On gosub( EQ1, EQ2, EQ3 )
 
Set( Int(y), Int(x), color),Apndrow(pixeles)
--i
Back if (i) is not zero
 
Canvas-term
Cls
i=1
Iterator(++i, Leq(i,LIMITE), Colorfore([i,3]Get(pixeles)), \
Locate( [i,1]Get(pixeles), [i,2]Get(pixeles) ), Print(c) )
Pause
 
End
Subrutines
EQ1:
Let(x := Div(x, 2))
Let(y := Div(y, 2))
Let(color:=9), Return
 
EQ2:
Let(x := Add( mid ancho, Div(Sub(mid ancho, x), 2) ) )
Let(y := Sub( alto, Div( Sub(alto, y), 2 )))
Let(color:=10), Return
EQ3:
Let(x := Sub(ancho, Div( Sub(ancho, x), 2)))
Let(y := Div(y, 2))
Let(color:=4), Return
 
</syntaxhighlight>
{{out}}
[[File:Chaos Game - salida_juego.png]]
 
=={{header|BASIC}}==
This should require minimal adaptation to work with any of the older Microsoft-style BASICs. Users of other dialects will need to replace lines <tt>10</tt> and <tt>150</tt> with the appropriate statements to select a graphics output mode (if necessary) and to plot a pixel at <tt>x,y</tt> in colour <tt>v</tt>; they should also add <tt>LET</tt> throughout and <tt>170 END</tt> if their dialects require those things.
<langsyntaxhighlight lang="basic">10 SCREEN 1
20 X = INT(RND(0) * 200)
30 Y = INT(RND(0) * 173)
Line 31 ⟶ 248:
140 Y = Y/2
150 PSET X,Y,V
160 NEXT I</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
Adapted from the code given above.
<langsyntaxhighlight lang="basic">10 HGR2
20 X = INT(RND(1) * 200)
30 Y = INT(RND(1) * 173)
Line 50 ⟶ 268:
150 HCOLOR=V+4
160 HPLOT X,Y
170 NEXT I</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">#Chaos game
 
ancho = 500 : alto = 300
x = Int(Rand * ancho)
y = Int(Rand * alto)
 
Clg
FastGraphics
Graphsize ancho , alto
 
For iteracion = 1 To 30000
vertice = Int(Rand * 3) + 1
Begin Case
Case vertice = 1
x = x / 2
y = y / 2
Color red
Case vertice = 2
x = (ancho/2) + ((ancho/2)-x) / 2
y = alto - (alto-y) / 2
Color green
Case vertice = 3
x = ancho - (ancho-x) / 2
y = y / 2
Color blue
End Case
#Pset (x,y),vertice
Plot (x,y)
Next iteracion
Refresh
ImgSave "chaos_game.jpg", "jpg"
End</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">100 REM Chaos game
110 CLS
120 SCREEN 7 '320x200 EGA Color
130 X = INT(RND(1) * 200)
140 Y = INT(RND(1) * 173)
150 FOR I=1 TO 20000
160 V = INT(RND(1) * 3) + 1
170 ON V GOTO 180,210,240
180 X = X/2
190 Y = Y/2
200 GOTO 260
210 X = 100 + (100-X)/2
220 Y = 173 - (173-Y)/2
230 GOTO 260
240 X = 200 - (200-X)/2
250 Y = Y/2
260 PSET(X,Y),V
270 NEXT I
280 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "ChaosGam.bas"
110 RANDOMIZE
120 GRAPHICS HIRES 4
130 LET X=RND(800):LET Y=RND(600)
140 FOR I=1 TO 20000
150 LET VERTEX=RND(3)
160 SELECT CASE VERTEX
170 CASE 0
180 LET X=X/2
190 LET Y=Y/2
200 CASE 1
210 LET X=400+(400-X)/2
220 LET Y=600-(600-Y)/2
230 CASE 2
240 LET X=800-(800-X)/2
250 LET Y=Y/2
260 END SELECT
270 SET INK VERTEX+1
280 PLOT X,Y
290 NEXT</syntaxhighlight>
 
==={{header|Locomotive Basic}}===
Adapted from the generic BASIC version. In [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic] this program completes in less than a second. But on a real CPC (or equivalent emulator), the same program takes over six minutes to run. So using CPCBasic is strongly advised. On CPCBasic, one can also use "mode 3" instead of mode 1 in line 10 and increase iterations to e.g. 2000000 in line 40, resulting in a higher-resolution image.
<syntaxhighlight lang="locobasic">10 mode 1:randomize time:defint a-z
20 x = 640 * rnd
30 y = 400 * rnd
40 for i=1 to 20000
50 v = rnd * 2 + 1
60 on v goto 70,100,130
70 x = x/2
80 y = y/2
90 goto 150
100 x = 320 + (320-x)/2
110 y = 400 - (400-y)/2
120 goto 150
130 x = 640 - (640-x)/2
140 y = y/2
150 plot x,y,v
160 next i</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">100 REM Chaos game
110 CLS
120 SCREEN 2
130 X = INT(RND(1) * 256)
140 Y = INT(RND(1) * 192)
150 FOR I=1 TO 20000
160 V = INT(RND(1) * 3) + 1
170 ON V GOTO 180,220,260
180 X = X/2
190 Y = Y/2
200 V = 8 'red
210 GOTO 290
220 X = 128 + (128-X)/2
230 Y = 192 - (192-Y)/2
240 V = 3 'green
250 GOTO 290
260 X = 256 - (256-X)/2
270 Y = Y/2
280 V = 7 'blue
290 PSET(X,Y),V
300 NEXT I
310 END</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 56 ⟶ 397:
 
Note that ZX81 BASIC does not have an explicit computed <code>GOTO</code>; we can, however, actually compute the value of an expression and then <code>GOTO</code> it as a line number.
<langsyntaxhighlight lang="basic"> 10 LET X=RND*46
20 LET Y=RND*40
30 FOR I=1 TO 5000
Line 70 ⟶ 411:
130 LET Y=Y/2
140 PLOT X,42-Y
150 NEXT I</langsyntaxhighlight>
{{out}}
Screenshot [http://www.edmundgriffiths.com/zx81chaosgame.jpg here]. As with most ZX81 graphics, you can obtain the very best results by making it quite small and looking at it from a long way away.
Line 76 ⟶ 417:
==={{header|ZX Spectrum Basic}}===
The final <code>INK</code> statement sets the foreground colour back to black.
<langsyntaxhighlight lang="basic"> 10 LET x=RND*200
20 LET y=RND*173
30 FOR i=1 TO 20000
Line 93 ⟶ 434:
160 PLOT x,y
170 NEXT i
180 INK 0</langsyntaxhighlight>
 
=={{header|C}}==
 
Interactive code which asks the side length of the starting triangle and number of iterations as inputs, a larger number of iterations produces a more accurate approximation of the Sierpinski fractal. Requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library.
 
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<stdlib.h>
Line 151 ⟶ 491:
return 0;
}</langsyntaxhighlight>
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">using System.Diagnostics;
using System.Drawing;
 
namespace RosettaChaosGame
{
class Program
{
static void Main(string[] args)
{
var bm = new Bitmap(600, 600);
 
var referencePoints = new Point[] {
new Point(0, 600),
new Point(600, 600),
new Point(300, 81)
};
var r = new System.Random();
var p = new Point(r.Next(600), r.Next(600));
for (int count = 0; count < 10000; count++)
{
bm.SetPixel(p.X, p.Y, Color.Magenta);
int i = r.Next(3);
p.X = (p.X + referencePoints[i].X) / 2;
p.Y = (p.Y + referencePoints[i].Y) / 2;
}
const string filename = "Chaos Game.png";
bm.Save(filename);
Process.Start(filename);
}
}
}</syntaxhighlight>
=={{header|C++}}==
This program will generate the Sierpinski Triangle and save it to your hard drive.
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <ctime>
Line 304 ⟶ 676:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
 
<lang csharp>using System.Diagnostics;
using System.Drawing;
 
namespace RosettaChaosGame
{
class Program
{
static void Main(string[] args)
{
var bm = new Bitmap(600, 600);
 
var referencePoints = new Point[] {
new Point(0, 600),
new Point(600, 600),
new Point(300, 81)
};
var r = new System.Random();
var p = new Point(r.Next(600), r.Next(600));
for (int count = 0; count < 10000; count++)
{
bm.SetPixel(p.X, p.Y, Color.Magenta);
int i = r.Next(3);
p.X = (p.X + referencePoints[i].X) / 2;
p.Y = (p.Y + referencePoints[i].Y) / 2;
}
const string filename = "Chaos Game.png";
bm.Save(filename);
Process.Start(filename);
}
}
}</lang>
 
=={{header|Common Lisp}}==
{{libheader|opticl}}
<langsyntaxhighlight lang="lisp">(defpackage #:chaos
(:use #:cl
#:opticl))
Line 370 ⟶ 707:
(setf (pixel image (first point) (second point))
(values 255 0 0)))
(write-png-file "chaos.png" image)))</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
{{libheader| System.Classes}}
{{libheader| Vcl.Graphics}}
{{libheader| Vcl.Forms}}
{{libheader| Vcl.ExtCtrls}}
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">
unit main;
 
interface
 
uses
Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls,
System.Generics.Collections;
 
type
TColoredPoint = record
P: TPoint;
Index: Integer;
constructor Create(PX, PY: Integer; ColorIndex: Integer);
end;
 
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
Buffer: TBitmap;
Points: array[0..2] of TPoint;
Stack: TStack<TColoredPoint>;
Tick: TTimer;
procedure Run(Sender: TObject);
procedure AddPoint;
function HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint;
{ Private declarations }
public
{ Public declarations }
end;
 
const
Colors: array[0..2] of Tcolor = (clRed, clGreen, clBlue);
 
var
Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
{ TColoredPoint }
 
constructor TColoredPoint.Create(PX, PY: Integer; ColorIndex: Integer);
begin
self.P := Tpoint.Create(PX, PY);
self.Index := ColorIndex;
end;
 
{ TForm1 }
 
procedure TForm1.FormCreate(Sender: TObject);
begin
Buffer := TBitmap.Create;
Stack := TStack<TColoredPoint>.Create;
Tick := TTimer.Create(nil);
Caption := 'Chaos Game';
 
DoubleBuffered := True;
 
ClientHeight := 640;
ClientWidth := 640;
var margin := 60;
var size := ClientWidth - 2 * margin;
 
Points[0] := TPoint.Create(ClientWidth div 2, margin);
Points[1] := TPoint.Create(margin, size);
Points[2] := TPoint.Create(margin + size, size);
 
Stack.Push(TColoredPoint.Create(-1, -1, Colors[0]));
 
Tick.Interval := 10;
Tick.OnTimer := Run;
end;
 
function TForm1.HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint;
begin
Result := TColoredPoint.Create((a.p.X + b.x) div 2, (a.p.y + b.y) div 2, index);
end;
 
procedure TForm1.AddPoint;
begin
var colorIndex := Random(3);
var p1 := Stack.Peek;
var p2 := Points[colorIndex];
Stack.Push(HalfWayPoint(p1, p2, colorIndex));
end;
 
procedure TForm1.Run(Sender: TObject);
begin
if Stack.Count < 50000 then
begin
for var i := 0 to 999 do
AddPoint;
Invalidate;
end;
end;
 
procedure TForm1.FormDestroy(Sender: TObject);
begin
Tick.Free;
Buffer.Free;
Stack.Free;
end;
 
procedure TForm1.FormPaint(Sender: TObject);
begin
for var p in Stack do
begin
with Canvas do
begin
Pen.Color := Colors[p.Index];
Brush.Color := Colors[p.Index];
Brush.Style := bsSolid;
Ellipse(p.p.X - 1, p.p.y - 1, p.p.X + 1, p.p.y + 1);
end;
end;
end;
end.</syntaxhighlight>
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=Zc1BCoMwEIXhfU7xL20FO1aKuMhJQhbFKgrVQAiS3L5MkW66GJj5eMwbwztEBhGTncfiEFoRHoI35aSenqHDm4wlPvdX2GaumjPlT+YQWbG0pKAgIgbYwjGRKbrHaUxI0+novZxP1j3xBe2pMjXZLf7CjbuqdlWFmvLTxnwA Run it]
 
<syntaxhighlight>
color 900
x[] = [ 0 100 50 ]
y[] = [ 7 7 93 ]
x = randomf * 100
y = randomf * 100
for i = 1 to 100000
move x y
rect 0.3 0.3
h = randint 3
x = (x + x[h]) / 2
y = (y + y[h]) / 2
.
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">; Chaos game
 
(defun make-array (size)
"Create an empty array with size*size elements."
(setq m-array (make-vector size nil))
(dotimes (i size)
(setf (aref m-array i) (make-vector size 0)))
m-array)
 
(defun chaos-next (p)
"Return the next coordinates."
(let* ((points (list (cons 1 0) (cons -1 0) (cons 0 (sqrt 3))))
(v (elt points (random 3)))
(x (car p))
(y (cdr p))
(x2 (car v))
(y2 (cdr v)))
(setq nx (/ (+ x x2) 2.0))
(setq ny (/ (+ y y2) 2.0))
(cons nx ny)))
 
(defun chaos-lines (arr size)
"Turn array into a string for XPM conversion."
(setq all "")
(dotimes (y size)
(setq line "")
(dotimes (x size)
(setq line (concat line (if (= (elt (elt arr y) x) 1) "*" "."))))
(setq all (concat all "\"" line "\",\n")))
all)
 
(defun chaos-show (arr size)
"Convert size*size array to XPM image and show it."
(insert-image (create-image (concat (format "/* XPM */
static char * chaos[] = {
\"%i %i 2 1\",
\". c #000000\",
\"* c #00ff00\"," size size)
(chaos-lines arr size) "};") 'xpm t)))
 
(defun chaos (size scale max-iter)
"Play the chaos game."
(let ((arr (make-array size))
(p (cons 0 0)))
(dotimes (it max-iter)
(setq p (chaos-next p))
(setq x (round (+ (/ size 2) (* scale (car p)))))
(setq y (round (+ (- size 10) (* -1 scale (cdr p)))))
(setf (elt (elt arr y) x) 1))
(chaos-show arr size)))
 
(chaos 400 180 50000) </syntaxhighlight>
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">
open System.Windows.Forms
open System.Drawing
open System
 
let sz = 300
let polygon = [Point(sz/2, int (float sz*(1.0-sin(Math.PI/3.0)))); Point(0, sz-1); Point(sz-1, sz-1)]
 
let bmp = new Bitmap(sz, sz)
let paint (p: Point) = bmp.SetPixel(p.X, p.Y, Color.Black)
 
let random = Random()
let seed = Point(int (random.NextDouble() * float sz), int (random.NextDouble() * float sz))
let midpoint (p1: Point) (p2: Point) = Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2)
let randomVertex() = polygon.[random.Next(polygon.Length)]
let step p _ =
paint p
midpoint p (randomVertex())
Seq.init 100000 id |> Seq.fold step seed
 
let f = new Form()
f.ClientSize <- bmp.Size
f.Paint.Add (fun args -> args.Graphics.DrawImage(bmp, Point(0, 0)))
f.Show()
</syntaxhighlight>
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
<br>
<syntaxhighlight lang="forth">#! /usr/bin/gforth
\ Chaos Game
 
require random.fs
 
\ initialize the random number generator with a time-dependent seed
utime drop seed !
 
\ parses a number from a string
: parse-number ( -- n )
s>number? invert throw drop
;
 
 
\ parse the width of the triangle, the number of steps and the output filename from the command-line
 
." width: " next-arg parse-number dup . cr CONSTANT WIDTH
." steps: " next-arg parse-number dup . cr CONSTANT STEPS
." output: " next-arg 2dup type cr 2CONSTANT OUT-FILE
 
 
\ height of the triangle: height = sqrt(3) / 2 * width
WIDTH 0 d>f 3e fsqrt f* 2e f/ fround f>d drop CONSTANT HEIGHT \ height of the triangle: height = sqrt(3) / 2 * width
 
 
\ coordinates of the three corners of the triangle
 
0 CONSTANT X1
0 CONSTANT Y1
WIDTH CONSTANT X2
0 CONSTANT Y2
WIDTH 2 / CONSTANT X3
HEIGHT CONSTANT Y3
 
 
\ minimal and maximal x and y coordinates
 
X1 X2 X3 min min CONSTANT XMIN
X1 X2 X3 max max CONSTANT XMAX
Y1 Y2 Y3 min min CONSTANT YMIN
Y1 Y2 Y3 max max CONSTANT YMAX
 
XMAX XMIN - 1+ CONSTANT XSIZE
YMAX YMIN - 1+ CONSTANT YSIZE
 
 
\ initialize array for all possible points
 
XSIZE YSIZE *
dup CREATE ARR cells allot
ARR swap cells erase
 
 
\ address of the cell corresponding to point (x,y)
: addr? ( x y -- addr )
XSIZE * + cells ARR +
;
 
\ scalar product of the 2-vectors
: sp ( x1 y1 x2 y2 -- n )
swap >r * r> rot * +
;
 
\ is the point (x,y) on the left of the ray from (px,py) to (qx,qy)?
: left? ( px py qx qy x y -- f )
{ px py qx qy x y }
py qy -
qx px -
x px -
y py -
sp 0>=
;
 
\ is the point (x,y) in the triangle?
: in-triangle? ( x y -- f )
{ x y }
X1 Y1 X2 Y2 x y left?
X2 Y2 X3 Y3 x y left?
X3 Y3 X1 Y1 x y left?
and and
;
 
\ generates a random number in [a,b]
: random-in-range ( a b -- n )
over - 1+ random +
;
 
\ generates a random point in the triangle
: random-in-triangle ( -- x y )
0 0
BEGIN
2drop
XMIN XMAX random-in-range
YMIN YMAX random-in-range
2dup in-triangle?
UNTIL
;
 
\ finds the middle of to points (px,py) and (qx,qy)
: middle ( px py qx qy -- x y )
swap -rot
+ 2/ -rot
+ 2/ swap
;
 
\ plays the chaos game for a number of steps
: game ( n -- )
random-in-triangle
rot
0 DO
2dup addr? true swap !
3 random CASE
0 OF X1 Y1 ENDOF
1 OF X2 Y2 ENDOF
2 OF X3 Y3 ENDOF
ENDCASE
middle
LOOP
2drop
;
 
\ writes the result in pbm-format
: write-pbm ( -- )
." P1" cr
XSIZE . YSIZE . cr
YMIN 1- YMAX -DO
XMAX 1+ XMIN DO
i j addr? @ IF 1 . ELSE 0 . THEN
LOOP
cr
1 -LOOP
;
 
\ writes the result to a pbm-file
: to-pbm ( c-addr u -- )
w/o create-file throw ['] write-pbm over outfile-execute close-file throw
;
 
\ play the game and save the result
STEPS game OUT-FILE to-pbm
 
bye</syntaxhighlight>
 
{{out}}
playing a million steps on a triangle with base length 1000:
<tt>./chaos-game.fs 1000 1000000 chao-game.pbm</tt>:]
[https://commons.wikimedia.org/wiki/File:Chaos_Game.png]<br>
=={{header|Fortran}}==
This FORTRAN code creates an output file which can be drawn with gnuplot.
<syntaxhighlight lang="fortran">
PROGRAM CHAOS
IMPLICIT NONE
REAL, DIMENSION(3):: KA, KN ! Koordinates old/new
REAL, DIMENSION(3):: DA, DB, DC ! Triangle
INTEGER:: I, Z
INTEGER, PARAMETER:: UT = 17
! Define corners of triangle
DA = (/ 0., 0., 0. /)
DB = (/ 600., 0., 0. /)
DC = (/ 500., 0., 400. /)
! Define starting point
KA = (/ 500., 0., 100. /)
OPEN (UNIT = UT, FILE = 'aus.csv')
DO I=1, 1000000
Z = ZAHL()
WRITE (UT, '(3(F12.6, ";"))') KA
SELECT CASE (Z)
CASE (1)
CALL MITTELP(KA, DA, KN)
CASE (2)
CALL MITTELP(KA, DB, KN)
CASE (3)
CALL MITTELP(KA, DC, KN)
END SELECT
KA = KN
END DO
CLOSE (UT)
CONTAINS
! Calculates center of two points
SUBROUTINE MITTELP(P1, P2, MP)
REAL, INTENT(IN), DIMENSION(3):: P1, P2
REAL, INTENT(OUT), DIMENSION(3):: MP
MP = (P1 + P2) / 2.
END SUBROUTINE MITTELP
! Returns random number
INTEGER FUNCTION ZAHL()
REAL:: ZZ
CALL RANDOM_NUMBER(ZZ)
ZZ = ZZ * 3.
ZAHL = FLOOR(ZZ) + 1
IF (ZAHL .GT. 3) ZAHL = 3
END FUNCTION ZAHL
END PROGRAM CHAOS
</syntaxhighlight>
Gnuplot Code to draw file:
<syntaxhighlight lang="gnuplot">
set terminal jpeg enhanced size 1600,960
set output 'chaos.jpg'
set nokey
set style line 1 lc rgb '#0060ad' lt 1 lw 3 pt 7 ps 0.3
plot 'aus.csv' using 1:3 with points ls 1 notitle
</syntaxhighlight>
=={{header|FreeBASIC}}==
{{trans|BASIC256}}
<syntaxhighlight lang="freebasic">
' Chaos game
Const ancho = 320, alto = 240
Dim As Integer x, y, iteracion, vertice
x = Int(Rnd * ancho)
y = Int(Rnd * alto)
 
Screenres ancho, alto, 8
Cls
 
For iteracion = 1 To 30000
vertice = Int(Rnd * 3) + 1
Select Case vertice
Case 1
x = x / 2
y = y / 2
vertice = 4 'red
Case 2
x = (ancho/2) + ((ancho/2)-x) / 2
y = alto - (alto-y) / 2
vertice = 2 'green
Case 3
x = ancho - (ancho-x) / 2
y = y / 2
vertice = 1 'blue
End Select
Pset (x,y),vertice
Next iteracion
Sleep
End
</syntaxhighlight>
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Chaos_game}}
 
'''Solution'''
 
[[File:Fōrmulæ - Chaos game 04.png]]
 
'''Test case. Sierpiński triangle'''
 
[[File:Fōrmulæ - Chaos game 05.png]]
 
[[File:Fōrmulæ - Chaos game 06.png]]
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn DoIt
long w = 460, h = 400, i, x = rnd(w), y = rnd(h)
for i = 1 to 50000
select ( rnd(3)-1 )
case 1
x = w/2+(w/2-x)/2
y = h-(h-y)/2
pen ,fn ColorRed
case 2
x = w-(w-x)/2
y = y/2
pen ,fn ColorGreen
case else
x = x/2
y = y/2
pen ,fn ColorBlue
end select
line x-0.5,y-0.5,x+0.5,y+0.5
next
end fn
 
window 1, @"Chaos Game", (0,0,460,400)
WindowSetBackgroundColor( 1, fn ColorWhite )
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
[[file:Chaos game FB.png]]
 
=={{header|GML}}==
Create two new objects and rename them to "Game" and "Point" respectively.
 
 
'''"Game" Object Create Event:'''
<syntaxhighlight lang="gml">offset = 32; //Distance from triangle vertices to edges of window
 
//triangle vertex coordinates
x1 = room_width / 2;
y1 = offset;
x2 = room_width - offset;
y2 = room_height - offset;
x3 = offset;
y3 = room_height - offset;
 
//Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step event)
vx = 0;
vy = 0;
 
//Coords of current point
px = random(room_width);
py = random(room_height);
 
//Make sure the point is within the triangle
while(!point_in_triangle(px, py, x1, y1, x2, y2, x3, y3))
{
px = random(room_width);
py = random(room_height);
}
 
vertex = 0; //This determines which vertex coords are chosen
max_iterations = 8000;
step = true; //Used with the interval alarm to change the step speed
step_count = 0;
interval = 1; //Number of frames between each step. 1 = no delay
alarm[0] = interval;</syntaxhighlight>
 
 
'''"Game" Object Step Event:'''
<syntaxhighlight lang="gml">if(step and step_count < max_iterations) //Wait for alarm to finish, or stop completely
{ // if the desired number of iterations is hit
vertex = choose(1, 2, 3);
step = false;
alarm[0] = interval;
switch(vertex)
{
case 1:
vx = x1;
vy = y1;
break;
case 2:
vx = x2;
vy = y2;
break;
case 3:
vx = x3;
vy = y3;
break;
}
 
var dir = point_direction(px, py, vx, vy);
var mid_dist = point_distance(px, py, vx, vy);
var midx = px + lengthdir_x(mid_dist / 2, dir);
var midy = py + lengthdir_y(mid_dist / 2, dir);
instance_create_layer(midx, midy, "Instances", Point);
 
px = midx;
py = midy;
step_count++;
}</syntaxhighlight>
 
 
'''"Game" Object Draw Event:'''
<syntaxhighlight lang="gml">if(step_count < max_iterations)
{
draw_triangle(x1, y1, x2, y2, x3, y3, true);
draw_circle(px, py, 1, false);
draw_line(px, py, vx, vy);
}</syntaxhighlight>
 
 
'''"Game" Object Alarm 0:'''
<syntaxhighlight lang="gml">step = true;
alarm[0] = interval;</syntaxhighlight>
 
 
'''"Point" Object Draw Event:'''
<syntaxhighlight lang="gml">draw_circle(x, y, 5, false);</syntaxhighlight>
=={{header|Gnuplot}}==
{{trans|PARI/GP}}
{{Works with|gnuplot|5.0 (patchlevel 3) and above}}
[[File:ChGS3Gnu1.png|right|thumb|Output ChGS3Gnu1.png]]
 
<syntaxhighlight lang="gnuplot">
## Chaos Game (Sierpinski triangle) 2/16/17 aev
reset
fn="ChGS3Gnu1"; clr='"red"';
ttl="Chaos Game (Sierpinski triangle)"
sz=600; sz1=sz/2; sz2=sz1*sqrt(3);
x=y=xf=yf=v=0;
dfn=fn.".dat"; ofn=fn.".png";
set terminal png font arial 12 size 640,640
set print dfn append
set output ofn
unset border; unset xtics; unset ytics; unset key;
set size square
set title ttl font "Arial:Bold,12"
lim=30000; max=100; x=y=xw=yw=p=0;
randgp(top) = floor(rand(0)*top)
x=randgp(sz); y=randgp(sz2);
do for [i=1:lim] {
v=randgp(3);
if (v==0) {x=x/2; y=y/2}
if (v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2}
if (v==2) {x=sz-(sz-x)/2; y=y/2}
xf=floor(x); yf=floor(y);
if(!(xf<1||xf>sz||yf<1||yf>sz)) {print xf," ",yf};
}
plot dfn using 1:2 with points pt 7 ps 0.5 lc @clr
set output
unset print
</syntaxhighlight>
{{Output}}
<pre>
File: ChGS3Gnu1.png
</pre>
=={{header|Go}}==
This writes a simple GIF animation of the method.
<langsyntaxhighlight Golang="go">package main
 
import (
Line 478 ⟶ 1,453:
}
return err
}</langsyntaxhighlight>
=={{header|Groovy}}==
 
{{libheader|JavaFX}}
=={{header|Gnuplot}}==
{{trans|PARI/GP}}
{{Works with|gnuplot|5.0 (patchlevel 3) and above}}
[[File:ChGS3Gnu1.png|right|thumb|Output ChGS3Gnu1.png]]
 
<syntaxhighlight lang="groovy">import javafx.animation.AnimationTimer
<lang gnuplot>
import javafx.application.Application
## Chaos Game (Sierpinski triangle) 2/16/17 aev
import javafx.scene.Scene
reset
import javafx.scene.layout.Pane
fn="ChGS3Gnu1"; clr='"red"';
import javafx.scene.paint.Color
ttl="Chaos Game (Sierpinski triangle)"
import javafx.scene.shape.Circle
sz=600; sz1=sz/2; sz2=sz1*sqrt(3);
import javafx.stage.Stage
x=y=xf=yf=v=0;
 
dfn=fn.".dat"; ofn=fn.".png";
class ChaosGame extends Application {
set terminal png font arial 12 size 640,640
 
set print dfn append
final randomNumberGenerator = new Random()
set output ofn
unset border; unset xtics; unset ytics; unset key;
set size square
set title ttl font "Arial:Bold,12"
lim=30000; max=100; x=y=xw=yw=p=0;
randgp(top) = floor(rand(0)*top)
x=randgp(sz); y=randgp(sz2);
do for [i=1:lim] {
v=randgp(3);
if (v==0) {x=x/2; y=y/2}
if (v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2}
if (v==2) {x=sz-(sz-x)/2; y=y/2}
xf=floor(x); yf=floor(y);
if(!(xf<1||xf>sz||yf<1||yf>sz)) {print xf," ",yf};
}
plot dfn using 1:2 with points pt 7 ps 0.5 lc @clr
set output
unset print
</lang>
{{Output}}
<pre>
File: ChGS3Gnu1.png
</pre>
 
@Override
void start(Stage primaryStage) {
primaryStage.title = 'Chaos Game'
primaryStage.scene = getScene()
primaryStage.show()
}
 
def getScene() {
def colors = [Color.RED, Color.GREEN, Color.BLUE]
 
final width = 640, height = 640, margin = 60
final size = width - 2 * margin
 
def points = [
new Circle(width / 2, margin, 1, colors[0]),
new Circle(margin, size, 1, colors[1]),
new Circle(margin + size, size, 1, colors[2])
]
 
def pane = new Pane()
pane.style = '-fx-background-color: black;'
points.each {
pane.children.add it
}
 
def currentPoint = new Circle().with {
centerX = randomNumberGenerator.nextInt(size - margin) + margin
centerY = randomNumberGenerator.nextInt(size - margin) + margin
it
}
 
({
 
def newPoint = generatePoint(currentPoint, points, colors)
pane.children.add newPoint
currentPoint = newPoint
 
} as AnimationTimer).start()
 
new Scene(pane, width, height)
}
 
def generatePoint(currentPoint, points, colors) {
def selection = randomNumberGenerator.nextInt 3
new Circle().with {
centerX = (currentPoint.centerX + points[selection].centerX) / 2
centerY = (currentPoint.centerY + points[selection].centerY) / 2
radius = 1
fill = colors[selection]
it
}
}
 
static main(args) {
launch(ChaosGame)
}
}</syntaxhighlight>
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
import Control.Monad.Random (fromList)
 
Line 530 ⟶ 1,538:
gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]
gameOfChaos n transformations x = iterateA (fromList transformations) x
where iterateA f x = scanr ($) x <$> replicateM n f</langsyntaxhighlight>
 
Some transformations:
 
<langsyntaxhighlight lang="haskell">-- the Sierpinsky`s triangle
triangle = [ (mid (0, 0), 1)
, (mid (1, 0), 1)
Line 550 ⟶ 1,558:
dragon = [(f1, 1), (f2, 1)]
where f1 (x,y) = (0.5*x - 0.5*y, 0.5*x + 0.5*y)
f2 (x,y) = (-0.5*x + 0.5*y+1, -0.5*x - 0.5*y)</langsyntaxhighlight>
 
Drawing the result:
<langsyntaxhighlight lang="haskell">import Control.Monad.Random (getRandomR)
import Graphics.Gloss
 
Line 561 ⟶ 1,569:
display window white $ foldMap point pts
where window = InWindow "Game of Chaos" (400,400) (0,0)
point (x,y) = translate (100*x) (100*y) $ circle 0.02 </langsyntaxhighlight>
 
=={{header|J}}==
[[File:j_chaos_game.png|300px|thumb|right]]
<syntaxhighlight lang="j">
<lang j>
Note 'plan, Working in complex plane'
Make an equilateral triangle.
Line 599 ⟶ 1,606:
 
'marker'plot NEW_POINTS
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
[[File:chaos_game.png|300px|thumb|right]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.*;
import java.util.*;
Line 611 ⟶ 1,617:
 
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
 
Line 655 ⟶ 1,661:
stack.add(halfwayPoint(p1, p2, colorIndex));
} catch (EmptyStackException e) {
Systeme.out.printlnprintStackTrace(e);
}
}
Line 692 ⟶ 1,698:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Plots the fractal on an HTML <tt>canvas</tt> element.
<langsyntaxhighlight lang="javascript"><html>
 
<head>
Line 748 ⟶ 1,753:
</body>
 
</html></langsyntaxhighlight>
 
=={{header|Julia}}==
Run in REPL.
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">using Luxor
<lang julia>
using Luxor
width = 1000;
height = 1000;
Drawing(width, height, "./chaos.png");
t = Turtle(0, 0, true, 0, (0., 0., 0.));
 
function chaos()
x = rand(1:width);
width = 1000
y = rand(1:height);
height = 1000
Drawing(width, height, "./chaos.png")
t = Turtle(0, 0, true, 0, (0., 0., 0.))
x = rand(1:width)
y = rand(1:height)
 
for l in 1:30_000
v = rand(1:3);
if v == 1
x /= 2;
y /= 2;
elseif v == 2
x = width/2 + (width/2 - x)/2;
y = height - (height - y)/2;
else
x = width - (width - x)/2;
y = y / 2;
end
Reposition(t, x, height-y)
Circle(t, 3)
end
Reposition(t, x, height-y);
Circle(t, 3);
end
 
finishchaos();
finish()
preview();
preview()
</lang>
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">//Version 1.1.51
 
import java.awt.*
Line 863 ⟶ 1,868:
}
}
}</langsyntaxhighlight>
 
{{output}}
Line 869 ⟶ 1,874:
Same as Java entry
</pre>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to chaosgame :sidelength :iterations
make "width :sidelength
make "height (:sidelength/2 * sqrt 3)
Line 899 ⟶ 1,903:
]
hideturtle
end</langsyntaxhighlight>
 
=={{header|Lua}}==
Needs L&Ouml;VE 2d Engine
<syntaxhighlight lang="lua">
<lang Lua>
math.randomseed( os.time() )
colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}
Line 944 ⟶ 1,947:
love.graphics.draw( canvas )
end
</syntaxhighlight>
</lang>
 
=={{header|MathematicaM2000 Interpreter}}==
{{trans|Locomotive Basic}}
<lang Mathematica>
Old style programming (GOTO, ON GOTO) inside Module. Export bitmap to Clipboard.
 
 
<syntaxhighlight lang="m2000 interpreter">
Module Chaos {
01 Read Ox as integer, Oy as Integer
02 def Screen$
05 cls 0,0 // black background, row for split screen
10 def integer x,y,i,v
20 x = 640 * rnd
30 y = 400 * rnd
40 for i=1 to 20000
50 v = rnd * 2 + 1
60 on v goto 70,100,130
70 x = x/2
80 y = y/2
90 goto 150
100 x = 320 + (320-x)/2
110 y = 400 - (400-y)/2
120 goto 150
130 x = 640 - (640-x)/2
140 y = y/2
150 pset v*2, x*twipsX+Ox,y*twipsY+Oy
160 next i
170 Move Ox, Oy
180 Copy 640*twipsX, 400*twipsY to Screen$
190 Clipboard Screen$
}
Call Chaos 3000, 3000
</syntaxhighlight>
{{output}}
[[File:Chaosgame.png|thumb]]
 
points = 5000;
a = {0, 0};
b = {1, 0};
c = {0.5, 1};
d = {.7, .3};
S = {};
For[i = 1, i < points, i++, t = RandomInteger[2];
If[t == 0, d = Mean[{a, d}],
If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]]
Graphics[Point[S]]
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">chaosGame := proc(numPoints)
local points, i;
randomize();
Line 979 ⟶ 2,003:
plots:-display( seq([plots:-display([seq(point(points[i]), i = 1..j)])], j = 1..numelems(points) ), insequence=true);
end use;
end proc:</langsyntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">points = 5000;
a = {0, 0};
b = {1, 0};
c = {0.5, 1};
d = {.7, .3};
S = {};
For[i = 1, i < points, i++, t = RandomInteger[2];
If[t == 0, d = Mean[{a, d}],
If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]]
Graphics[Point[S]]</syntaxhighlight>
=={{header|Nim}}==
==={{header|Using a game library}}===
{{libheader|rapid}}
The "rapid" library is no longer maintained and this program fails to compile with last available version.
<syntaxhighlight lang="nim">import random
 
import rapid/gfx
 
var
window = initRWindow()
.title("Rosetta Code - Chaos Game")
.open()
surface = window.openGfx()
sierpinski = window.newRCanvas()
points: array[3, Vec2[float]]
 
for i in 0..<3:
points[i] = vec2(cos(PI * 2 / 3 * i.float), sin(PI * 2 / 3 * i.float)) * 300
 
var point = vec2(rand(0.0..surface.width), rand(0.0..surface.height))
 
surface.vsync = false
surface.loop:
draw ctx, step:
let vertex = sample(points)
point = (point + vertex) / 2
ctx.renderTo(sierpinski):
ctx.transform():
ctx.translate(surface.width / 2, surface.height / 2)
ctx.rotate(-PI / 2)
ctx.begin()
ctx.point((point.x, point.y))
ctx.draw(prPoints)
ctx.clear(gray(0))
ctx.begin()
ctx.texture = sierpinski
ctx.rect(0, 0, surface.width, surface.height)
ctx.draw()
ctx.noTexture()
update step:
discard</syntaxhighlight>
 
==={{header|Using SDL}}===
{{libheader|SDL2}}
<syntaxhighlight lang="nim">## needs sdl2 ("nimble install sdl2")
 
import sdl2, random
 
let
max_it = 50000
size = [800, 600]
v = [
[0, 0],
[size[0] - 1, 0],
[size[0] div 2, size[1] - 1]
]
 
discard sdl2.init(INIT_EVERYTHING)
 
var
window: WindowPtr
render: RendererPtr
 
window = createWindow("chaos", 100, 100, cint(size[0]), cint(size[1]), SDL_WINDOW_SHOWN)
render = createRenderer(window, -1, Renderer_Accelerated or
Renderer_PresentVsync or Renderer_TargetTexture)
 
var
evt = sdl2.defaultEvent
runGame = true
it = 0
r: Point
 
r.x = cint(rand(size[0] - 1))
r.y = cint(rand(size[1] - 1))
render.setDrawColor(0, 0, 0)
render.clear
 
while it < max_it:
let vn = rand(2)
r.x = cint((r.x + v[vn][0]) div 2)
r.y = cint((r.y + v[vn][1]) div 2)
if vn == 0:
render.setDrawColor(255, 0, 0)
elif vn == 1:
render.setDrawColor(0, 255, 0)
else:
render.setDrawColor(0, 0, 255)
render.drawPoint(r.x, r.y)
inc it
 
while runGame:
render.present
delay(100)
while pollEvent(evt):
if evt.kind == QuitEvent:
runGame = false
break
 
destroy render
destroy window</syntaxhighlight>
 
==={{header|Writing result into an image}}===
{{libheader|imageman}}
 
<syntaxhighlight lang="nim">import math
import random
 
import imageman
 
const
Width = 400
Height = 400
Margin = 20
 
type Coords = tuple[x, y: float]
 
# The triangle.
const T = [Coords (0.0, 0.0), (1.0, 0.0), (0.5, 0.5 * tan(PI / 3))]
 
#---------------------------------------------------------------------------------------------------
 
func toPoint(v: Coords): Point =
## Convert [0..1] coordinates to image coordinates.
## We have to change scale, then to change position of y-axis.
result = ((Margin + v.x * (Width - 2 * Margin)).toInt,
((Height - Margin) - v.y * (Height - 2 * Margin)).toInt)
 
#---------------------------------------------------------------------------------------------------
 
func side(p, p1, p2: Coords): float =
## Auxiliary function to check if a point is in a triangle.
(p2.y - p1.y) * (p.x - p1.x) + (p1.x - p2.x) * (p.y - p1.y)
 
#---------------------------------------------------------------------------------------------------
 
proc firstPoint(): Coords =
## Choose the first point.
 
while true:
result = (x: rand(1.0), y: rand(1.0))
let b1 = side(result, T[0], T[1]) >= 0
let b2 = side(result, T[1], T[2]) >= 0
let b3 = side(result, T[2], T[0]) >= 0
if b1 == b2 and b2 == b3:
# The point is in the triangle. Keep it.
return
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
const
Iterations = 50_000
Black = ColorRGBU [byte 0, 0, 0]
White = ColorRGBU [byte 255, 255, 255]
PointColor = ColorRGBU [byte 255, 255, 0] # Color for points.
 
# Points in image coordinates.
const
A = T[0].toPoint
B = T[1].toPoint
C = T[2].toPoint
 
 
randomize()
var image = initImage[ColorRGBU](Width, Height)
image.fill(Black)
 
# Draw the triangle.
image.drawLine(A, B, White)
image.drawLine(B, C, White)
image.drawLine(C, A, White)
 
var p = firstPoint()
 
for _ in 1..Iterations:
let pt = p.toPoint
image[pt.x, pt.y] = PointColor
# Find position of next point.
let idx = rand(2)
p = ((p.x + T[idx].x) / 2, (p.y + T[idx].y) / 2)
 
image.savePNG("chaos_game.png", compression = 9)</syntaxhighlight>
=={{header|PARI/GP}}==
Note: Find plotmat() here on RosettaCode Wiki.
{{Works with|PARI/GP|2.9.1 and above}}
[[File:SierpTri1.png|right|thumb|Output SierpTri1.png]]
<langsyntaxhighlight lang="parigp">
\\ Chaos Game (Sierpinski triangle) 2/15/17 aev
pChaosGameS3(size,lim)={
Line 1,001 ⟶ 2,217:
\\ Test:
pChaosGameS3(600,30000); \\ SierpTri1.png
</langsyntaxhighlight>
{{Output}}
<pre>
Line 1,009 ⟶ 2,225:
</pre>
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
<lang Pascal>
program ChaosGame;
 
Line 1,087 ⟶ 2,303:
end.
 
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Imager;
 
my $width = 1000;
Line 1,127 ⟶ 2,342:
}
 
$img->write(file => 'chaos_game_triangle.png');</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2018.10}}
 
<lang perl6>use Image::PNG::Portable;
 
my ($w, $h) = (640, 640);
 
my $png = Image::PNG::Portable.new: :width($w), :height($h);
 
my @vertex = [0, 0], [$w, 0], [$w/2, $h];
 
my @xy = [0,0], [0,0], [0,0], [0,0];
 
# :degree must be equal to or less than @xy elements.
(^1e5).race(:4degree).map: {
my $p = ++$ % +@xy;
@xy[$p] = do given @vertex.pick -> @v { ((@xy[$p] »+« @v) »/» 2)».Int };
$png.set: |@xy[$p], 0, 255, 0;
}
 
$png.write: 'Chaos-game-perl6.png';</lang>
 
=={{header|Phix}}==
Implements five of the fractals on the wikipedia page.
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
<lang Phix>--
You can run this online [http://phix.x10.mx/p2js/chaos.htm here]. Press space to cycle through the five fractals.
-- demo\rosetta\Chaos_game.exw
<!--<syntaxhighlight lang="phix">(phixonline)-->
--
<span style="color: #000080;font-style:italic;">--
include pGUI.e
-- demo\rosetta\Chaos_game.exw
-- ===========================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">TRI</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SQ1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SQ2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SQ3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">PENT</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">descs</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Sierpinsky Triangle"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"Square 1"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"Square 2"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"Square 3"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"Pentagon"</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">mode</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">TRI</span>
<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>
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</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: #004080;">atom</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: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.05</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.05</span><span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.9</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">points</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mode</span><span style="color: #0000FF;"><</span><span style="color: #000000;">SQ1</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: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">}}:</span>
<span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mode</span><span style="color: #0000FF;"><</span><span style="color: #000000;">PENT</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: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">}}</span>
<span style="color: #0000FF;">:{{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</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: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">5</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">last</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1000</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">points</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">=</span><span style="color: #000000;">TRI</span> <span style="color: #008080;">or</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">last</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">nx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ny</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">points</span><span style="color: #0000FF;">[</span><span style="color: #000000;">r</span><span style="color: #0000FF;">]</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: #0000FF;">=</span> <span style="color: #0000FF;">{(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">nx</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ny</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}</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: #004600;">CD_GREY</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SQ2</span>
<span style="color: #008080;">or</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SQ3</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">points</span><span style="color: #0000FF;">))+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SQ3</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">points</span><span style="color: #0000FF;">))+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">last</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Chaos Game (%s)"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">descs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">]})</span>
<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>
<span style="color: #008080;">function</span> <span style="color: #000000;">timer_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: #7060A8;">IupUpdate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_IGNORE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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>
<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>
<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_GRAY</span><span style="color: #0000FF;">)</span>
<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>
<span style="color: #008080;">function</span> <span style="color: #000000;">key_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;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_ESC</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #008000;">' '</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">mode</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">></span><span style="color: #000000;">PENT</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">mode</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">TRI</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRedraw</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<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=640x640"</span><span style="color: #0000FF;">)</span>
<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>
<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>
<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="Chaos Game"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"KEY_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"key_cb"</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>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">timer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupTimer</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"timer_cb"</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">40</span><span style="color: #0000FF;">)</span>
<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>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<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|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Initialize our reference points.
Clear the screen to the lightest gray color.
Play the chaos game.
Refresh the screen.
Wait for the escape key.
Shut down.
 
To play the chaos game:
Ihandle dlg, canvas
Pick a spot within 2 inches of the screen's center.
cdCanvas cddbuffer, cdcanvas
Loop.
Draw the spot.
If a counter is past 20000, exit.
Pick a reference spot.
Find a middle spot of the spot and the reference spot.
Put the middle spot into the spot.
Repeat.
 
To find a middle spot of a spot and another spot:
enum TRI,SQ1,SQ2,SQ3,PENT
Put the spot's x coord plus the other spot's x coord divided by 2 into the middle spot's x coord.
Put the spot's y coord plus the other spot's y coord divided by 2 into the middle spot's y coord.
 
The top spot is a spot.
sequence descs = {"Sierpinsky Triangle",
The left spot is a spot.
"Square 1",
The right spot is a spot.
"Square 2",
"Square 3",
"Pentagon"}
 
To initialize our reference points:
integer mode = TRI
Move up 2-1/2 inches.
 
Put the context's spot into the top spot.
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
Turn right. Turn 1/6 of the way around.
atom {w,h} = IupGetIntInt(canvas, "DRAWSIZE")
Move 5 inches.
atom {x,y} = {w*0.05,h*0.05}
Put the context's spot into the right spot.
{w,h} = {w*0.9,h*0.9}
Turn 1/3 of the way around.
sequence points = iff(mode<SQ1?{{x,y},{x+w/2,y+h},{x+w,y}}:
Move 5 inches.
iff(mode<PENT?{{x,y},{x,y+h},{x+w,y+h},{x+w,y}}
Put the context's spot into the left spot.
:{{x+w/6,y},{x,y+h*2/3},{x+w/2,y+h},{x+w,y+h*2/3},{x+w*5/6,y}}))
cdCanvasActivate(cddbuffer)
integer last = 0
for i=1 to 1000 do
integer r = rand(length(points))
if mode=TRI or r!=last then
atom {nx,ny} = points[r]
{x,y} = {(x+nx)/2,(y+ny)/2}
cdCanvasPixel(cddbuffer, x, y, CD_GREY)
if mode=SQ2
or mode=SQ3 then
r = mod(r,length(points))+1
if mode=SQ3 then
r = mod(r,length(points))+1
end if
end if
last = r
end if
end for
cdCanvasFlush(cddbuffer)
IupSetStrAttribute(dlg, "TITLE", "Chaos Game (%s)", {descs[mode]})
return IUP_DEFAULT
end function
 
function timer_cb(Ihandle /*ih*/)
IupUpdate(canvas)
return IUP_IGNORE
end function
 
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_GRAY)
return IUP_DEFAULT
end function
 
function esc_close(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if
if c=' ' then
mode += 1
if mode>PENT then
mode = TRI
end if
cdCanvasClear(cddbuffer)
IupRedraw(canvas)
end if
return IUP_CONTINUE
end function
 
procedure main()
IupOpen()
 
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "640x640")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
 
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", "Chaos Game")
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
 
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
Ihandle timer = IupTimer(Icallback("timer_cb"), 40)
IupMainLoop()
IupClose()
end procedure
 
main()</lang>
 
To pick a reference spot:
Pick a number between 1 and 3.
If the number is 1, put the top spot into the reference spot.
If the number is 2, put the right spot into the reference spot.
If the number is 3, put the left spot into the reference spot.</syntaxhighlight>
{{out}}
[https://commons.wikimedia.org/wiki/File:Chaos-game.png]
=={{header|Processing}}==
<langsyntaxhighlight lang="java">size(300, 260);
 
background(#ffffff); // white
Line 1,278 ⟶ 2,519:
}
set(x, height-y, colour);
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
 
<syntaxhighlight lang="python">from __future__ import division
 
size(300, 260)
 
background(255) # white
 
x = floor(random(width))
y = floor(random(height))
 
for _ in range(30000):
v = floor(random(3))
if v == 0:
x = x / 2
y = y / 2
colour = color(0, 255, 0) # green
elif v == 1:
x = width / 2 + (width / 2 - x) / 2
y = height - (height - y) / 2
colour = color(255, 0, 0) # red
elif v == 2:
x = width - (width - x) / 2
y = y / 2
colour = color(0, 0, 255) # blue
 
set(x, height - y, colour)</syntaxhighlight>
=={{header|Python}}==
 
<syntaxhighlight lang="python">
<lang Python>
import argparse
import random
Line 1,399 ⟶ 2,667:
main(arg_parser.parse_args())
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ $ "turtleduck.qky" loadfile ] now!
 
[ 2 3 circle ] is dot ( --> )
 
[ 1 fly
-1 4 turn
1 fly
1 4 turn ] is toxy ( n n --> )
 
[ swap 2dup toxy
dot
1 2 turn
toxy
1 2 turn ] is plot ( n n --> )
 
[ 200 random
346 random
over 346 *
over 200 * < if
[ dip [ 400 + ]
692 swap - ] ] is intriangle ( --> n n )
 
[ 3 random
[ table
[ 2 /
dip [ 2 / ] ]
[ 2 /
dip [ 800 + 2 / ] ]
[ 692 + 2 /
dip [ 400 + 2 / ] ] ]
do ] is tovertex ( n n --> )
 
turtle
0 frames
-400 1 fly
1 4 turn
340 1 fly
-1 4 turn
intriangle
10000 times
[ i^ 100 mod 0= if frame
2dup plot
tovertex ]
2drop
1 frames</syntaxhighlight>
 
{{out}}
 
[[File:Quackery chaos game.png|thumb|center]]
 
=={{header|R}}==
Line 1,407 ⟶ 2,726:
{{Works with|R|3.3.1 and above}}
[[File:SierpTriR1.png|right|thumb|Output SierpTriR1.png]]
<syntaxhighlight lang="r">
<lang r>
# Chaos Game (Sierpinski triangle) 2/15/17 aev
# pChaosGameS3(size, lim, clr, fn, ttl)
Line 1,431 ⟶ 2,750:
}
pChaosGameS3(600, 30000, "red", "SierpTriR1", "Sierpinski triangle")
</langsyntaxhighlight>
{{Output}}
<pre>
Line 1,440 ⟶ 2,759:
</pre>
 
'''Alternative code:'''
 
<syntaxhighlight lang="r">
pta = c(1,2)
ptb = c(4,2)
ptc = c(2.5,4)
spt = c(1,2)
 
plot(t(data.frame(pta,ptb,ptc)),
xlab= "", ylab = "", pch = 19, asp =1,
xaxt='n',yaxt='n', ann=FALSE,frame.plot=FALSE)
points(x = spt[1], y = spt[2], col = "blue", pch = 19)
 
ittt = 100000
ptcex = .2
for (i in 1:ittt) {
d = sample(1:6,1,TRUE)
if (d == 1 | d == 2) {
pta1 = spt + ((pta-spt)/2)
points(pta1[1],pta1[2], col = "red", pch = 19, cex = ptcex)
spt=pta1
}
if (d == 3 | d == 4) {
ptb1 = spt + (ptb-spt)/2
points(ptb1[1],ptb1[2], col = "red", pch = 19, cex = ptcex)
spt=ptb1
}
if (d == 5 | d == 6) {
ptc1 = spt + (ptc-spt)/2
points(ptc1[1],ptc1[2], col = "red", pch = 19, cex = ptcex)
spt=ptc1
}
}
</syntaxhighlight>
=={{header|Racket}}==
 
{{trans|Haskell}}
 
<syntaxhighlight lang="racket">#lang racket
 
(require 2htdp/image)
 
(define SIZE 300)
 
(define (game-of-chaos fns WIDTH HEIGHT SIZE
#:offset-x [offset-x 0] #:offset-y [offset-y 0]
#:iters [iters 10000]
#:bg [bg 'white] #:fg [fg 'black])
(define dot (square 1 'solid fg))
(define all-choices (apply + (map first fns)))
(for/fold ([image (empty-scene WIDTH HEIGHT bg)]
[x (random)] [y (random)]
#:result image)
([i (in-range iters)])
(define picked (random all-choices))
(define fn (for/fold ([acc 0] [result #f] #:result result) ([fn (in-list fns)])
#:break (> acc picked)
(values (+ (first fn) acc) (second fn))))
(match-define (list x* y*) (fn x y))
(values (place-image dot (+ offset-x (* SIZE x*)) (+ offset-y (* SIZE y*)) image)
x* y*)))
 
(define (draw-triangle)
(define ((mid a b) x y) (list (/ (+ a x) 2) (/ (+ b y) 2)))
(define (triangle-height x) (* (sqrt 3) 0.5 x))
(game-of-chaos (list (list 1 (mid 0 0))
(list 1 (mid 1 0))
(list 1 (mid 0.5 (triangle-height 1))))
SIZE (triangle-height SIZE) SIZE))
 
(define (draw-fern)
(define (f1 x y) (list 0 (* 0.16 y)))
(define (f2 x y) (list (+ (* 0.85 x) (* 0.04 y)) (+ (* -0.04 x) (* 0.85 y) 1.6)))
(define (f3 x y) (list (+ (* 0.2 x) (* -0.26 y)) (+ (* 0.23 x) (* 0.22 y) 1.6)))
(define (f4 x y) (list (+ (* -0.15 x) (* 0.28 y)) (+ (* 0.26 x) (* 0.24 y) 0.44)))
(game-of-chaos (list (list 1 f1) (list 85 f2) (list 7 f3) (list 7 f4))
(/ SIZE 2) SIZE (/ SIZE 11) #:offset-x 70 #:offset-y 10
#:bg 'black #:fg 'white))
 
(define (draw-dragon)
(game-of-chaos
(list (list 1 (λ (x y) (list (+ (* 0.5 x) (* -0.5 y)) (+ (* 0.5 x) (* 0.5 y)))))
(list 1 (λ (x y) (list (+ (* -0.5 x) (* 0.5 y) 1) (+ (* -0.5 x) (* -0.5 y))))))
SIZE (* 0.8 SIZE) (/ SIZE 1.8) #:offset-x 64 #:offset-y 120))
 
(draw-triangle)
(draw-fern)
(draw-dragon)</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.10}}
 
<syntaxhighlight lang="raku" line>use Image::PNG::Portable;
 
my ($w, $h) = (640, 640);
 
my $png = Image::PNG::Portable.new: :width($w), :height($h);
 
my @vertex = [0, 0], [$w, 0], [$w/2, $h];
 
my @xy = [0,0], [0,0], [0,0], [0,0];
 
# :degree must be equal to or less than @xy elements.
(^1e5).race(:4degree).map: {
my $p = ++$ % +@xy;
@xy[$p] = do given @vertex.pick -> @v { ((@xy[$p] »+« @v) »/» 2)».Int };
$png.set: |@xy[$p], 0, 255, 0;
}
 
$png.write: 'Chaos-game-perl6.png';</syntaxhighlight>
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm draws a Sierpinski triangle by running the choaschaos game with a million points*/
parse value scrsize() with sd sw . /*obtain the depth and width of screen.*/
sw= sw - 2 /*adjust the screen width down by two. */
Line 1,466 ⟶ 2,895:
/* [↑] strip trailing blanks (output).*/
say strip(_, 'T') /*display one row (line) of the image. */
end /*row*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
This REXX program makes use of &nbsp; '''SCRSIZE''' &nbsp; REXX program (or
Line 1,476 ⟶ 2,905:
here &nbsp; ───► &nbsp; [[SCRSIZE.REX]].
 
(Shown at &nbsp; '''<sup>1</sup>/<sub>10</sub>''' &nbsp; size on a &nbsp; <big>426</big>&times;<big>201</big> &nbsp; screen.)
 
'''{{out|output''' |text=&nbsp; when using the following input: &nbsp; &nbsp; <tt> &nbsp; , &nbsp; █ </tt>}}
<pre style="font-size:10%">
Line 1,681 ⟶ 3,110:
</pre>
</b>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Chaos game
 
Line 1,743 ⟶ 3,171:
}
label1 {setpicture(p1) show()}
</syntaxhighlight>
</lang>
* [https://lh3.googleusercontent.com/-xqBO5MB8fpc/Wg05SvwaF9I/AAAAAAAABDA/UGI2goKdDoAR6nbbGZF0YcuwGG6tancvACLcBGAs/s1600/CalmoSoftChaos.jpg Chaos Game (image)]
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">x = int(rnd(0) * 200)
y = int(rnd(0) * 173)
graphic #g, 200,200
Line 1,767 ⟶ 3,194:
#g set(x,y)
next
render #g</langsyntaxhighlight>
 
=={{header|Rust}}==
Dependencies: image, rand
<syntaxhighlight lang ="rust">extern crate image;
extern crate image;
extern crate rand;
 
use stdrand::fsprelude::File*;
use rand::Rng;
use std::f32;
 
fn main() {
let max_iterations = 50_000u3250_000;
let img_side = 800u32800;
let tri_size = 400f32400.0;
 
// Create a new ImgBuf
Line 1,787 ⟶ 3,213:
 
// Create triangle vertices
let mut vertices: [[f32; 2]; 3] = [[0f320.0, 0f320.0]; 3];
for i in 0..vertices.len() {
vertices[i][0] = (img_side as f32 / 2.0)
(img_side as f32 / 2.) + (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).cos();
vertices[i][1] = (img_side as f32 / 2.0)
(img_side as f32 / 2.) + (tri_size / 2.0) * (f32::consts::PI * i as f32 * 2.0 / 3.0).sin();
}
for v in &vertices {
imgbuf.put_pixel(v[0] as u32, v[1] as u32, image::Luma([255u8]));
}
println!("Verticies: {:?}", vertices);
 
// Iterate chaos game
let mut rng = rand::weak_rngthread_rng();
let mut x = img_side as f32 / 2.0;
let mut y = img_side as f32 / 2.0;
for _ in 0..max_iterations {
let choice = rng.gen_range(0, ..vertices.len());
x = (x + vertices[choice][0]) / 2.0;
y = (y + vertices[choice][1]) / 2.0;
 
imgbuf.put_pixel(x as u32, y as u32, image::Luma([255u8]));
Line 1,811 ⟶ 3,238:
 
// Save image
let fout = &mut File::createimgbuf.save("fractal.png").unwrap();
}
image::ImageLuma8(imgbuf).save(fout, image::PNG).unwrap();
</syntaxhighlight>
}</lang>
 
=={{header|Scala}}==
===Java Swing Interoperability===
<langsyntaxhighlight Scalalang="scala">import javax.swing._
import java.awt._
import java.awt.event.ActionEvent
Line 1,885 ⟶ 3,311:
)
 
}</langsyntaxhighlight>
=={{header|Scilab}}==
This script uses complex numbers to represent (x,y) coordinates: real part as x position, and imaginary part as y position.
<syntaxhighlight lang="text">//Input
n_sides = 3;
side_length = 1;
Line 1,932 ⟶ 3,358:
plot2d(real(points),imag(points),0)
plot2d(real(vertices),imag(vertices),-3);
set(gca(),'isoview','on');</langsyntaxhighlight>
{{out}}
It outputs a graphic window and prints on the console the time elapsed during iterations.
<pre>Time: 1.0424433s.</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">require('Imager')
 
var width = 600
Line 1,972 ⟶ 3,397:
}
 
img.write(file => 'chaos_game.png')</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/chaos-game-sidef.png Chaos game]
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
INTEGER U, COLUMNS, LINES;
COLUMNS := 40;
Line 2,015 ⟶ 3,439:
END;
END
</syntaxhighlight>
</lang>
{{in}}
<pre>
Line 2,063 ⟶ 3,487:
XXX
</pre>
=={{header|Uiua}}==
<syntaxhighlight lang="Uiua">
Dim ← 500
Points ← [[50 ⌊÷2Dim] [-50Dim 50] [-50Dim -50Dim]]
# Uncomment to try different square or pentagonal references.
# Points ← [[50 50] [-50Dim 50] [50 -50Dim][-50Dim -50Dim]]
# Points ← [[50 ⌊÷2Dim] [⌊×0.4Dim 50] [⌊×0.4Dim -50Dim] [-50Dim 120] [-50Dim -120Dim]]
Colours ← [[1 0 0] [0 1 0] [0 0 1] [1 1 0] [1 0 1] [0 1 1]]
Rand ← ⌊×⚂
 
↯Dim_Dim_3 0
∧(⍜(⊡|[1 1 1]◌))Points
⊟Rand Dim Rand Dim
⍥(
Rand⧻Points
# Set next point and colour based on target.
⊃(⌊÷2+⊡:Points|⊙◌⊡:Colours)
⟜⍜⊡◌⊙:
)10000
# Uncomment to save image.
# &fwa "UiuaChaosGameSerpinski.png" &ime "png"
 
</syntaxhighlight>
{{out}}
[[File:UiuaChaosGameSerpinski.png|thumb|center|Render using colours associated with each target point.]]
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
{{libheader|Wren-dynamic}}
{{libheader|Wren-seq}}
<syntaxhighlight lang="wren">import "dome" for Window
import "graphics" for Canvas, Color
import "math" for Point
import "random" for Random
import "./dynamic" for Tuple
import "./seq" for Stack
 
var ColoredPoint = Tuple.create("ColoredPoint", ["x", "y", "colorIndex"])
 
class ChaosGame {
construct new(width, height) {
Window.resize(width, height)
Canvas.resize(width, height)
Window.title = "Chaos game"
_width = width
_height = height
_stack = Stack.new()
_points = null
_colors = [Color.red, Color.green, Color.blue]
_r = Random.new()
}
 
init() {
Canvas.cls(Color.white)
var margin = 60
var size = _width - 2 * margin
_points = [
Point.new((_width/2).floor, margin),
Point.new(margin, size),
Point.new(margin + size, size)
]
_stack.push(ColoredPoint.new(-1, -1, 0))
}
 
addPoint() {
var colorIndex = _r.int(3)
var p1 = _stack.peek()
var p2 = _points[colorIndex]
_stack.push(halfwayPoint(p1, p2, colorIndex))
}
 
drawPoints() {
for (cp in _stack) {
var c = _colors[cp.colorIndex]
Canvas.circlefill(cp.x, cp.y, 1, c)
}
}
 
halfwayPoint(a, b, idx) { ColoredPoint.new(((a.x + b.x)/2).floor, ((a.y + b.y)/2).floor, idx) }
 
update() {
if (_stack.count < 50000) {
for (i in 0...25) addPoint()
}
}
 
draw(alpha) {
drawPoints()
}
}
 
var Game = ChaosGame.new(640, 640)</syntaxhighlight>
 
=={{header|X86 Assembly}}==
Sixty bytes handles it.
<syntaxhighlight lang="asm"> 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
4 .386
5 org 100h
6 ;assume: ax=0, bx=0, cx=00FFh, dx=cs, si=0100h
7
8 0100 B0 12 start: mov al, 12h ;set 640x480x4 graphic screen
9 0102 CD 10 int 10h
10
11 0104 69 04 4E35 cha10: imul ax, [si], 4E35h ;generate random number
12 0108 40 inc ax
13 0109 89 04 mov [si], ax ;save seed
14 010B 8A C4 mov al, ah ;use high byte
15 010D D4 03 aam 3 ;al:= rem(al/3)
16 010F 8A D8 mov bl, al
17 0111 02 DB add bl, bl ;double to index words
18
19 0113 03 8F 0130r add cx, [bx+Tx] ;X:= (X+Tx(R)) /2
20 0117 D1 E9 shr cx, 1
21
22 0119 03 97 0136r add dx, [bx+Ty] ;Y:= (Y+Ty(R)) /2
23 011D D1 EA shr dx, 1
24
25 011F B8 0C02 mov ax, 0C02h ;write green (2) graphics pixel
26 0122 CD 10 int 10h ;(bh=0)
27
28 0124 B4 01 mov ah, 01h ;loop until keystroke
29 0126 CD 16 int 16h
30 0128 74 DA jz cha10
31
32 012A B8 0003 mov ax, 0003h ;restore normal text-mode screen
33 012D CD 10 int 10h
34 012F C3 ret ;return to DOS
35
36 0130 0140 002B 0255 Tx dw 320, 320-277, 320+277 ;equilateral triangle
37 0136 0000 01DF 01DF Ty dw 0, 479, 479
38 end start</syntaxhighlight>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">int Tx, Ty, X, Y, R;
[SetVid($12); \640x480x4 graphics
Tx:= [320, 320-277, 320+277]; \equilateral triangle
Ty:= [0, 479, 479]; \277 = 480 / (2*Sin(60))
X:= Ran(640); \random starting point
Y:= Ran(480);
repeat R:= Ran(3); \select random triangle point
X:= (X+Tx(R))/2; \new point is halfway to it
Y:= (Y+Ty(R))/2;
Point(X, Y, 2\green\); \plot new point
until KeyHit;
SetVid($03); \restore normal text mode
]</syntaxhighlight>
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">width = 640 : height = 480
open window width, height
window origin "lb"
Line 2,086 ⟶ 3,658:
color 255 * (vertex = 0), 255 * (vertex = 1), 255 * (vertex = 2)
dot x, y
next</langsyntaxhighlight>
=={{header|Z80 Assembly}}==
{{trans|BASIC}}
 
This program runs on an MSX-2, in "SCREEN 5" (256x192 graphics mode).
It assembles to a .COM file that runs under MSX-DOS, and it will run until you press the
space key.
 
<syntaxhighlight lang="z80">VREG: equ 99h ; VDP register port
VR0: equ 0F3DFh ; Copy of VDP R0 in memory
VR1: equ 0F3E0h ; Copy of VDP R1 in memory
NEWKEY: equ 0FBE5h ; MSX BIOS puts key data here
VDP: equ 98h ; VDP data port
ROM: equ 0FCC0h ; Main ROM slot
JIFFY: equ 0FCE9h ; BIOS timer
calslt: equ 1Ch ; Interslot call routine
initxt: equ 6Ch ; Switch to default text mode
org 100h
ld bc,(JIFFY) ; Initialize RNG with time
ld d,b
ld e,c
exx ; RNG state stored in alternate registers
di ; Set up the VDP for 256x192 graphics mode
ld a,(VR0) ; Get old value of R0
and 112 ; Blank out mode bits
or 6 ; Set high 3 bits = 011(0)
out (VREG),a
ld a,128 ; Store in register 0
out (VREG),a
ld a,(VR1) ; Get old value of R1
and 99 ; Blank out mode bits
out (VREG),a
ld a,129 ; Low mode bits are 0 so we can just send it
out (VREG),a
ld a,31 ; Bitmap starts at beginning of VRAM
out (VREG),a
ld a,130
out (VREG),a
xor a ; Zero out the VRAM - set address to 0
out (VREG),a
ld a,142
out (VREG),a
xor a
out (VREG),a
ld a,64 ; Tell VDP to allow writing to VRAM
out (VREG),a
xor a ; Write zeroes to the VDP
ld c,192 ; 2 pixels per byte, meaning 128*192 bytes
zero1: ld b,128
zero2: out (VDP),a
djnz zero2
dec c
jr nz,zero1
ei
genX: call random ; Generate starting X coordinate
cp 200
jr nc,genX
ld b,a ; B = X
genY: call random ; Generate starting Y coordinate
cp 173
jr nc,genY
ld c,a ; C = Y
step: call random ; Get direction
and a,3 ; Directions {0,1,2}
cp a,3
jr z,step
ld ixh,a ; Store direction in IXH for color
dec a ; Select direction
jr z,d1
dec a
jr z,d2
xor a ; X /= 2
rr b
xor a ; Y /= 2
rr c
jr plot
d1: xor a ; There's a 16-bit SBC but not a 16-bit SUB
ld hl,100 ; (16-bit math or intermediate values won't fit)
ld d,a ; DE = X
ld e,b
sbc hl,de ; 100 - X
xor a
rr h ; (100 - X) / 2
rr l
ld e,100 ; (100 - X) / 2 + 100
add hl,de
ld b,l ; -> X
xor a
ld hl,173 ; 173
ld e,c
sbc hl,de ; (173 - Y)
rr h ; (173 - Y) / 2
rr l
ex de,hl
ld l,173
xor a
sbc hl,de ; 173 - (173-Y)/2
ld c,l ; -> Y
jr plot
d2: xor a
rr c ; Y /= 2
xor a
ld hl,200
ld d,a ; DE = X
ld e,b
sbc hl,de ; 200-X
xor a
rr h ; (200-X)/2
rr l
ex de,hl
ld l,200
sbc hl,de ; 200 - (200-X)/2
ld b,l ; -> X
plot: ld d,c ; Write address = CB/2
ld e,b
xor a
rr d
rr e
ld a,d ; First control byte =
rlca ; high 2 bytes of address
rlca
and 3
ld h,a ; Keep this value, we'll need it again
di
out (VREG),a
ld a,142 ; To port 14
out (VREG),a
ld a,e ; 2nd control byte = low 8 bits
out (VREG),a
ld a,d ; 3rd control byte = middle 6 bits
and 63 ; Bit 6 off = read
out (VREG),a
nop ; Give it some processing time
nop
in a,(VDP) ; Read the two pixels there
ld l,a ; Keep this byte
ld a,h ; Now set the VDP to write to that address
out (VREG),a
ld a,142
out (VREG),a
ld a,e
out (VREG),a
ld a,d
and 63 ; Bit 6 on = write
or 64
out (VREG),a
ld a,ixh ; Get color
add a,12
ld d,b ; Left or right pixel?
rr d
jr c,wpix
rlca ; Shift left if X is even
rlca
rlca
rlca
wpix: or l ; OR with other pixel in the byte
out (VDP),a ; Write byte
ei
wkey: ld a,(NEWKEY+8)
inc a ; Check if space key pushed
jp z,step ; If not, do another step
ld iy,ROM ; Switch back to text mode and quit
ld ix,initxt
jp calslt
random: exx ; RNG state stored in alternate registers
inc b ; X++
ld a,b ; X,
xor e ; ^ C,
xor c ; ^ A,
ld c,a ; -> A
add a,d ; + B
ld d,a ; -> B
rra ; >> 1
xor c ; ^ A,
add a,e ; + C,
ld e,a ; -> C
exx
ret</syntaxhighlight>
=={{header|zkl}}==
This is a half assed animated process - a bunch of pixels are drawn every couple of seconds and the pixmap written [to the file system]. So, if you open the output file ("chaosGame.jpg") it will [auto] update and show the progression of the image.
Line 2,094 ⟶ 3,842:
{{trans|Java}}
[[File:ChaosGame.zkl.jpg|240px|thumb|right]]
<langsyntaxhighlight lang="zkl">w,h:=640,640;
bitmap:=PPM(w,h,0xFF|FF|FF); // White background
colors:=T(0xFF|00|00,0x00|FF|00,0x00|00|FF); // red,green,blue
Line 2,121 ⟶ 3,869:
 
done.wait(); // don't exit until thread is done
println("Done");</langsyntaxhighlight>
2,120

edits