我最近开始尝试将我编写的康威生命游戏的 C++ 代码复制到 Perl 中,并且几乎是逐字复制。但是,C++ 代码的输出与 Perl 的输出有很大不同。C++ 代码运行完美,但 Perl 代码给出了奇怪的行为。任何看过生命游戏的人都应该知道,以下游戏状态很奇怪:
[][] [] [] [] [][][] [] [] [] [] [] [] [][] []
[] [] [] [] [] [] [] [][] [] [] [][] [] [] []
[] [][] [] [] [] [] [] [][][][] [] [] [][][][][] [] []
[] [][] [] [] [] [][][][] [] [] [] [] [][] []
[] [][] [] [] [][][] [] [] [] [] [][] [] []
[] [] [][][][][] [] [] [][] [][] [] [][] [] [][][] []
[] [] [] [][][] [][] [][][] [][][] [] []
[] [] [][][][][][][][][][] [][][][][] [] []
[][] [] [][][][][][][] [][][] [][] [][] []
[] [] [][][][] [] [] [] [] [][][] []
[][] [] [] [] [] [] [][] [] [][]
[] [] [][] [] [][][][] [][] [] []
[][] [] [][][][][] [][][] [][][][][][][][] [][]
[] [] [] [] [] [][][][] [][]
[][] [] [] [] [] [] [] [][][] [][][][][][][][]
[][] [] [] [] [] [] [] [][][][] [] [][] [][]
[] [][] [] [][] [] [] [][][][] [][][]
[] [][][][] [] [] [] [] [] [] [] [] [] [] [] []
[][][] [][][] [] [][] [][] [] [] [] []
[] [][][] [] [][] [][] [] [] [] [][] []
[][] [] [] [][][][][][] [][] [] [] []
[] [] [][][][][][][][][] [] [] [] [] [][][]
[][] [][][] [] [] [][] [] [] [] [][] [] [] []
[] [] [] [][] [][][][][][][] [] [][] [] [] [] []
每个[]
代表一个活细胞,而任何两个空白代表一个死细胞。奇怪的部分是在许多运行代码的尝试中出现的水平线和垂直线。我还没有看到预期的行为(滑翔机、振荡器等)。
我的代码如下;我将不胜感激任何帮助/澄清。提前致谢!
#!/usr/bin/perl
use warnings;
use strict;
use Curses;
use Time::HiRes 'usleep';
my $iterations = 100;
$iterations = $ARGV[0] if @ARGV;
initscr;
getmaxyx(my $rows, my $columns);
$columns = int($columns / 2);
my ($i, $j);
my @initial_state;
foreach $i (0 .. $rows) {
foreach $j (0 .. $columns) {
$initial_state[$i][$j] = int rand(2);
}
}
my @current_state = @initial_state;
my @next_state;
my $iteration;
my ($up, $down, $right, $left);
my $adjacent_cells;
foreach $iteration (0 .. $iterations) {
foreach $i (0 .. $rows) {
foreach $j (0 .. $columns) {
$up = ($i + 1) % $rows;
$down = ($i - 1) % $rows;
$right = ($j + 1) % $columns;
$left = ($j - 1) % $columns;
$adjacent_cells = $current_state[$i][$right]
+ $current_state[$i][$left]
+ $current_state[$up][$right]
+ $current_state[$up][$left]
+ $current_state[$down][$right]
+ $current_state[$down][$left]
+ $current_state[$up][$j]
+ $current_state[$down][$j];
if ( $current_state[$i][$j] ) {
$next_state[$i][$j] = $adjacent_cells == 2 || $adjacent_cells == 3 ? 1 : 0;
addstr($i, 2*$j, '[]');
}
else {
$next_state[$i][$j] = $adjacent_cells == 3 ? 1 : 0;
addstr($i, 2*$j, ' ');
}
}
}
@current_state = @next_state unless $iteration == $iterations;
usleep 10000;
refresh();
}
getch();
endwin();