Wireworld: Difference between revisions
m
→{{header|Wren}}: Minor tidy
No edit summary |
m (→{{header|Wren}}: Minor tidy) |
||
(38 intermediate revisions by 21 users not shown) | |||
Line 14:
The cell transition rules are this:
::{| class=wikitable
|-
! Input State
Line 53:
While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V allstates = ‘Ht. ’
V head = allstates[0]
V tail = allstates[1]
V conductor = allstates[2]
V empty = allstates[3]
V w =
|‘tH.........
. .
...
. .
Ht.. ......’
T WW
[[Char]] world
Int w
Int h
F (world, w, h)
.world = world
.w = w
.h = h
F readfile(f)
V world = f.map(row -> row.rtrim(Array[Char]("\r\n")))
V height = world.len
V width = max(world.map(row -> row.len))
V nonrow = [‘ ’(‘ ’ * width)‘ ’]
V world2 = nonrow [+] world.map(row -> ‘ ’String(row).ljust(@width)‘ ’) [+] nonrow
V world3 = world2.map(row -> Array(row))
R WW(world3, width, height)
F newcell(currentworld, x, y)
V istate = currentworld[y][x]
assert(istate C :allstates, ‘Wireworld cell set to unknown value "#."’.format(istate))
V ostate = :empty
I istate == :head
ostate = :tail
E I istate == :tail
ostate = :conductor
E I istate == :empty
ostate = :empty
E
V n = sum([(-1, -1), (-1, +0), (-1, +1),
(+0, -1), (+0, +1),
(+1, -1), (+1, +0), (+1, +1)].map((dx, dy) -> Int(@currentworld[@y + dy][@x + dx] == :head)))
ostate = I n C 1..2 {:head} E :conductor
R ostate
F nextgen(ww)
V (world, width, height) = ww
V newworld = copy(world)
L(x) 1 .. width
L(y) 1 .. height
newworld[y][x] = newcell(world, x, y)
R WW(newworld, width, height)
F world2string(ww)
R ww.world[1 .< (len)-1].map(row -> (row[1 .< (len)-1]).join(‘’).rtrim((‘ ’, "\t", "\r", "\n"))).join("\n")
V ww = readfile(w.split("\n"))
L(gen) 10
print(("\n#3 ".format(gen))‘’(‘=’ * (ww.w - 4))"\n")
print(world2string(ww))
ww = nextgen(ww)</syntaxhighlight>
{{out}}
<pre style="height:45ex;overflow:scroll">
0 =======
tH.........
. .
...
. .
Ht.. ......
1 =======
.tH........
H .
...
H .
t... ......
2 =======
H.tH.......
t .
...
t .
.H.. ......
3 =======
tH.tH......
. H
...
. .
HtH. ......
4 =======
.tH.tH.....
H t
HHH
H .
t.tH ......
5 =======
H.tH.tH....
t .
ttt
t .
.H.t ......
6 =======
tH.tH.tH...
. H
...
. .
HtH. ......
7 =======
.tH.tH.tH..
H t
HHH
H .
t.tH ......
8 =======
H.tH.tH.tH.
t .
ttt
t .
.H.t ......
9 =======
tH.tH.tH.tH
. H
...
. .
HtH. ......
</pre>
=={{header|Ada}}==
<
procedure Test_Wireworld is
Line 120 ⟶ 273:
Wireworld (Oscillator);
end loop;
end Test_Wireworld;</
The solution assumes that the border of the board is empty. When transition is performed these cells are not changed. Automation transition is an in-place operation that allocates memory for to keep one row of the board size.
<pre style="height:30ex;overflow:scroll">
Line 170 ⟶ 323:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - missing transput function "printf" and non standard associate}}
<
Wireworld implementation.
CO
Line 291 ⟶ 444:
print ( world2string(ww) );
ww := next gen(ww)
OD</
{{out}}
<pre style="height:45ex;overflow:scroll">
Line 369 ⟶ 522:
{{works with|AutoHotkey_L}}
{{libheader|GDIP}}
<
#NoEnv
SetBatchLines, -1
Line 475 ⟶ 628:
Exit:
Gdip_Shutdown(pToken)
ExitApp</
=={{header|AutoIt}}==
<
$ww = ""
$ww &= "tH........." & @CR
Line 582 ⟶ 735:
WEnd
EndFunc ;==>Wireworld
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
[[Image:wireworld_bbc.gif|right]]
<
DIM P&(Size%-1,Size%-1), Q&(Size%-1,Size%-1)
Line 628 ⟶ 781:
SWAP P&(), Q&()
WAIT 50
UNTIL FALSE</
=={{header|C}}==
Line 642 ⟶ 795:
Compile with <code>-D_POSIX_C_SOURCE=199309L</code> or greater to make <code>nanosleep</code> visible in <code><time.h></code>.
<
#define ANIMATE_VT100_POSIX
#include <stdio.h>
Line 703 ⟶ 856:
return 0;
}</
=={{header|C sharp}}==
See: [[Wireworld/C sharp]]
=={{header|C++}}==
Line 710 ⟶ 866:
{{libheader|POSIX}} (for usleep)
<
#include <set>
#include <map>
Line 955 ⟶ 1,111:
}
std::cout << std::endl;
}</
=={{header|Ceylon}}==
<
shared Cell output({Cell*} neighbors) =>
Line 1,062 ⟶ 1,215:
}
}
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(destructuring-bind (rows cols) (array-dimensions wireworld)
(loop for off-row from (max 0 (1- row)) to (min (1- rows) (1+ row)) sum
Line 1,130 ⟶ 1,283:
" ... "
". . "
"Ht.. ......")))</
{{out}}
<pre style="height:30ex;overflow:scroll">CL-USER> (wireworld-show-gens (make-rosetta-wireworld) 12)
Line 1,207 ⟶ 1,360:
=={{header|D}}==
<
void wireworldStep(char[][] W1, char[][] W2) pure nothrow @safe @nogc {
Line 1,244 ⟶ 1,397:
swap(world, world2);
}
}</
{{out}}
<pre>
Line 1,281 ⟶ 1,434:
. ....
.. </pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IOUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Wireworld;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils;
var
rows, cols: Integer;
rx, cx: Integer;
mn: TArray<Integer>;
procedure Print(grid: TArray<byte>);
begin
writeln(string.Create('_', cols * 2), #10);
for var r := 1 to rows do
begin
for var c := 1 to cols do
begin
if grid[r * cx + c] = 0 then
write(' ')
else
write(' ', chr(grid[r * cx + c]));
end;
writeln;
end;
end;
procedure Step(var dst: TArray<byte>; src: TArray<byte>);
begin
for var r := 1 to rows do
begin
for var c := 1 to cols do
begin
var x := r * cx + c;
dst[x] := src[x];
case chr(dst[x]) of
'H':
dst[x] := ord('t');
't':
dst[x] := ord('.');
'.':
begin
var nn := 0;
for var n in mn do
if src[x + n] = ord('H') then
inc(nn);
if (nn = 1) or (nn = 2) then
dst[x] := ord('H');
end;
end;
end;
end;
end;
procedure Main();
const
CONFIG_FILE = 'ww.config';
begin
if not FileExists(CONFIG_FILE) then
begin
Writeln(CONFIG_FILE, ' not exist');
exit;
end;
var srcRows := TFile.ReadAllLines(CONFIG_FILE);
rows := length(srcRows);
cols := 0;
for var r in srcRows do
begin
if Length(r) > cols then
cols := length(r);
end;
rx := rows + 2;
cx := cols + 2;
mn := [-cx - 1, -cx, -cx + 1, -1, 1, cx - 1, cx, cx + 1];
var _odd: TArray<byte>;
var _even: TArray<byte>;
SetLength(_odd, rx * cx);
SetLength(_even, rx * cx);
FillChar(_odd[0], rx * cx, 0);
FillChar(_even[0], rx * cx, 0);
for var i := 0 to High(srcRows) do
begin
var r := srcRows[i];
var offset := (i + 1) * cx + 1;
for var j := 1 to length(r) do
_odd[offset + j - 1] := ord(r[j]);
end;
while True do
begin
print(_odd);
step(_even, _odd);
Readln;
print(_even);
step(_odd, _even);
Readln;
end;
end;
begin
Main;
{$IFNDEF UNIX} readln; {$ENDIF}
end.</syntaxhighlight>
{{out}}
<pre>__________________
t H
. . . . .
. .
__________________
. t
. H . . .
. .
__________________
. .
. t H . .
. H
__________________
. .
. . t H .
H t
__________________
. .
H . . t H
t .
__________________
H .
t . . . t
. .
__________________
t H
. . . . .
. .
__________________
. t
. H . . .
. .
</pre>
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=hVTNbuMgEL7zFKNstdptFdaOVSU95J53WFUrikmLlhgLSJv06XfAYLDjarkYz3zz980M9mrB6V6JoyOvSr8wBaffz9BxoOSF8b+vRp+7FrbbLfkGpDeag33TH0BRDwBcCWb8xXKmBOyhrir4heZB9omCQXEPFX169MKjNiAxJCjR+VBehueC0B8S1lD/hJNuowc810LRyvesOOl3gWb3McI13aJaHtG7fEbrKkp8ulph+KpKIqEyrJ7DnnZLsM0c1jS7EWbFXLtrmiii8WsEd54a+0mClA6sGsHaxKq9w0Cy68/O/2Ev9oEtFD8M8UcSMxvYtO+x1uDDiF4wt6CN5vwOI4B1hr8xY9F3zhyL5T6DFV1lYfZSEBWIGbCHRexmEesWsU2JLZmEmwIg05m+BSU4LJGudZnszEcynJKN59w5qQbxajXy+T/KKfEd9EsSBrtDZZrwtDjnvmVOpCZ/sQiLk4bugihRVA5kcwurF2AFEXa6FD6R1u/fuvbpFMCkvH6hxCO9ocS5bP0CIvd4u8xBFh72sbDLrDLIjZheEe7z3AAmYKf5Q650Ml/zmeluKp8MzbBqH6wfuuVbQInuwMmTCG/a0K+AwifPf4MKn7JHRAZZFmCTwxD9QRtG3IGmQ+gYcPw5OEohqgn5Bw== Run it]
<syntaxhighlight>
sys topleft
global m[] nc .
background 777
#
proc show . .
clear
scale = 100 / nc
sz = scale * 0.95
for i to len m[]
x = (i - 1) mod nc
y = (i - 1) div nc
move x * scale y * scale
if m[i] = 0
color 000
elif m[i] = 1
color 980
elif m[i] = 2
color 338
else
color 833
.
rect sz sz
.
.
proc read . .
s$ = input
nc = len s$ + 2
for i to nc
m[] &= 0
.
repeat
m[] &= 0
for c$ in strchars s$
if c$ = "."
m[] &= 1
elif c$ = "H"
m[] &= 2
elif c$ = "t"
m[] &= 3
else
m[] &= 0
.
.
for i to nc - len s$ - 1
m[] &= 0
.
s$ = input
until s$ = ""
.
for i to nc
m[] &= 0
.
.
read
#
len mn[] len m[]
#
proc update . .
for i to len m[]
if m[i] = 2
mn[i] = 3
elif m[i] = 3
mn[i] = 1
elif m[i] = 1
s = 0
for dx = -1 to 1
for dy = -1 to 1
ix = i + dy * nc + dx
s += if m[ix] = 2
.
.
if s = 2 or s = 1
mn[i] = 2
else
mn[i] = 1
.
.
.
swap mn[] m[]
.
on timer
update
show
timer 0.5
.
show
timer 0.5
#
input_data
tH.........
. .
...
. .
Ht.. ......
</syntaxhighlight>
=={{header|Elena}}==
ELENA 6.x, using cellular library
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import cellular;
const string sample =
" tH......
. ......
...Ht... .
....
. .....
....
......tH .
. ......
...Ht...";
const string conductorLabel = ".";
const string headLabel = "H";
const string tailLabel = "t";
const string emptyLabel = " ";
const int empty = 0;
const int conductor = 1;
const int electronHead = 2;
const int electronTail = 3;
wireWorldRuleSet = new RuleSet
{
int proceed(Space s, int x, int y)
{
int cell := s.at(x, y);
cell =>
conductor
{
int number := s.LiveCell(x, y, electronHead);
if (number == 1 || number == 2)
{
^ electronHead
}
else
{
^ conductor
}
}
electronHead
{
^ electronTail
}
electronTail
{
^ conductor
}
!{
^ cell
}
}
};
sealed class Model
{
Space theSpace;
constructor load(string stateString, int maxX, int maxY)
{
var strings := stateString.splitBy(newLineConstant).selectBy::(s => s.toArray()).toArray();
theSpace := IntMatrixSpace.allocate(maxX, maxY, RuleSet
{
int proceed(Space s, int x, int y)
{
int retVal := 0;
if (x < strings.Length)
{
var l := strings[x];
if (y < l.Length)
{
(l[y]) =>
conductorLabel { retVal := conductor }
headLabel { retVal := electronHead }
tailLabel { retVal := electronTail }
emptyLabel { retVal := empty }
}
else
{
retVal := empty
}
}
else
{
retVal := empty
};
^ retVal
}
})
}
run()
{
theSpace.update(wireWorldRuleSet)
}
print()
{
int columns := theSpace.Columns;
int rows := theSpace.Rows;
int i := 0;
int j := 0;
while (i < rows)
{
j := 0;
while (j < columns)
{
var label := emptyLabel;
int cell := theSpace.at(i, j);
cell =>
conductor { label := conductorLabel }
electronHead { label := headLabel }
electronTail { label := tailLabel };
console.write(label);
j := j + 1
};
i := i + 1;
console.writeLine()
}
}
}
public program()
{
Model model := Model.load(sample,10,30);
for(int i := 0; i < 10; i += 1)
{
console.printLineFormatted("Iteration {0}",i);
model.print().run()
}
}</syntaxhighlight>
{{out}}
<pre>
Iteration 0
tH......
. ......
...Ht... .
....
. .....
....
......tH .
. ......
...Ht...
Iteration 1
.tH.....
. ......
..Ht.... .
....
. .....
....
.......t .
. H.....
..Ht....
Iteration 2
..tH....
. ......
.Ht..... .
....
. .....
....
........ .
. tH....
.Ht....H
Iteration 3
...tH...
. ......
Ht...... .
....
. .....
....
........ .
. .tH...
Ht....Ht
/* ... */
Iteration 9
...tH...
. .tH...
......Ht .
....
H H....
tttH
...tH... .
. ......
Ht......
</pre>
=={{header|Elixir}}==
{{trans|Ruby}}
<
@empty " "
@head "H"
Line 1,367 ⟶ 2,016:
"""
Wireworld.run(text)</
{{out}}
Line 1,638 ⟶ 2,287:
</pre>
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Wireworld. Nigel Galloway: January 22nd., 2024
type Cell= |E |T |H |C
let n=array2D [[T;H;C;C;C;C;C;C;C;C;C];
[C;E;E;E;C;E;E;E;E;E;E];
[E;E;E;C;C;C;E;E;E;E;E];
[C;E;E;E;C;E;E;E;E;E;E];
[H;T;C;C;E;C;C;C;C;C;C]]
let fG n g=match n|>Seq.sumBy(fun n->match Array2D.get g (fst n) (snd n) with H->1 |_->0) with 1 |2->H |_->C
let fX i=i|>Array2D.mapi(fun n g->function |E->E |H->T |T->C |C->fG (Seq.allPairs [max 0 (n-1)..min (n+1) (Array2D.length1 i-1)] [max 0 (g-1)..min (g+1) (Array2D.length2 i-1)]) i)
Seq.unfold(fun n->Some(n,fX n))n|>Seq.take 15|>Seq.iteri(fun n g->printfn "%d:\n%A\n" n g)
</syntaxhighlight>
{{out}}
after 7: 8,9,10 are repeated as 11,12,13 then 14,15,16 etc
<pre>
0:
[[T; H; C; C; C; C; C; C; C; C; C]
[C; E; E; E; C; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[C; E; E; E; C; E; E; E; E; E; E]
[H; T; C; C; E; C; C; C; C; C; C]]
1:
[[C; T; H; C; C; C; C; C; C; C; C]
[H; E; E; E; C; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[H; E; E; E; C; E; E; E; E; E; E]
[T; C; C; C; E; C; C; C; C; C; C]]
2:
[[H; C; T; H; C; C; C; C; C; C; C]
[T; E; E; E; C; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[T; E; E; E; C; E; E; E; E; E; E]
[C; H; C; C; E; C; C; C; C; C; C]]
3:
[[T; H; C; T; H; C; C; C; C; C; C]
[C; E; E; E; H; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[C; E; E; E; C; E; E; E; E; E; E]
[H; T; H; C; E; C; C; C; C; C; C]]
4:
[[C; T; H; C; T; H; C; C; C; C; C]
[H; E; E; E; T; E; E; E; E; E; E]
[E; E; E; H; H; H; E; E; E; E; E]
[H; E; E; E; C; E; E; E; E; E; E]
[T; C; T; H; E; C; C; C; C; C; C]]
5:
[[H; C; T; H; C; T; H; C; C; C; C]
[T; E; E; E; C; E; E; E; E; E; E]
[E; E; E; T; T; T; E; E; E; E; E]
[T; E; E; E; C; E; E; E; E; E; E]
[C; H; C; T; E; C; C; C; C; C; C]]
6:
[[T; H; C; T; H; C; T; H; C; C; C]
[C; E; E; E; H; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[C; E; E; E; C; E; E; E; E; E; E]
[H; T; H; C; E; C; C; C; C; C; C]]
7:
[[C; T; H; C; T; H; C; T; H; C; C]
[H; E; E; E; T; E; E; E; E; E; E]
[E; E; E; H; H; H; E; E; E; E; E]
[H; E; E; E; C; E; E; E; E; E; E]
[T; C; T; H; E; C; C; C; C; C; C]]
8:
[[H; C; T; H; C; T; H; C; T; H; C]
[T; E; E; E; C; E; E; E; E; E; E]
[E; E; E; T; T; T; E; E; E; E; E]
[T; E; E; E; C; E; E; E; E; E; E]
[C; H; C; T; E; C; C; C; C; C; C]]
9:
[[T; H; C; T; H; C; T; H; C; T; H]
[C; E; E; E; H; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[C; E; E; E; C; E; E; E; E; E; E]
[H; T; H; C; E; C; C; C; C; C; C]]
10:
[[C; T; H; C; T; H; C; T; H; C; T]
[H; E; E; E; T; E; E; E; E; E; E]
[E; E; E; H; H; H; E; E; E; E; E]
[H; E; E; E; C; E; E; E; E; E; E]
[T; C; T; H; E; C; C; C; C; C; C]]
11:
[[H; C; T; H; C; T; H; C; T; H; C]
[T; E; E; E; C; E; E; E; E; E; E]
[E; E; E; T; T; T; E; E; E; E; E]
[T; E; E; E; C; E; E; E; E; E; E]
[C; H; C; T; E; C; C; C; C; C; C]]
12:
[[T; H; C; T; H; C; T; H; C; T; H]
[C; E; E; E; H; E; E; E; E; E; E]
[E; E; E; C; C; C; E; E; E; E; E]
[C; E; E; E; C; E; E; E; E; E; E]
[H; T; H; C; E; C; C; C; C; C; C]]
13:
[[C; T; H; C; T; H; C; T; H; C; T]
[H; E; E; E; T; E; E; E; E; E; E]
[E; E; E; H; H; H; E; E; E; E; E]
[H; E; E; E; C; E; E; E; E; E; E]
[T; C; T; H; E; C; C; C; C; C; C]]
14:
[[H; C; T; H; C; T; H; C; T; H; C]
[T; E; E; E; C; E; E; E; E; E; E]
[E; E; E; T; T; T; E; E; E; E; E]
[T; E; E; E; C; E; E; E; E; E; E]
[C; H; C; T; E; C; C; C; C; C; C]]
</pre>
=={{header|Forth}}==
<
8 constant h
Line 1,719 ⟶ 2,489:
: gen ['] newrow foreachrow age ;
: wireworld begin gen 0 0 at-xy show key? until ;</
{{out}}
Line 1,844 ⟶ 2,614:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 1,928 ⟶ 2,698:
end do
end subroutine Nextgen
end program Wireworld</
{{out}}
<pre style="height:30ex;overflow:scroll">Generation 0
Line 2,020 ⟶ 2,790:
. .
tH...</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#define MAXX 319
#define MAXY 199
enum state
E=0, C=8, H=9, T=4 'doubles as colours: black, grey, bright blue, red
end enum
dim as uinteger world(0 to 1, 0 to MAXX, 0 to MAXY), active = 0, buffer = 1
dim as double rate = 1./3. 'seconds per frame
dim as double tick
dim as uinteger x, y
function turn_on( world() as unsigned integer, x as uinteger, y as uinteger, a as uinteger ) as boolean
dim as ubyte n = 0
dim as integer qx, qy
for qx = -1 to 1
for qy = -1 to 1
if qx=0 andalso qy=0 then continue for
if world(a,(x+qx+MAXX+1) mod (MAXX+1), (y+qy+MAXY+1) mod (MAXY+1))=H then n=n+1 'handles wrap-around
next qy
next qx
if n=1 then return true
if n=2 then return true
return false
end function
'generate sample map
for x=20 to 30
world(active, x, 20) = C
world(active, x, 24) = C
next x
world(active, 24, 24 ) = E
world(active, 20, 21 ) = C
world(active, 20, 23 ) = C
world(active, 24, 21 ) = C
world(active, 23, 22 ) = C
world(active, 24, 22 ) = C
world(active, 25, 22 ) = C
world(active, 24, 23 ) = C
world(active, 20, 20 ) = T
world(active, 21, 20 ) = H
world(active, 21, 24 ) = T
world(active, 20, 24 ) = H
screen 12
do
tick = timer
for x = 0 to 319
for y = 0 to 199
pset (x,y), world(active, x, y)
if world(active,x,y) = E then world(buffer,x,y) = E 'empty cells stay empty
if world(active,x,y) = H then world(buffer,x,y) = T 'electron heads turn into electron tails
if world(active,x,y) = T then world(buffer,x,y) = C 'electron tails revert to conductors
if world(active,x,y) = C then
if turn_on(world(),x,y,active) then
world(buffer,x,y) = H 'maybe electron heads spread
else
world(buffer,x,y) = C 'otherwise condutor remains conductor
end if
end if
next y
next x
while tick + rate > timer
wend
cls
buffer = 1 - buffer
active = 1 - buffer
loop</syntaxhighlight>
=={{header|GML}}==
Only visual output. Not an all-out simulator, but has some functions not on by default.
<
/*
Wireworld first declares constants and then reads a wireworld from a textfile.
Line 2,120 ⟶ 2,963:
ds_grid_destroy(gridid);
ds_list_destroy(listid);
}</
Now the step event
<syntaxhighlight lang="gml">
//Step event
/*
Line 2,341 ⟶ 3,184:
}
}
</syntaxhighlight>
Now the draw event
<syntaxhighlight lang="gml">
//Draw event
/*
Line 2,406 ⟶ 3,249:
}
draw_set_color(c_black);
</syntaxhighlight>
=={{header|Go}}==
Text output. Press Enter to compute and display successive generations.
<
import (
Line 2,498 ⟶ 3,342:
}
}
}</
=={{header|Haskell}}==
<
import Control.Monad
import Control.Arrow
Line 2,521 ⟶ 3,365:
noH = length $ filter (=='H') $ concat xs
runCircuit = iterate (map(map nwState).take3x3)</
Example executed in GHCi:
<
". ....",
" .. "
]
example = mapM_ (mapM_ putStrLn) .map (borden ' ').take 9 $ runCircuit oscillator</
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 2,584 ⟶ 3,428:
This simulation starts in single step mode and can be switched to run uninterrupted. The window can be saved at any point in single step mode.
This uses 1 pixel per cell so this animation looks tiny. Also the orientation has been flipped.
<
$define EDGE -1
Line 2,675 ⟶ 3,519:
}
}
end</
{{libheader|Icon Programming Library}}
Line 2,681 ⟶ 3,525:
=={{header|J}}==
The example circuit:<
tH........
. .
Line 2,687 ⟶ 3,531:
. .
Ht.. .....
)</
A 'boarding' verb board and the next cell state verb nwS:
<
nwS=: 3 : 0
Line 2,695 ⟶ 3,539:
if. ('.'=e)*. e.&1 2 +/'H'=,y do. 'H' return. end.
' t..' {~ ' Ht.' i. e
)</
The 'most' powerful part is contained in the following iterating sentence, namely the dyad cut ;. [http://www.jsoftware.com/help/dictionary/d331.htm ]. In this way verb nwS can work on all the 3x3 matrices containing each cell surrounded by its 8 relevant neighbors.
<
(<10) process circuit</
Example run:
<pre style="height:30ex;overflow:scroll">
Line 2,765 ⟶ 3,609:
Note also that a graphical presentation can be achieved using viewmat. For example:
<
viewmat"2 ' .tH'i. (<10) process circ0</
(This example opens 10 windows, one for each generation.)
Line 2,782 ⟶ 3,626:
<input type='file' accept='text/plain' onchange='openFile( event )' />
<br /></body></html></pre>
<
var ctx, sizeW, sizeH, scl = 10, map, tmp;
function getNeighbour( i, j ) {
Line 2,871 ⟶ 3,715:
simulate();
}
</syntaxhighlight>
=={{header|jq}}==
Line 2,883 ⟶ 3,727:
* For speed, the simulation uses the exploded string (an array).
* The ASCII values of the symbols used to display the state are hardcoded.
<
def cols: split("\n")[0]|length + 1; # allow for the newline
Line 2,919 ⟶ 3,763:
$world | evolve($i; $w) as $next
| if .[$i] == $next then . else .[$i] = $next end )
| [., $lines, $w] ; # </
'''Animation'''
<
def cls: "\u001b[2J";
Line 2,946 ⟶ 3,790:
# Input: a string representing the initial state
def frames(n): animation(n; -1);#</
'''Examples''':
<
"+-----------+\n" +
"|tH.........|\n" +
Line 2,962 ⟶ 3,806:
" . .... \n" +
" .. \n" +
" \n" ;</
'''Illustration 1''':
<
world9 | animation(10; 1000)</
'''Illustration 2''':
<
world11 | frames(10)</
To run: jq -n -r -f wireworld.rc
=={{header|Julia}}==
<syntaxhighlight lang="julia">function surround2D(b, i, j)
h, w = size(b)
[b[x,y] for x in i-1:i+1, y in j-1:j+1 if (0 < x <= h && 0 < y <= w)]
end
surroundhas1or2(b, i, j) = 0 < sum(map(x->Char(x)=='H', surround2D(b, i, j))) <= 2 ? 'H' : '.'
function boardstep!(currentboard, nextboard)
x, y = size(currentboard)
for j in 1:y, i in 1:x
ch = Char(currentboard[i, j])
if ch == ' '
continue
else
nextboard[i, j] = (ch == 'H') ? 't' : (ch == 't' ? '.' :
surroundhas1or2(currentboard, i, j))
end
end
end
const b1 = " " *
" tH " *
" . .... " *
" .. " *
" "
const mat = reshape(map(x->UInt8(x[1]), split(b1, "")), (9, 5))'
const mat2 = copy(mat)
function printboard(mat)
for i in 1:size(mat)[1]
println("\t", join([Char(c) for c in mat[i,:]], ""))
end
end
println("Starting Wireworld board:")
printboard(mat)
for step in 1:8
boardstep!(mat, mat2)
println(" Step $step:")
printboard(mat2)
mat .= mat2
end
</syntaxhighlight>{{output}}<pre>
Starting Wireworld board:
tH
. ....
..
Step 1:
.t
. H...
..
Step 2:
..
. tH..
.H
Step 3:
..
. .tH.
Ht
Step 4:
..
H ..tH
t.
Step 5:
H.
t ...t
..
Step 6:
tH
. ....
..
Step 7:
.t
. H...
..
Step 8:
..
. tH..
.H
</pre>
=={{header|Liberty BASIC}}==
[[File:AnimWW.gif]]
<syntaxhighlight lang="lb">
WindowWidth = 840
WindowHeight = 600
Line 3,104 ⟶ 4,047:
timer 1000, [tmr]
wait
</syntaxhighlight>
=={{header|Logo}}==
{{Works with|MSWlogo}}
(The wireworld given in the file must be bounded by spaces for the program to work. Also it is notable that the program takes the width as the longest of the lines.)
<
Make "speed 60/:speed
wireworldread :filename
Line 3,249 ⟶ 4,120:
if (mditem (list :y-1 :x-1) :field)=:thing [Make "neighbours :neighbours+1]
ifelse OR :neighbours=1 :neighbours=2 [op "true] [op "false]
end</
=={{header|
If ran using [[L%C3%96VE]], it will animate the simulation on a window. Otherwise it will print the first 10 steps on the console.
<syntaxhighlight lang="lua">
local map = {{'t', 'H', '.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', ' ', ' ', ' ', '.'},
{' ', ' ', ' ', '.', '.', '.'},
{'.', ' ', ' ', ' ', '.'},
{'H', 't', '.', '.', ' ', '.', '.', '.', '.', '.', '.'}}
function step(map)
local next = {}
for i = 1, #map do
next[i] = {}
for j = 1, #map[i] do
next[i][j] = map[i][j]
if map[i][j] == "H" then
next[i][j] = "t"
elseif map[i][j] == "t" then
next[i][j] = "."
elseif map[i][j] == "." then
local count = ((map[i-1] or {})[j-1] == "H" and 1 or 0) +
((map[i-1] or {})[j] == "H" and 1 or 0) +
((map[i-1] or {})[j+1] == "H" and 1 or 0) +
((map[i] or {})[j-1] == "H" and 1 or 0) +
((map[i] or {})[j+1] == "H" and 1 or 0) +
((map[i+1] or {})[j-1] == "H" and 1 or 0) +
((map[i+1] or {})[j] == "H" and 1 or 0) +
((map[i+1] or {})[j+1] == "H" and 1 or 0)
if count == 1 or count == 2 then
next[i][j] = "H"
else
next[i][j] = "."
end
end
end
end
return next
end
if not not love then
local time, frameTime, size = 0, 0.25, 20
local colors = {["."] = {255, 200, 0},
["t"] = {255, 0, 0},
["H"] = {0, 0, 255}}
function love.update(dt)
time = time + dt
if time > frameTime then
time = time - frameTime
map = step(map)
end
end
function love.draw()
for i = 1, #map do
for j = 1, #map[i] do
love.graphics.setColor(colors[map[i][j]] or {0, 0, 0})
love.graphics.rectangle("fill", j*size, i*size, size, size)
end
end
end
else
for iter = 1, 10 do
print("\nstep "..iter.."\n")
for i = 1, #map do
for j = 1, #map[i] do
io.write(map[i][j])
end
io.write("\n")
end
map = step(map)
end
end
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">DynamicModule[{data =
ArrayPad[PadRight[Characters /@ StringSplit["tH.........
. .
Line 3,265 ⟶ 4,210:
3, {{a_, b_, c_}, {d_, 3, e_}, {f_, g_, h_}} :>
Switch[Count[{a, b, c, d, e, f, g, h}, 1], 1, 1, 2, 1, _, 3]},
data], ColorRules -> {1 -> Yellow, 2 -> Red}]]</
=={{header|MiniScript}}==
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<syntaxhighlight lang="miniscript">
colors = [color.black, color.yellow, color.aqua, color.red]
deltas = [[-1,-1], [-1,0], [-1,1],
[ 0,-1], [ 0,1],
[ 1,-1], [ 1,0], [ 1,1]]
displayGrid = function(grid, td)
for y in range(0, grid.len - 1)
for x in range(0, grid[0].len - 1)
td.setCell x,y, grid[y][x]
end for
end for
end function
buildGrid = function(s)
lines = s.split(char(13))
nRows = lines.len
nCols = 0
for line in lines
if line.len > nCols then nCols = line.len
end for
grid = []
emptyRow = []
for c in range(1,nCols)
emptyRow.push(0)
end for
for line in lines
row = emptyRow[:]
for i in range(0, line.len - 1)
row[i] = " .Ht".indexOf(line[i])
end for
grid.push(row)
end for
return grid
end function
getNewState = function(td, x, y)
cellState = td.cell(x, y)
if cellState == 3 then
return 1
else if cellState == 2 then
return 3
else if cellState == 1 then
sum = 0
for delta in deltas
x1 = x + delta[0]
y1 = y + delta[1]
if td.cell(x1, y1) == 2 then sum += 1
end for
if sum == 1 or sum == 2 then
return 2
else
return 1
end if
end if
return cellState
end function
clear
wireWorldProgram = "tH........." + char(13)
wireWorldProgram += ". ." + char(13)
wireWorldProgram += " ..." + char(13)
wireWorldProgram += ". ." + char(13)
wireWorldProgram += "Ht.. ......"
grid = buildGrid(wireWorldProgram)
// Prepare a tile display
// Generate image used for the tiles from the colors defined above.
img = Image.create(colors.len, 1);
for i in range(0, colors.len - 1)
img.setPixel(i, 0, colors[i])
end for
cols = grid[0].len
rows = grid.len
display(4).mode = displayMode.tile
td = display(4)
cSize = 25
td.cellSize = cSize // size of cells on screen
td.scrollX = -(960 - cols * (cSize + 1)) / 2
td.scrollY = -(640 - rows * (cSize + 1)) / 2
td.extent = [cols, rows]
td.overlap = -1 // adds a small gap between cells
td.tileSet = img; td.tileSetTileSize = 1
td.clear 0
while true
displayGrid(grid, td)
for y in range(0, rows - 1)
for x in range(0, cols - 1)
grid[y][x] = getNewState(td, x, y)
end for
end for
wait 0.5
end while
</syntaxhighlight>
=={{header|Nim}}==
{{trans|C}}
<
var world, world2 = """
Line 3,279 ⟶ 4,325:
|Ht.. ......|
+-----------+"""
let h = world.splitLines.len
let w = world.splitLines[0].len
template isH(x, y): int = int(s[i + w * y + x] == 'H')
proc next(o: var string, s: string, w: int) =
Line 3,304 ⟶ 4,351:
world2.next(world, w)
swap world, world2</
=={{header|OCaml}}==
<
" ......tH ";
" . ...... ";
Line 3,363 ⟶ 4,410:
aux n
in
aux w</
=={{header|Oz}}==
Includes a simple animation, using a text widget.
<
Rules =
[rule(& & )
Line 3,458 ⟶ 4,505:
{Field set(text:{ShowArena Gi})}
{Delay 500}
end</
=={{header|PARI/GP}}==
<
wireworldStep(M)={
my(sz=matsize(M),t);
Line 3,491 ⟶ 4,538:
)
};
animate(read("wireworld.gp"))</
=={{header|Perl}}==
Read the initial World from stdin and print 10 steps to stdout
<
for (1 .. 10) {
Line 3,515 ⟶ 4,562:
}
@f = (@a,[]);
}</
Input:
<pre>tH.........
Line 3,594 ⟶ 4,641:
</pre>
=={{header|
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/Wireworld.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Wireworld.exw
-- ==========================
--
-- Invoke with file to read, or let it read the one below (if compiled assumes source is in the same directory)
--
-- Note that tabs in description files are not supported - where necessary spaces can be replaced with _ chars.
-- (tab chars in text files should technically always represent (to-next) 8 spaces, but not many editors respect
-- that, and instead assume the file will only ever be read by the same program/with matching settings. </rant>)
-- (see also demo\edix\src\tabs.e\ExpandTabs() for what you'd need if you knew what the tab chars really meant.)
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">default_description</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
tH.........
.___.
___...
.___.
Ht.. ......
"""</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lines</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">counts</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">longest</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valid_line</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">line</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</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: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" _.tH"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">l</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'\t'</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- as above</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"error: tab char on line %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">l</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</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: #000000;">0</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: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">load_desc</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">text</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: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">default_description</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()[$],</span><span style="color: #008000;">".exe"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">".exw"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"error opening %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</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: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">valid_line</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">line</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</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: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">valid_line</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">longest</span><span style="color: #0000FF;"><</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</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;">for</span>
<span style="color: #008080;">exit</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: #000000;">counts</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">dxy</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,+</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{+</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{+</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,+</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">set_counts</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</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;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">lines</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: #008000;">'.'</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dxy</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">cx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cy</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</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;">dxy</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cy</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cy</span><span style="color: #0000FF;">][</span><span style="color: #000000;">cx</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'H'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">count</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;">for</span>
<span style="color: #000000;">counts</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: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">or</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</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;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</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: #008080;">constant</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Wireworld"</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: #0000FF;">,</span> <span style="color: #000000;">timer</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;">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: #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;">integer</span> <span style="color: #000000;">dx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">w</span><span style="color: #0000FF;">/(</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">dy</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;">/(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">2</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: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">set_counts</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</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;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">y</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lines</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;">colour</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" _"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">CD_BLACK</span>
<span style="color: #008080;">elsif</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;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">CD_YELLOW</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">counts</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: #008080;">then</span>
<span style="color: #000000;">lines</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: #0000FF;">=</span> <span style="color: #008000;">'H'</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'H'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">CD_BLUE</span>
<span style="color: #000000;">lines</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: #0000FF;">=</span> <span style="color: #008000;">'t'</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'t'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">CD_RED</span>
<span style="color: #000000;">lines</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: #0000FF;">=</span> <span style="color: #008000;">'.'</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</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: #000000;">colour</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasBox</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;">dx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">dx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">dx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">dy</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">-(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">dy</span><span style="color: #0000FF;">+</span><span style="color: #000000;">dy</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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: #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_BLACK</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;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">load_desc</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=300x180"</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;">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;">500</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="%s"`</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">title</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: #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|PHP}}==
<syntaxhighlight lang="php">
$desc = 'tH.........
. .
Line 3,931 ⟶ 4,918:
draw_world($world);
};
</syntaxhighlight>
=={{header|PicoLisp}}==
This example uses 'grid' from "lib/simul.l", which maintains a two-dimensional
structure.
<
(let
Line 3,971 ⟶ 4,958:
(for This Col
(=: val (: next)) ) )
(prinl) ) )</
{{out}}
<pre> +---+---+---+---+---+---+---+---+---+---+---+
Line 4,014 ⟶ 5,001:
=={{header|PureBasic}}==
===Standalone version===
<
#Empty
#Electron_head
Line 4,128 ⟶ 5,115:
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EndDataSection</
===Load from external source, graphical presentations===
<
CompilerError "The file handling in this small program is only in ASCII."
CompilerEndIf
Line 4,274 ⟶ 5,261:
EndIf
Until Event=#PB_Event_CloseWindow
EndIf</
Example of data file to load
<pre>; Save as "WireWorld.txt"
Line 4,332 ⟶ 5,319:
=={{header|Python}}==
<
Wireworld implementation.
'''
Line 4,401 ⟶ 5,388:
print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' )
print ( world2string(ww) )
ww = nextgen(ww)</
{{out}}
Line 4,487 ⟶ 5,474:
=={{header|Racket}}==
<
#lang racket
(require 2htdp/universe)
Line 4,595 ⟶ 5,582:
(run-wire-world #:initial-state initial-list)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" line>class Wireworld {
has @.line;
method height returns Int { @!line.elems }
method width returns Int { max @!line».chars }
multi method new(@line) { samewith :@line }
multi method new($str ) { samewith $str.lines }
method gist { join "\n", @.line }
method !neighbors($i where ^$.height, $j where ^$.width)
{
my @i = grep ^$.height, $i «+« (-1, 0, 1);
my @j = grep ^$.width, $j «+« (-1, 0, 1);
gather for @i X @j -> (\i, \j) {
next if [ i, j ] ~~ [ $i, $j ];
take @!line[i].comb[j];
}
}
method succ {
my @succ;
for ^$.height X ^$.width -> ($i, $j) {
@succ[$i] ~=
do given @.line[$i].comb[$j] {
when 'H' { 't' }
when 't' { '.' }
when '.' {
grep('H', self!neighbors($i, $j)) == 1|2 ?? 'H' !! '.'
}
default { ' ' }
}
}
return self.new: @succ;
}
}
my %*SUB-MAIN-OPTS;
%*SUB-MAIN-OPTS<named-anywhere> = True;
multi sub MAIN (
IO() $filename,
Numeric:D :$interval = 1/4,
Bool :$stop-on-repeat,
) {
run-loop :$interval, :$stop-on-repeat, Wireworld.new: $filename.slurp;
}
#| run a built-in example
multi sub MAIN (
Numeric:D :$interval = 1/4,
Bool :$stop-on-repeat,
) {
run-loop
:$interval,
:$stop-on-repeat,
Wireworld.new:
Q:to/§/
tH.........
. .
...
. .
Ht.. ......
§
}
sub run-loop (
Wireworld:D $initial,
Real:D(Numeric) :$interval = 1/4,
Bool :$stop-on-repeat
){
my %seen is SetHash;
print "\e7"; # save cursor position
for $initial ...^ * eqv * { # generate a sequence (uses .succ)
print "\e8"; # restore cursor position
.say;
last if $stop-on-repeat and %seen{ .gist }++;
sleep $interval;
}
}</syntaxhighlight>
When run with <code>--stop-on-repeat</code>
{{out}}
<pre>H.tH.tH.tH.
t .
ttt
t .
.H.t ......</pre>
=={{header|REXX}}==
<
parse arg iFID . '(' generations rows cols bare head tail wire clearScreen reps
if iFID=='' then iFID= "WIREWORLD.TXT"
generations = p(generations 100 ) /*number generations that are allowed. */
rows = p(rows 3 ) /*the number of cell rows. */
cols = p(cols 3 ) /* " " " " columns. */
bare = pickChar(bare
clearScreen = p(clearScreen 0 ) /*1 means to clear the screen. */
head = pickChar(head 'H' ) /*pick the character for the head. */
tail = pickChar(
wire = pickChar(wire . ) /* " " " " " wire. */
reps = p(reps 2 ) /*stop program if there are 2 repeats.*/
fents= max(cols, linesize() - 1
#reps= 0; $.= bare; gens=
/* [↓] read the input file. */
L=
end
/*watch cells evolve, 4 possible states*/
do life=1 for gens;
do r=1 for rows /*process each of the rows. */
do c=1 for cols; ?= $.r.c; ??=
select /*determine the type of cell. */
when ?==head then ??= tail
when ?==tail then ??= wire
when ?==wire then do; #=
otherwise nop
end /*select*/
@.r.c= ?? /*possible assign a cell a new state.*/
end /*c*/
end /*r*/
Line 4,642 ⟶ 5,719:
end /*life*/
/*stop watching the universe (or life).*/
halt: if life-1\==gens then say 'The
done: exit
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
$: parse arg _row,_col; return $._row._col==head
assign$: do r=1 for rows; do c=1 for cols; $.r.c= @.r.c; end; end; return
hood: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1)
p: return word(arg(1), 1) /*pick the 1st word in list.*/
pickChar: parse arg _ .;arg U .;L=length(_);if U==bla then _=' '; if L==3 then _=d2c(_);if L==2 then _=x2c(_);return _
showRows: _=; do r=1 for rows; z=; do c=1 for cols; z= z||$.r.c; end; z= strip(z,'T'); say z; _= _||z; end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showCells: if clearScreen then 'CLS' /*◄──change
call showRows /*show rows in proper order.*/
say right( copies('═', fents)life, fents)
if _==''
if !._
!._= 1
if reps\==0 & #reps<=reps then return /*so far, so good, no reps.
say '"Wireworld" repeated itself' reps "times, the program is stopping."
signal done /*
Programming note: the '''hood''' subroutine (above) could be optimized for speed by setting some short-circuit values <code>('''r-1''', '''c-1''', '''r+1''', and '''c+1''') </code> and using those values in the subsequent expressions.
The '''
{{out|output|text= when using the default input file:}}
(Cycle '''0''' (zero) is essentially a copy of the input file.)
<pre style="height:60ex">
Line 4,753 ⟶ 5,832:
t.tH ......
═══════════════════════════════════════════════════════════════════════════════════════13
"Wireworld" repeated itself 2 times, the program is stopping.
</pre>
=={{header|RISC-V Assembly}}==
<syntaxhighlight lang="risc-v">
/* gnu assembler syntax */
wireworld:
/* unsigned int width (a0) */
/* unsigned int height (a1) */
/* char* grid (a2) */
mv a4,a2
li t4,'. /* conductor */
li t5,'H /* head */
li t6,'t /* tail */
addi t2,a0,-1
addi t3,a1,-1
mv t1,zero
.yloop: /* outer loop (y) */
mv t0,zero
.xloop: /* inner loop (x) */
lb a5,0(a4)
bgt a5,t4,.torh
blt a5,t4,.empty
/* conductor: */
/* unsigned int head_count (a3) */
/* char* test_ptr (a6) */
/* char test (a7) */
mv a3,zero
sub a6,a4,a0
addi a6,a6,-1
0: beq t1,zero,1f /* bounds up */
beq t0,zero,0f /* bounds left */
lb a7,0(a6)
bne a7,t6,0f
addi a3,a3,1
0: lb a7,1(a6)
bne a7,t6,0f
addi a3,a3,1
0: beq t0,t2,0f /* bounds right */
lb a7,2(a6)
bne a7,t6,0f
addi a3,a3,1
0:1: add a6,a6,a0
beq t0,zero,0f /* bounds left */
lb a7,0(a6)
bne a7,t6,0f
addi a3,a3,1
0: beq t0,t2,0f /* bounds right */
lb a7,2(a6)
bne a7,t5,0f
addi a3,a3,1
0: add a6,a6,a0
beq t1,t3,1f /* bounds down */
beq t0,zero,0f /* bounds left */
lb a7,0(a6)
bne a7,t5,0f
addi a3,a3,1
0: lb a7,1(a6)
bne a7,t5,0f
addi a3,a3,1
0: beq t0,t2,0f /* bounds right */
lb a7,2(a6)
bne a7,t5,0f
addi a3,a3,1
0:1: beq a3,zero,.empty
addi a3,a3,-2
bgt a3,zero,.empty
mv a5,t5 /* convert conductor to electron head */
j .save
.torh: beq a5,t6,.tail
.head: mv a5,t6
j .save
.tail: mv a5,t4
.save: sb a5,0(a4)
.empty: /* do nothing */
/* end x-loop */
addi a4,a4,1
addi t0,t0,1
bne t0,a0,.xloop
/* end y-loop */
addi t1,t1,1
bne t1,a1,.yloop
ret
</syntaxhighlight>
For output, compile the above to an object file and link against the following program:
<syntaxhighlight lang="c">
#include <stdio.h>
#include <string.h>
char init[] = " tH....tH "
" . ...... "
" ........ . "
" .. .... .. .. .. "
".. ... . ..tH....tH... .tH..... ....tH.. .tH."
" .. .... .. .. .. "
" tH...... . "
" . ....tH "
" ...Ht... ";
int width = 60;
int height = 9;
void wireworld(unsigned int, unsigned int, char *);
int main() {
char tmp[width + 1] = {};
do {
for (int i = 0; i < height; i++) {
strncpy(tmp, init + i * width, width);
puts(tmp);
}
wireworld(width, height, init);
} while (getchar());
return 0;
}
</syntaxhighlight>
Example output:
<pre style="height:60ex">
tH....tH
. ......
........ .
.. .... .. .. ..
.. ... . ..tH....tH... .tH..... ....tH.. .tH.
.. .... .. .. ..
tH...... .
. ....tH
...Ht...
.tH....t
. H.....
........ .
.. .... .. .. ..
.. ... . ...tH....tH.. ..tH.... .....tH. ..tH
.. .... .. .. ..
.tH..... H
. .....t
..Ht....
..tH....
. tH....
.......H .
.. .... .. .. H.
.. ... . ....tH....tH. ...tH... ......tH ...t
.. HHH. .. .. H.
..tH.... t
. ......
.Ht.....
...tH...
. .tH...
......Ht .
.. .... H. .. tH
.. ... H H....tH....tH ....tH.. .......t ....
.. tttH H. .. tH
...tH... .
. ......
Ht......
....tH..
. ..tH..
.....Ht. .
.. HHHH tH .. .t
.. ... t tH....tH....t .....tH. ........ H...
.. ...t tH .. .t
....tH.. .
H ......
t.......
.....tH.
. ...tH.
....Ht.. .
.. tttt .t H. ..
.. ... . .tH....tH.... H.....tH ........ tH..
.. .... .t H. ..
H....tH. .
t ......
........
......tH
. ....tH
...Ht... .
.. .... .. tH ..
.. ... . ..tH....tH... tH.....t ........ .tH.
.. .... .. tH ..
tH....tH .
. ......
........
.......t
. H....t
..Ht.... H
.. .... .. .t ..
.. ... . ...tH....tH.. .tH..... H....... ..tH
.. .... .. .t ..
.tH....t .
. H.....
........
........
. tH....
.Ht....H t
.. HHH. .. .. ..
.. ... . ....tH....tH. ..tH.... tH...... ...t
.. .... .. .. ..
..tH.... .
. tH....
.......H
........
. .tH...
Ht....Ht .
.. tttH H. .. ..
.. ... H H....tH....tH ...tH... .tH..... ....
.. .... H. .. ..
...tH... .
. .tH...
......Ht
........
H ..tH..
t....Ht. .
.. ...t tH .. ..
.. ... t tH....tH....t ....tH.. ..tH.... ....
.. HHHH tH .. ..
....tH.. .
. ..tH..
.....Ht.
H.......
t ...tH.
....Ht.. .
.. .... .t .. ..
.. ... . .tH....tH.... H....tH. ...tH... ....
.. tttt .t .. ..
.....tH. .
. ...tH.
....Ht..
tH......
. ....tH
...Ht... .
.. .... .. H. ..
.. ... . ..tH....tH... tH....tH ....tH.. ....
.. .... .. H. ..
......tH .
. ....tH
...Ht...
.tH.....
. .....t
..Ht.... H
.. .... .. tH ..
.. ... . ...tH....tH.. .tH....t .....tH. ....
.. .... .. tH ..
.......t H
. H....t
..Ht....
..tH....
. ......
.Ht..... t
.. HHH. .. .t H.
.. ... . ....tH....tH. ..tH.... H.....tH ....
.. HHH. .. .t H.
........ t
. tH....
.Ht....H
...tH...
. ......
Ht...... .
.. tttH H. .. tH
.. ... . H....tH....tH ...tH... tH.....t ....
.. tttH H. .. tH
........ .
. .tH...
Ht....Ht
....tH..
H ......
t....... .
.. ...t tH .. .t
.. ... . t.....tH....t ....tH.. .tH..... H...
.. ...t tH .. .t
........ .
H ..tH..
t....Ht.
H....tH.
t ......
........ .
.. .... .t .. ..
.. ... . .......tH.... H....tH. ..tH.... tH..
.. .... .t .. ..
H....... .
t ...tH.
....Ht..
tH....tH
. ......
........ .
.. .... .. H. ..
.. ... . ........tH... tH....tH ...tH... .tH.
.. .... .. H. ..
tH...... .
. ....tH
...Ht...
.tH....t
. H.....
........ .
.. .... .. tH ..
.. ... . .........tH.. .tH....t ....tH.. ..tH
.. .... .. tH ..
.tH..... H
. .....t
..Ht....
</pre>
=={{header|Ruby}}==
See: [[Wireworld/Ruby]]
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::str::FromStr;
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum State {
Empty,
Conductor,
ElectronTail,
ElectronHead,
}
impl State {
fn next(&self, e_nearby: usize) -> State {
match self {
State::Empty => State::Empty,
State::Conductor => {
if e_nearby == 1 || e_nearby == 2 {
State::ElectronHead
} else {
State::Conductor
}
}
State::ElectronTail => State::Conductor,
State::ElectronHead => State::ElectronTail,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WireWorld {
pub width: usize,
pub height: usize,
pub data: Vec<State>,
}
impl WireWorld {
pub fn new(width: usize, height: usize) -> Self {
WireWorld {
width,
height,
data: vec![State::Empty; width * height],
}
}
pub fn get(&self, x: usize, y: usize) -> Option<State> {
if x >= self.width || y >= self.height {
None
} else {
self.data.get(y * self.width + x).copied()
}
}
pub fn set(&mut self, x: usize, y: usize, state: State) {
self.data[y * self.width + x] = state;
}
fn neighbors<F>(&self, x: usize, y: usize, mut f: F) -> usize
where F: FnMut(State) -> bool
{
let (x, y) = (x as i32, y as i32);
let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)];
neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count()
}
pub fn next(&mut self) {
let mut next_state = vec![];
for y in 0..self.height {
for x in 0..self.width {
let e_count = self.neighbors(x, y, |e| e == State::ElectronHead);
next_state.push(self.get(x, y).unwrap().next(e_count));
}
}
self.data = next_state;
}
}
impl FromStr for WireWorld {
type Err = ();
fn from_str(s: &str) -> Result<WireWorld, ()> {
let s = s.trim();
let height = s.lines().count();
let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0);
let mut world = WireWorld::new(width, height);
for (y, line) in s.lines().enumerate() {
for (x, ch) in line.trim_end().chars().enumerate() {
let state = match ch {
'.' => State::Conductor,
't' => State::ElectronTail,
'H' => State::ElectronHead,
_ => State::Empty,
};
world.set(x, y, state);
}
}
Ok(world)
}
}</syntaxhighlight>
graphical output using winit 0.24 and pixels 0.2
<syntaxhighlight lang="rust">use pixels::{Pixels, SurfaceTexture};
use winit::event::*;
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
use std::{env, fs};
mod wireworld;
use wireworld::{State, WireWorld};
const EMPTY_COLOR: [u8; 3] = [0x00, 0x00, 0x00];
const WIRE_COLOR: [u8; 3] = [0xFC, 0xF9, 0xF8];
const HEAD_COLOR: [u8; 3] = [0xFC, 0x00, 0x00];
const TAIL_COLOR: [u8; 3] = [0xFC, 0x99, 0x33];
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
eprintln!("Error: No Input File");
std::process::exit(1);
}
let input_file = fs::read_to_string(&args[1]).unwrap();
let mut world: WireWorld = input_file.parse().unwrap();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title(format!("Wireworld - {}", args[1]))
.build(&event_loop).unwrap();
let size = window.inner_size();
let texture = SurfaceTexture::new(size.width, size.height, &window);
let mut image_buffer = Pixels::new(world.width as u32, world.height as u32, texture).unwrap();
event_loop.run(move |ev, _, flow| {
match ev {
Event::WindowEvent {
event: WindowEvent::CloseRequested, ..
} => {
*flow = ControlFlow::Exit;
}
Event::WindowEvent {
event: WindowEvent::KeyboardInput {
input: KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Space),
..
}, ..
}, ..
} => {
world.next();
window.request_redraw();
}
Event::RedrawRequested(_) => {
let frame = image_buffer.get_frame();
for (pixel, state) in frame.chunks_exact_mut(4).zip(world.data.iter()) {
let color = match state {
State::Empty => EMPTY_COLOR,
State::Conductor => WIRE_COLOR,
State::ElectronTail => TAIL_COLOR,
State::ElectronHead => HEAD_COLOR,
};
pixel[0] = color[0]; // R
pixel[1] = color[1]; // G
pixel[2] = color[2]; // B
pixel[3] = 0xFF; // A
}
image_buffer.render().unwrap();
}
_ => {}
}
});
}</syntaxhighlight>
=={{header|Sidef}}==
{{trans|Perl}}
<
10.times {
say f.map { .join(" ") + "\n" }.join
var a = [[]]
for y in (1 ..^ f.end
var r = f[y]
var rr = ['']
for x in (1 ..^ r.end
var c = r[x]
rr << (
given(c) {
when('H') { 't' }
when('t') { '.' }
when('.') { <. H>[[f
default { c }
}
)
}
rr << ''
a << rr
}
f = [a..., []]
}
Line 4,791 ⟶ 6,388:
...
. .
Ht.. ......</
=={{header|Smalltalk}}==
See: [[Wireworld/Smalltalk]]
=={{header|Standard ML}}==
<
type world = char vector vector
Line 4,839 ⟶ 6,439:
" ... ",
". . ",
"Ht.. ......"]</
=={{header|Tcl}}==
Line 4,852 ⟶ 6,449:
to construct a two dimensional 3 by 3 sliding window.
The rule function maps a pair (cell,neighborhood) to a new cell.
<
rule = case~&l\~&l {`H: `t!, `t: `.!,`.: @r ==`H*~; {'H','HH'}?</`H! `.!}
Line 4,858 ⟶ 6,455:
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
evolve "n" = @iNC ~&x+ rep"n" ^C\~& rule**+ neighborhoods@h</
test program:
<
<
Line 4,869 ⟶ 6,466:
#show+
example = mat0 evolve13 diode</
{{out}}
<pre style="height:15ex;overflow:scroll">
Line 4,927 ⟶ 6,524:
......... ...
..
</pre>
=={{header|Wren}}==
{{trans|Go}}
{{libheader|wren-fmt}}
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./ioutil" for FileUtil, Stdin
var rows = 0 // extent of input configuration
var cols = 0 // """
var rx = 0 // grid extent (includes border)
var cx = 0 // """
var mn = [] // offsets of Moore neighborhood
var print = Fn.new { |grid|
System.print("__" * cols)
System.print()
for (r in 1..rows) {
for (c in 1..cols) Fmt.write(" $s", grid[r*cx+c])
System.print()
}
}
var step = Fn.new { |dst, src|
for (r in 1..rows) {
for (c in 1..cols) {
var x = r*cx + c
dst[x] = src[x]
if (dst[x] == "H") {
dst[x] = "t"
} else if (dst[x] == "t") {
dst[x] = "."
} else if (dst[x] == ".") {
var nn = 0
for (n in mn) {
if (src[x+n] == "H") nn = nn + 1
}
if (nn == 1 || nn == 2) dst[x] = "H"
}
}
}
}
var srcRows = FileUtil.readLines("ww.config")
rows = srcRows.count
for (r in srcRows) {
if (r.count > cols) cols = r.count
}
rx = rows + 2
cx = cols + 2
mn = [-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1]
// allocate two grids and copy input into first grid
var odd = List.filled(rx*cx, " ")
var even = List.filled(rx*cx, " ")
var ri = 0
for (r in srcRows) {
for (i in 0...r.count) {
odd[(ri+1)*cx+1+i] = r[i]
}
ri = ri + 1
}
// run
while (true) {
print.call(odd)
step.call(even, odd)
Stdin.readLine() // wait for enter to be pressed
print.call(even)
step.call(odd, even)
Stdin.readLine() // ditto
}</syntaxhighlight>
{{out}}
<pre>
Although not shown, same as Go output.
</pre>
=={{header|XPL0}}==
[[File:WireXPL0.gif|right]]
<
char New(53,40), Old(53,40);
Line 4,978 ⟶ 6,654:
until KeyHit; \keystroke terminates program
SetVid(3); \restore normal text mode
]</
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">open window 230,130
backcolor 0,0,0
clear window
label circuit
DATA " "
DATA " tH......... "
DATA " . . "
DATA " ... "
DATA " . . "
DATA " Ht.. ...... "
DATA " "
DATA ""
do
read a$
if a$ = "" break
n = n + 1
redim t$(n)
t$(n) = a$+a$
loop
size = len(t$(1))/2
E2 = size
first = true
Orig = 0
Dest = E2
do
for y = 2 to n-1
for x = 2 to E2-1
switch mid$(t$(y),x+Orig,1)
case " ": color 32,32,32 : mid$(t$(y),x+Dest,1) = " " : break
case "H": color 0,0,255 : mid$(t$(y),x+Dest,1) = "t" : break
case "t": color 255,0,0 : mid$(t$(y),x+Dest,1) = "." : break
case ".":
color 255,200,0
t = 0
for y1 = y-1 to y+1
for x1 = x-1 to x+1
t = t + ("H" = mid$(t$(y1),x1+Orig,1))
next x1
next y1
if t=1 or t=2 then
mid$(t$(y),x+Dest,1) = "H"
else
mid$(t$(y),x+Dest,1) = "."
end if
end switch
fill circle x*16, y*16, 8
next x
print t$(y),"="
next y
first = not first
if first then
Orig = 0 : Dest = E2
else
Orig = E2 : Dest = 0
end if
wait .5
loop
</syntaxhighlight>
|