A. K. デュードニー 著「コンピューターレクリエーション4 遊びの展開」 より、 チョロアリのグラフィック(その1)です。チョロアリが動く規則はとても簡単です。
たったこれだけの規則ですが、 最初はでたらめに動き回っていた(ように見える)チョロアリが、 そのうちにある方向へ向かって柱が伸びていくように進んでいきます。 画面は上下と左右を連結しているので、柱が無限に伸びるわけではありませんが、 その模様はとても面白いです。
//
// チョロアリ1
//
// Copyright (C) 2001 Makoto Hiroi
//
import java.awt.*;
import java.applet.*;
import java.util.*;
public class Ant extends Applet implements Runnable
{
// 変数定義
final int SIZE = 100;
byte plane[] = new byte[SIZE * SIZE];
int dir = 0, x = 50, y = 50, width, height, edge;
Image double_buffer;
Graphics dg;
Thread trig = null;
// 初期化
public void init(){
trig = new Thread( this );
width = getSize().width;
height = getSize().height;
double_buffer = createImage( width, height );
dg = double_buffer.getGraphics();
edge = width / SIZE;
// 画面の初期化
dg.setColor( Color.black );
dg.fillRect( 0, 0, width, height );
// 平面の初期化
for( int i = 0; i < (SIZE * SIZE); i++ ){
plane[i] = 0;
}
trig.start();
}
public void paint( Graphics g ){
g.drawImage( double_buffer, 0, 0, null );
}
public void update( Graphics g ){
paint( g );
}
public void run(){
while( true ){
try {
Thread.sleep( 20 );
} catch( InterruptedException e ){}
doIt();
doIt();
doIt();
doIt();
repaint();
}
}
void doIt(){
int postion = y * SIZE + x;
if( plane[postion] == 0 ){
dir = (dir + 1) % 4;
dg.setColor( Color.red );
plane[postion] = 1;
} else {
dir = (dir + 3) % 4;
dg.setColor( Color.black );
plane[postion] = 0;
}
dg.fillRect( x * edge, y * edge, edge, edge );
switch( dir ){
case 0 :
x = (x <= 0 ? SIZE - 1 : x - 1);
break;
case 1 :
y = (y <= 0 ? SIZE - 1 : y - 1);
break;
case 2 :
x = (x >= SIZE - 1 ? 0 : x + 1);
break;
case 3 :
y = (y >= SIZE - 1 ? 0 : y + 1);
break;
}
}
}