Wireworld: Difference between revisions

97,663 bytes added ,  3 months ago
m
m (→‎{{header|Sidef}}: minor code simplifications)
m (→‎{{header|Wren}}: Minor tidy)
(45 intermediate revisions by 25 users not shown)
Line 1:
{{task|Games}} [[Category:Cellular automata]]
[[Category:Cellular automata]]
{{omit from|GUISS}}
 
[[wp:Wireworld|Wireworld]] is a cellular automaton with some similarities to [[Conway's Game of Life]].
 
Line 7 ⟶ 9:
and is much simpler to program for.
 
A wireworldWireworld arena consists of a cartesianCartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneously.
 
The cell transition rules are this:
::{| class=wikitable
|-
! Input State
Line 39 ⟶ 41:
|}
 
 
To implement this task, create a program that reads a wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "<tt>H</tt>" for an electron head, "<tt>t</tt>" for a tail, "<tt>.</tt>" for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
;Task:
Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "<tt>H</tt>" for an electron head, "<tt>t</tt>" for a tail, "<tt>.</tt>" for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:
<pre>
tH.........
Line 49 ⟶ 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}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Wireworld is
Line 116 ⟶ 273:
Wireworld (Oscillator);
end loop;
end Test_Wireworld;</langsyntaxhighlight>
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 166 ⟶ 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}}
<langsyntaxhighlight lang="algol68">CO
Wireworld implementation.
CO
Line 287 ⟶ 444:
print ( world2string(ww) );
ww := next gen(ww)
OD</langsyntaxhighlight>
{{out}}
<pre style="height:45ex;overflow:scroll">
Line 365 ⟶ 522:
{{works with|AutoHotkey_L}}
{{libheader|GDIP}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">#SingleInstance, Force
#NoEnv
SetBatchLines, -1
Line 471 ⟶ 628:
Exit:
Gdip_Shutdown(pToken)
ExitApp</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
<langsyntaxhighlight lang="autoit">
$ww = ""
$ww &= "tH........." & @CR
Line 578 ⟶ 735:
WEnd
EndFunc ;==>Wireworld
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
[[Image:wireworld_bbc.gif|right]]
<langsyntaxhighlight lang="bbcbasic"> Size% = 20
DIM P&(Size%-1,Size%-1), Q&(Size%-1,Size%-1)
Line 624 ⟶ 781:
SWAP P&(), Q&()
WAIT 50
UNTIL FALSE</langsyntaxhighlight>
 
=={{header|C}}==
Line 638 ⟶ 795:
Compile with <code>-D_POSIX_C_SOURCE=199309L</code> or greater to make <code>nanosleep</code> visible in <code><time.h></code>.
 
<langsyntaxhighlight lang="c">/* 2009-09-27 <kaz@kylheku.com> */
#define ANIMATE_VT100_POSIX
#include <stdio.h>
Line 699 ⟶ 856:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
See: [[Wireworld/C sharp]]
 
=={{header|C++}}==
Line 706 ⟶ 866:
{{libheader|POSIX}} (for usleep)
 
<langsyntaxhighlight lang="cpp">#include <ggi/ggi.h>
#include <set>
#include <map>
Line 951 ⟶ 1,111:
}
std::cout << std::endl;
}</langsyntaxhighlight>
 
=={{header|C sharpCeylon}}==
<syntaxhighlight lang="ceylon">abstract class Cell(shared Character char) of emptyCell | head | tail | conductor {
See: [[Wireworld/C sharp]]
 
shared Cell output({Cell*} neighbors) =>
switch (this)
case (emptyCell) emptyCell
case (head) tail
case (tail) conductor
case (conductor) (neighbors.count(head.equals) in 1..2 then head else conductor);
 
string => char.string;
}
 
object emptyCell extends Cell(' ') {}
 
object head extends Cell('H') {}
 
object tail extends Cell('t') {}
 
object conductor extends Cell('.') {}
 
Map<Character,Cell> cellsByChar = map { for (cell in `Cell`.caseValues) cell.char->cell };
 
