用perl语言编写五子棋
时间: 2023-07-20 19:23:39 浏览: 93
五子棋java编写的,有点残,如果有意可以改改
以下是用 Perl 语言编写的五子棋代码,可以在终端运行:
```perl
#!/usr/bin/perl
use strict;
use warnings;
# 初始化棋盘
my @board;
for (my $i = 0; $i < 15; $i++) {
push @board, [(0) x 15];
}
# 定义棋子类型
my %pieces = (1 => '●', 2 => '○');
# 输出棋盘
sub print_board {
print " ";
for (my $i = 0; $i < 15; $i++) {
print " $i";
}
print "\n";
for (my $i = 0; $i < 15; $i++) {
print "$i ";
for (my $j = 0; $j < 15; $j++) {
print "$pieces{$board[$i][$j]} ";
}
print "\n";
}
}
# 判断胜负
sub check_win {
my ($row, $col, $piece) = @_;
my $count = 0;
# 横向
for (my $i = $col - 4; $i <= $col; $i++) {
if ($i >= 0 && $i + 4 < 15) {
my $flag = 1;
for (my $j = $i; $j < $i + 5; $j++) {
if ($board[$row][$j] != $piece) {
$flag = 0;
last;
}
}
$count += $flag;
}
}
# 纵向
for (my $i = $row - 4; $i <= $row; $i++) {
if ($i >= 0 && $i + 4 < 15) {
my $flag = 1;
for (my $j = $i; $j < $i + 5; $j++) {
if ($board[$j][$col] != $piece) {
$flag = 0;
last;
}
}
$count += $flag;
}
}
# 斜向
for (my $i = $row - 4; $i <= $row; $i++) {
if ($i >= 0 && $i + 4 < 15) {
my $flag = 1;
for (my $j = $i; $j < $i + 5; $j++) {
my $k = $j - $row + $col;
if ($k >= 0 && $k < 15 && $board[$j][$k] != $piece) {
$flag = 0;
last;
}
}
$count += $flag;
}
}
# 反斜向
for (my $i = $row - 4; $i <= $row; $i++) {
if ($i >= 0 && $i + 4 < 15) {
my $flag = 1;
for (my $j = $i; $j < $i + 5; $j++) {
my $k = $row + $col - $j;
if ($k >= 0 && $k < 15 && $board[$j][$k] != $piece) {
$flag = 0;
last;
}
}
$count += $flag;
}
}
return $count > 0;
}
# 下棋
my $turn = 1;
while (1) {
print_board();
print "请 $pieces{$turn} 下棋(输入行列坐标,如 3,4):";
my $input = <STDIN>;
chomp $input;
my ($row, $col) = split /,/, $input;
if ($board[$row][$col]) {
print "该位置已经有棋子了,请重新输入\n";
next;
}
$board[$row][$col] = $turn;
if (check_win($row, $col, $turn)) {
print_board();
print "$pieces{$turn} 获胜!\n";
last;
}
$turn = $turn == 1 ? 2 : 1;
}
```
运行后,在终端中可以进行五子棋游戏。输入行列坐标即可下棋,如 3,4 表示在第 3 行第 4 列下棋。当有一方获胜时,程序会输出获胜方并结束游戏。
阅读全文