我使用 Perl 和 TK 编写了元胞自动机(康威的生命游戏),只是为了好玩和练习。它适用于控制台输出。当我使用 TK 时,在第一个版本中,我只是删除并添加了新的单元格(矩形),大约 100 步后,我的程序变慢了(大约 10 倍)。然后我重写了图形部分:最初制作了所有 2500 个单元格 (50x50),然后更改它们的颜色而不是添加/删除它们。但经过 600-700 步后,我重新设计的自动机也开始减速。
这是 TK 的功能/错误还是我做错了什么?
按标签更改颜色:
$canvas->itemconfigure("cell"."$x $y", -fill=>'blue');
创建网格:
for($y = 0; $y < 50; $y++)
{
for($x = 0; $x < 50; $x++)
{
$canvas->createRectangle($x * 10, $y * 10, ($x + 1) * 10, ($y + 1) * 10, -fill=>'white', -tags=>["cell"."$x $y"]);
}
}
启动和停止循环:
sub start
{
$repeat = $MainWindow->repeat($speed, sub{&maketurn;});
# Function "maketurn" is not important, it is a simple counting of "alive" cells
# and changing color by tag
}
sub stop
{
if(defined($repeat))
{
$repeat->cancel();
}
}