class Wireworld(String data) {
 
value lines = data.lines;
 
value width = max(lines*.size);
value height = lines.size;
 
function toIndex(Integer x, Integer y) => x + y * width;
 
variable value currentState = Array.ofSize(width * height, emptyCell);
variable value nextState = Array.ofSize(width * height, emptyCell);
 
for (j->line in lines.indexed) {
for (i->char in line.indexed) {
currentState[toIndex(i, j)] = cellsByChar[char] else emptyCell;
}
}
 
value emptyGrid = Array.ofSize(width * height, emptyCell);
void clear(Array<Cell> cells) => emptyGrid.copyTo(cells);
 
shared void update() {
clear(nextState);
for(j in 0:height) {
for(i in 0:width) {
if(exists cell = currentState[toIndex(i, j)]) {
value nextCell = cell.output(neighborhood(currentState, i, j));
nextState[toIndex(i, j)] = nextCell;
}
}
}
value temp = currentState;
currentState = nextState;
nextState = temp;
}
 
shared void display() {
for (row in currentState.partition(width)) {
print("".join(row));
}
}
 
shared {Cell*} neighborhood(Array<Cell> grid, Integer x, Integer y) => {
for (j in y - 1..y + 1)
for (i in x - 1..x + 1)
if(i in 0:width && j in 0:height)
grid[toIndex(i, j)]
}.coalesced;
 
}
 
shared void run() {
value data = "tH.........
. .
...
. .
Ht.. ......";
 
value world = Wireworld(data);
 
variable value generation = 0;
 
void display() {
print("generation: ``generation``");
world.display();
}
 
display();
 
while (true) {
if (exists input = process.readLine(), input.lowercased == "q") {
return;
}
world.update();
generation++;
display();
 
}
}
</syntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun electron-neighbors (wireworld row col)
(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,022 ⟶ 1,283:
" ... "
". . "
"Ht.. ......")))</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">CL-USER> (wireworld-show-gens (make-rosetta-wireworld) 12)
Line 1,099 ⟶ 1,360:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void wireworldStep(char[][] W1, char[][] W2) pure nothrow @safe @nogc {
Line 1,136 ⟶ 1,397:
swap(world, world2);
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,173 ⟶ 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}}
<langsyntaxhighlight lang="elixir">defmodule Wireworld do
@empty " "
@head "H"
Line 1,259 ⟶ 2,016:
"""
Wireworld.run(text)</langsyntaxhighlight>
 
{{out}}
Line 1,530 ⟶ 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}}==
<langsyntaxhighlight lang="forth">16 constant w
8 constant h
 
Line 1,611 ⟶ 2,489:
: gen ['] newrow foreachrow age ;
 
: wireworld begin gen 0 0 at-xy show key? until ;</langsyntaxhighlight>
 
{{out}}
Line 1,736 ⟶ 2,614:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Wireworld
implicit none
Line 1,820 ⟶ 2,698:
end do
end subroutine Nextgen
end program Wireworld</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">Generation 0
Line 1,912 ⟶ 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.
<syntaxhighlight lang="gml">//Create event
/*
Wireworld first declares constants and then reads a wireworld from a textfile.
In order to implement wireworld in GML a single array is used.
To make it behave properly, there need to be states that are 'in-between' two states:
0 = empty
1 = conductor from previous state
2 = electronhead from previous state
5 = electronhead that was a conductor in the previous state
3 = electrontail from previous state
4 = electrontail that was a head in the previous state
*/
empty = 0;
conduc = 1;
eHead = 2;
eTail = 3;
eHead_to_eTail = 4;
coduc_to_eHead = 5;
working = true;//not currently used, but setting it to false stops wireworld. (can be used to pause)
toroidalMode = false;
factor = 3;//this is used for the display. 3 means a single pixel is multiplied by three in size.
 
var tempx,tempy ,fileid, tempstring, gridid, listid, maxwidth, stringlength;
tempx = 0;
tempy = 0;
tempstring = "";
maxwidth = 0;
 
//the next piece of code loads the textfile containing a wireworld.
//the program will not work correctly if there is no textfile.
if file_exists("WW.txt")
{
fileid = file_text_open_read("WW.txt");
gridid = ds_grid_create(0,0);
listid = ds_list_create();
while !file_text_eof(fileid)
{
tempstring = file_text_read_string(fileid);
stringlength = string_length(tempstring);
ds_list_add(listid,stringlength);
if maxwidth < stringlength
{
ds_grid_resize(gridid,stringlength,ds_grid_height(gridid) + 1)
maxwidth = stringlength
}
else
{
ds_grid_resize(gridid,maxwidth,ds_grid_height(gridid) + 1)
}
for (i = 1; i <= stringlength; i +=1)
{
switch (string_char_at(tempstring,i))
{
case ' ': ds_grid_set(gridid,tempx,tempy,empty); break;
case '.': ds_grid_set(gridid,tempx,tempy,conduc); break;
case 'H': ds_grid_set(gridid,tempx,tempy,eHead); break;
case 't': ds_grid_set(gridid,tempx,tempy,eTail); break;
default: break;
}
tempx += 1;
}
file_text_readln(fileid);
tempy += 1;
tempx = 0;
}
file_text_close(fileid);
//fill the 'open' parts of the grid
tempy = 0;
repeat(ds_list_size(listid))
{
tempx = ds_list_find_value(listid,tempy);
repeat(maxwidth - tempx)
{
ds_grid_set(gridid,tempx,tempy,empty);
tempx += 1;
}
tempy += 1;
}
boardwidth = ds_grid_width(gridid);
boardheight = ds_grid_height(gridid);
//the contents of the grid are put in a array, because arrays are faster.
//the grid was needed because arrays cannot be resized properly.
tempx = 0;
tempy = 0;
repeat(boardheight)
{
repeat(boardwidth)
{
board[tempx,tempy] = ds_grid_get(gridid,tempx,tempy);
tempx += 1;
}
tempy += 1;
tempx = 0;
}
//the following code clears memory
ds_grid_destroy(gridid);
ds_list_destroy(listid);
}</syntaxhighlight>
Now the step event
<syntaxhighlight lang="gml">
//Step event
/*
This step event executes each 1/speed seconds.
It checks everything on the board using an x and a y through two repeat loops.
The variables westN,northN,eastN,southN, resemble the space left, up, right and down respectively,
seen from the current x & y.
1 -> 5 (conductor is changing to head)
2 -> 4 (head is changing to tail)
3 -> 1 (tail became conductor)
*/
 
var tempx,tempy,assignhold,westN,northN,eastN,southN,neighbouringHeads,T;
tempx = 0;
tempy = 0;
westN = 0;
northN = 0;
eastN = 0;
southN = 0;
neighbouringHeads = 0;
T = 0;
 
if working = 1
{
repeat(boardheight)
{
repeat(boardwidth)
{
switch board[tempx,tempy]
{
case empty: assignhold = empty; break;
case conduc:
neighbouringHeads = 0;
if toroidalMode = true //this is disabled, but otherwise lets wireworld behave toroidal.
{
if tempx=0
{
westN = boardwidth -1;
}
else
{
westN = tempx-1;
}
if tempy=0
{
northN = boardheight -1;
}
else
{
northN = tempy-1;
}
if tempx=boardwidth -1
{
eastN = 0;
}
else
{
eastN = tempx+1;
}
if tempy=boardheight -1
{
southN = 0;
}
else
{
southN = tempy+1;
}
 
T=board[westN,northN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[tempx,northN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[eastN,northN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[westN,tempy];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[eastN,tempy];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[westN,southN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[tempx,southN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
T=board[eastN,southN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
else//this is the default mode that works for the provided example.
{//the next code checks whether coordinates fall outside the array borders.
//and counts all the neighbouring electronheads.
if tempx=0
{
westN = -1;
}
else
{
westN = tempx - 1;
T=board[westN,tempy];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if tempy=0
{
northN = -1;
}
else
{
northN = tempy - 1;
T=board[tempx,northN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if tempx = boardwidth -1
{
eastN = -1;
}
else
{
eastN = tempx + 1;
T=board[eastN,tempy];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if tempy = boardheight -1
{
southN = -1;
}
else
{
southN = tempy + 1;
T=board[tempx,southN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if westN != -1 and northN != -1
{
T=board[westN,northN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if eastN != -1 and northN != -1
{
T=board[eastN,northN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if westN != -1 and southN != -1
{
T=board[westN,southN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
if eastN != -1 and southN != -1
{
T=board[eastN,southN];
if T=eHead or T=eHead_to_eTail
{
neighbouringHeads += 1;
}
}
}
if neighbouringHeads = 1 or neighbouringHeads = 2
{
assignhold = coduc_to_eHead;
}
else
{
assignhold = conduc;
}
break;
case eHead: assignhold = eHead_to_eTail; break;
case eTail: assignhold = conduc; break;
default: break;
}
board[tempx,tempy] = assignhold;
tempx += 1;
}
tempy += 1;
tempx = 0;
}
}
</syntaxhighlight>
Now the draw event
<syntaxhighlight lang="gml">
//Draw event
/*
This event occurs whenever the screen is refreshed.
It checks everything on the board using an x and a y through two repeat loops and draws it.
It is an important step, because all board values are changed to the normal versions:
5 -> 2 (conductor changed to head)
4 -> 3 (head changed to tail)
*/
//draw sprites and text first
 
//now draw wireworld
var tempx,tempy;
tempx = 0;
tempy = 0;
 
repeat(boardheight)
{
repeat(boardwidth)
{
switch board[tempx,tempy]
{
case empty:
//draw_point_color(tempx,tempy,c_black);
draw_set_color(c_black);
draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);
break;
case conduc:
//draw_point_color(tempx,tempy,c_yellow);
draw_set_color(c_yellow);
draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);
break;
case eHead:
//draw_point_color(tempx,tempy,c_red);
draw_set_color(c_blue);
draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);
draw_rectangle_color(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,c_red,c_red,c_red,c_red,false);
break;
case eTail:
//draw_point_color(tempx,tempy,c_blue);
draw_set_color(c_red);
draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);
break;
case coduc_to_eHead:
//draw_point_color(tempx,tempy,c_red);
draw_set_color(c_blue);
draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);
board[tempx,tempy] = eHead;
break;
case eHead_to_eTail:
//draw_point_color(tempx,tempy,c_blue);
draw_set_color(c_red);
draw_rectangle(tempx*factor,tempy*factor,(tempx+1)*factor-1,(tempy+1)*factor-1,false);
board[tempx,tempy] = eTail;
break;
default: break;
}
tempx += 1
}
tempy += 1;
tempx = 0;
}
draw_set_color(c_black);
</syntaxhighlight>
 
=={{header|Go}}==
Text output. Press Enter to compute and display successive generations.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,004 ⟶ 3,342:
}
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.List
import Control.Monad
import Control.Arrow
Line 2,027 ⟶ 3,365:
noH = length $ filter (=='H') $ concat xs
 
runCircuit = iterate (map(map nwState).take3x3)</langsyntaxhighlight>
Example executed in GHCi:
<langsyntaxhighlight Haskelllang="haskell">oscillator= [" tH ",
". ....",
" .. "
]
 
example = mapM_ (mapM_ putStrLn) .map (borden ' ').take 9 $ runCircuit oscillator</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 2,090 ⟶ 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.
<langsyntaxhighlight Iconlang="icon">link graphics
 
$define EDGE -1
Line 2,181 ⟶ 3,519:
}
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 2,187 ⟶ 3,525:
 
=={{header|J}}==
The example circuit:<langsyntaxhighlight Jlang="j">circ0=:}: ] ;. _1 LF, 0 : 0
tH........
. .
Line 2,193 ⟶ 3,531:
. .
Ht.. .....
)</langsyntaxhighlight>
A 'boarding' verb board and the next cell state verb nwS:
<langsyntaxhighlight Jlang="j">board=: ' ' ,.~ ' ' ,. ' ' , ' ' ,~ ]
 
nwS=: 3 : 0
Line 2,201 ⟶ 3,539:
if. ('.'=e)*. e.&1 2 +/'H'=,y do. 'H' return. end.
' t..' {~ ' Ht.' i. e
)</langsyntaxhighlight>
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.
<langsyntaxhighlight Jlang="j"> process=: (3 3 nwS;. _3 board)^:
(<10) process circuit</langsyntaxhighlight>
Example run:
<pre style="height:30ex;overflow:scroll">
Line 2,271 ⟶ 3,609:
Note also that a graphical presentation can be achieved using viewmat. For example:
 
<langsyntaxhighlight lang="j">require'viewmat'
viewmat"2 ' .tH'i. (<10) process circ0</langsyntaxhighlight>
 
(This example opens 10 windows, one for each generation.)
Line 2,278 ⟶ 3,616:
=={{header|Java}}==
See: [[Wireworld/Java]]
 
=={{header|JavaScript}}==
You have to search and open the file manually.<br />
This is the HTML you need to test.
<pre>
<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>Wireworld</title>
<script src="wireworld.js"></script></head><body>
<input type='file' accept='text/plain' onchange='openFile( event )' />
<br /></body></html></pre>
<syntaxhighlight lang="javascript">
var ctx, sizeW, sizeH, scl = 10, map, tmp;
function getNeighbour( i, j ) {
var ii, jj, c = 0;
for( var b = -1; b < 2; b++ ) {
for( var a = -1; a < 2; a++ ) {
ii = i + a; jj = j + b;
if( ii < 0 || ii >= sizeW || jj < 0 || jj >= sizeH ) continue;
if( map[ii][jj] == 1 ) c++;
}
}
return ( c == 1 || c == 2 );
}
function simulate() {
drawWorld();
for( var j = 0; j < sizeH; j++ ) {
for( var i = 0; i < sizeW; i++ ) {
switch( map[i][j] ) {
case 0: tmp[i][j] = 0; break;
case 1: tmp[i][j] = 2; break;
case 2: tmp[i][j] = 3; break;
case 3:
if( getNeighbour( i, j ) ) tmp[i][j] = 1;
else tmp[i][j] = 3;
break;
}
}
}
[tmp, map] = [map, tmp];
setTimeout( simulate, 200 );
}
function drawWorld() {
ctx.fillStyle = "#000"; ctx.fillRect( 0, 0, sizeW * scl, sizeH * scl );
for( var j = 0; j < sizeH; j++ ) {
for( var i = 0; i < sizeW; i++ ) {
switch( map[i][j] ) {
case 0: continue;
case 1: ctx.fillStyle = "#03f"; break;
case 2: ctx.fillStyle = "#f30"; break;
case 3: ctx.fillStyle = "#ff3"; break;
}
ctx.fillRect( i, j, 1, 1 );
}
}
}
function openFile( event ) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
createWorld( reader.result );
};
reader.readAsText(input.files[0]);
}
function createWorld( txt ) {
var l = txt.split( "\n" );
sizeW = parseInt( l[0] );
sizeH = parseInt( l[1] );
map = new Array( sizeW );
tmp = new Array( sizeW );
for( var i = 0; i < sizeW; i++ ) {
map[i] = new Array( sizeH );
tmp[i] = new Array( sizeH );
for( var j = 0; j < sizeH; j++ ) {
map[i][j] = tmp[i][j] = 0;
}
}
var t;
for( var j = 0; j < sizeH; j++ ) {
for( var i = 0; i < sizeW; i++ ) {
switch( l[j + 2][i] ) {
case " ": t = 0; break;
case "H": t = 1; break;
case "t": t = 2; break;
case ".": t = 3; break;
}
map[i][j] = t;
}
}
init();
}
function init() {
var canvas = document.createElement( "canvas" );
canvas.width = sizeW * scl;
canvas.height = sizeH * scl;
ctx = canvas.getContext( "2d" );
ctx.scale( scl, scl );
document.body.appendChild( canvas );
simulate();
}
</syntaxhighlight>
 
=={{header|jq}}==
Line 2,289 ⟶ 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.
<langsyntaxhighlight lang="jq">def lines: split("\n")|length;
 
def cols: split("\n")[0]|length + 1; # allow for the newline
Line 2,325 ⟶ 3,763:
$world | evolve($i; $w) as $next
| if .[$i] == $next then . else .[$i] = $next end )
| [., $lines, $w] ; # </langsyntaxhighlight>
'''Animation'''
<langsyntaxhighlight lang="jq"># "clear screen":
def cls: "\u001b[2J";
 
Line 2,352 ⟶ 3,790:
 
# Input: a string representing the initial state
def frames(n): animation(n; -1);#</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">def world11:
"+-----------+\n" +
"|tH.........|\n" +
Line 2,368 ⟶ 3,806:
" . .... \n" +
" .. \n" +
" \n" ;</langsyntaxhighlight>
'''Illustration 1''':
<langsyntaxhighlight lang="jq"># Ten-step animation with about 1 sec between frames
world9 | animation(10; 1000)</langsyntaxhighlight>
'''Illustration 2''':
<langsyntaxhighlight lang="jq"># Ten frames in sequence:
world11 | frames(10)</langsyntaxhighlight>
 
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">
<lang lb>
WindowWidth = 840
WindowHeight = 600
Line 2,510 ⟶ 4,047:
timer 1000, [tmr]
wait
</syntaxhighlight>
</lang>
 
=={{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.)
<langsyntaxhighlight Logolang="logo">to wireworld :filename :speed ;speed in n times per second, approximated
Make "speed 60/:speed
wireworldread :filename
Line 2,582 ⟶ 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</langsyntaxhighlight>
 
=={{header|MathematicaLua}}==
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.
<lang Mathematica>DynamicModule[{data =
<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 2,598 ⟶ 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}]]</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight lang="nim">import strutils, os
 
var world, world2 = """
Line 2,612 ⟶ 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 2,637 ⟶ 4,351:
 
world2.next(world, w)
swap world, world2</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let w = [|
" ......tH ";
" . ...... ";
Line 2,696 ⟶ 4,410:
aux n
in
aux w</langsyntaxhighlight>
 
=={{header|Oz}}==
Includes a simple animation, using a text widget.
<langsyntaxhighlight lang="oz">declare
Rules =
[rule(& & )
Line 2,791 ⟶ 4,505:
{Field set(text:{ShowArena Gi})}
{Delay 500}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">\\ 0 = conductor, 1 = tail, 2 = head, 3 = empty
wireworldStep(M)={
my(sz=matsize(M),t);
Line 2,824 ⟶ 4,538:
)
};
animate(read("wireworld.gp"))</langsyntaxhighlight>
 
=={{header|Perl}}==
Read the initial World from stdin and print 10 steps to stdout
<langsyntaxhighlight lang="perl">my @f = ([],(map {chomp;['',( split // ),'']} <>),[]);
 
for (1 .. 10) {
Line 2,848 ⟶ 4,562:
}
@f = (@a,[]);
}</langsyntaxhighlight>
Input:
<pre>tH.........
Line 2,927 ⟶ 4,641:
</pre>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/pGUI}}
<lang perl6>class Wireworld {
{{libheader|Phix/online}}
has @.line;
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. &lt;/rant&gt;)
-- (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>
multi method new(@line) { self.new: :@line }
<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>
multi method new($str ) { self.new: $str.lines }
<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>
method gist { join "\n", @.line }
<span style="color: #004080;">sequence</span> <span style="color: #000000;">text</span>
method postcircumfix:<[ ]>($i) { @.line[$i].comb }
<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>
method neighbors($i where ^@.line, $j where ^$.line.pick.chars)
<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>
my @i = grep any(^@.line), $i «+« (-1, 0, 1);
my @j = grep any(^@.line.pick.chars), $j «+« (-1, 0, 1);
gather for @i X @j -> \i, \j {
next if [ i, j ] ~~ [ $i, $j ];
take self[i][j];
}
}
method succ {
my $succ = self.new: '' xx @.line;
for ^@.line X ^@.line.pick.chars -> $i, $j {
$succ.line[$i] ~=
do given self[$i][$j] {
when 'H' { 't' }
when 't' { '.' }
when '.' {
grep('H', self.neighbors($i, $j)) == 1|2 ?? 'H' !! '.'
}
default { ' ' }
}
}
return $succ;
}
}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">set_counts</span><span style="color: #0000FF;">()</span>
my $str =
<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>
"tH.........
<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>
Ht.. ......";
<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>
my Wireworld $world .= new: $str;
<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>
say $world++ for ^3;
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
</lang>
{{out}}
<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>
<pre>tH.........
<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>
Ht.. ......
<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>
.tH........
<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>
H .
<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>
H .
<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>
t... ......
<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>
H.tH.......
<span style="color: #000000;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">CD_YELLOW</span>
t .
<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>
t .
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
.H.. ......
<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>
</pre>
<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">
<lang PHP>
$desc = 'tH.........
. .
Line 3,095 ⟶ 4,918:
draw_world($world);
};
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
This example uses 'grid' from "lib/simul.l", which maintains a two-dimensional
structure.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(let
Line 3,135 ⟶ 4,958:
(for This Col
(=: val (: next)) ) )
(prinl) ) )</langsyntaxhighlight>
{{out}}
<pre> +---+---+---+---+---+---+---+---+---+---+---+
Line 3,178 ⟶ 5,001:
=={{header|PureBasic}}==
===Standalone version===
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#Empty
#Electron_head
Line 3,292 ⟶ 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</langsyntaxhighlight>
===Load from external source, graphical presentations===
<langsyntaxhighlight PureBasiclang="purebasic">CompilerIf #PB_Compiler_Unicode
CompilerError "The file handling in this small program is only in ASCII."
CompilerEndIf
Line 3,438 ⟶ 5,261:
EndIf
Until Event=#PB_Event_CloseWindow
EndIf</langsyntaxhighlight>
Example of data file to load
<pre>; Save as "WireWorld.txt"
Line 3,496 ⟶ 5,319:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">'''
Wireworld implementation.
'''
Line 3,565 ⟶ 5,388:
print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' )
print ( world2string(ww) )
ww = nextgen(ww)</langsyntaxhighlight>
 
{{out}}
Line 3,651 ⟶ 5,474:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(require 2htdp/universe)
Line 3,759 ⟶ 5,582:
 
(run-wire-world #:initial-state initial-list)
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="rexx">/*REXX program displays a wire world Cartesian grid of four─state cells. */
signal on halt /*handle any cell growth interruptus. */
parse arg iFID . '(' generations rows cols bare head tail wire clearScreen reps
if iFID=='' then iFID= "WIREWORLD.TXT" /*should default input file be used? */
blank bla = 'BLANK' /*the "name" for a blank. */
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 blankbla ) /*an empty cell character. used to show an empty cell.*/
clearScreen = p(clearScreen 0 ) /*1 means to clear the screen. */
head = pickChar(head 'H' ) /*pick the character for the head. */
tail = pickChar(wiretail . 't' ) /* " " " " " wiretail. */
wire = pickChar(wire . ) /* " " " " " wire. */
reps = p(reps 2 ) /*stop program if there are 2 repeats.*/
fents= max(cols, linesize() - 1,cols) /*the fence width used after displaying*/
#reps= 0; $.= bare; gens= abs(generations) /*at start, universe is new and barren.*/
gens=abs(generations) /*use for convenience (and short name).*/
/* [↓] read the input file. */
do r=1 while lines(iFID)\==0 /*keep reading until the End─Of─File. */
q= strip( linein(iFID), 'T') /*get singlea line from the input file. */
L= _=length(q); cols= max(cols, L) /*obtaincalculate themaximum lengthnumber of this (input)columns. row*/
cols=max(cols, _)do c=1 for L; $.r.c= substr(q, c, 1) /*assign the cells for the R row. /*calculate the maximum number of cols.*/
do c=1 for _; $.r.c=substr(q, c, 1); end /*assign the row cells.c*/
end end /*r*/
rows!.=r-1 0; signal on halt /*adjustinitial thestate rowof numbercells; (from DOhandle loop)halt.*/
liferows=0; r - 1; !.life= 0; call showCells /*display initial state of the cells. */
/*watch cells evolve, 4 possible states*/
do life=1 for gens; @.=bare bare /*perform for the number of generations*/
 
do r=1 for rows /*process each of the rows. */
do c=1 for cols; ?= $.r.c; ??=? ? /* " " " " columns. */
select /*determine the type of cell. */
when ?==head then ??= tail
when ?==tail then ??= wire
when ?==wire then do; #= n=hood(); if n#==1 | n#==2 then ??= head; end
otherwise nop
end /*select*/
@.r.c= ?? /*possible assign a cell a new state.*/
@.r.c=??
end /*c*/
end /*r*/
Line 3,806 ⟶ 5,719:
end /*life*/
/*stop watching the universe (or life).*/
halt: if life-1\==gens then say 'The ~~~Wireworld~~~───Wireworld─── program was interrupted by user.'
done: exit 0 /*stick a fork in it, we are all done.*/
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
$: 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 thisCLS for the OS.host*/
call showRows /*show rows in proper order.*/
say right( copies('═', fents)life, fents) /*display a bunchtitle offor cells. */
if _=='' then signal done then signal done /*No life? Then stop run. */
if !._ then #reps=#reps+1 then #reps= #reps + 1 /*detected repeated pattern.*/
!._= 1 /*it is now existencean extant state.*/
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 /*exitjump program,to wethis pgm'res done"exit". */</syntaxhighlight>
/*─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
$: 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
err: say; say center(' error! ',max(40,linesize()%2),"*"); say; do j=1 for arg(); say arg(j); say; end; say; exit 13
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)
pickChar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_)==3 then _=d2c(_);if length(_)==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</lang>
Programming note: &nbsp; the &nbsp; '''hood''' &nbsp; subroutine (above) could be optimized for speed by setting some short-circuit values &nbsp; <code>('''r-1''', '''c-1''', '''r+1''', and '''c+1''') </code> &nbsp; and using those values in the subsequent expressions.
 
<br>This REXX program makes use of the &nbsp; '''linesize''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
 
<br>The &nbsp; '''LINESIZE.REX''' &nbsp; REXX program is included here &nbsp; ──► &nbsp; [[LINESIZE.REX]]. <br><br>
The &nbsp; '''outputLINESIZE.REX''' &nbsp; whenREXX theprogram defaultis inputincluded filehere is&nbsp; ──► &nbsp; used:[[LINESIZE.REX]]. <br><br>
 
{{out|output|text=&nbsp; when using the default input file:}}
 
(Cycle &nbsp; '''0''' &nbsp; (zero) &nbsp; is essentially a copy of the input file.)
<pre style="height:60ex">
Line 3,917 ⟶ 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}}
<langsyntaxhighlight lang="ruby">var f = [[], DATA.lines.map {['', .chars..., '']}..., []];
 
10.times {
say f.map { .join(" ") + "\n" }.join;
var a = [[]];
for y in (1 ..^ f.end-1) {
var r = f[y];
var rr = [''];
for x in (1 ..^ r.end-1) {
var c = r[x];
rr << (
given(c) {
when('H') { 't' }
when('t') { '.' }
when('.') { <. H>[[f.ft([y-1, .. y+1)]].map{.ft([x-1, .. x+1)...]}.count('H') ~~ [1,2]] }
default { c }
}
)
}
rr << '';
a << rr;
}
f = [a..., []];
}
 
Line 3,955 ⟶ 6,388:
...
. .
Ht.. ......</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
See: [[Wireworld/Smalltalk]]
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">(* Maximilian Wuttke 12.04.2016 *)
 
type world = char vector vector
Line 4,003 ⟶ 6,439:
" ... ",
". . ",
"Ht.. ......"]</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
See: [[Wireworld/Smalltalk]]
 
=={{header|Tcl}}==
Line 4,016 ⟶ 6,449:
to construct a two dimensional 3 by 3 sliding window.
The rule function maps a pair (cell,neighborhood) to a new cell.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
rule = case~&l\~&l {`H: `t!, `t: `.!,`.: @r ==`H*~; {'H','HH'}?</`H! `.!}
Line 4,022 ⟶ 6,455:
neighborhoods = ~&thth3hthhttPCPthPTPTX**K7S+ swin3**+ swin3@hNSPiCihNCT+ --<0>*+ 0-*
 
evolve "n" = @iNC ~&x+ rep"n" ^C\~& rule**+ neighborhoods@h</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">diode =
 
<
Line 4,033 ⟶ 6,466:
#show+
 
example = mat0 evolve13 diode</langsyntaxhighlight>
{{out}}
<pre style="height:15ex;overflow:scroll">
Line 4,091 ⟶ 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]]
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
char New(53,40), Old(53,40);
 
Line 4,142 ⟶ 6,654:
until KeyHit; \keystroke terminates program
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{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>
9,476

edits