使用shell编写五子棋游戏
时间: 2024-03-15 16:02:38 浏览: 96
以下是一个简单的五子棋游戏的shell代码:
```shell
#!/bin/bash
# 初始化棋盘
declare -a chessboard
for ((i=0; i<15; i++)); do
for ((j=0; j<15; j++)); do
chessboard[$i,$j]=.
done
done
# 打印棋盘
print_chessboard() {
echo " A B C D E F G H I J K L M N"
for ((i=0; i<15; i++)); do
if [[ $i -lt 9 ]]; then
echo -n " $((i+1))"
else
echo -n "$((i+1))"
fi
for ((j=0; j<15; j++)); do
echo -n " ${chessboard[$i,$j]}"
done
echo ""
done
}
# 判断胜负
check_win() {
local row=$1
local col=$2
local player=${chessboard[$row,$col]}
# 横向判断
local count=1
local i=$row
local j=$col
while [[ $((j-1)) -ge 0 && ${chessboard[$i,$((j-1))]} == $player ]]; do
let count++
let j--
done
i=$row
j=$col
while [[ $((j+1)) -lt 15 && ${chessboard[$i,$((j+1))]} == $player ]]; do
let count++
let j++
done
if [[ $count -ge 5 ]]; then
echo $player
return
fi
# 纵向判断
count=1
i=$row
j=$col
while [[ $((i-1)) -ge 0 && ${chessboard[$((i-1)),$j]} == $player ]]; do
let count++
let i--
done
i=$row
j=$col
while [[ $((i+1)) -lt 15 && ${chessboard[$((i+1)),$j]} == $player ]]; do
let count++
let i++
done
if [[ $count -ge 5 ]]; then
echo $player
return
fi
# 左上到右下判断
count=1
i=$row
j=$col
while [[ $((i-1)) -ge 0 && $((j-1)) -ge 0 && ${chessboard[$((i-1)),$((j-1))]} == $player ]]; do
let count++
let i--
let j--
done
i=$row
j=$col
while [[ $((i+1)) -lt 15 && $((j+1)) -lt 15 && ${chessboard[$((i+1)),$((j+1))]} == $player ]]; do
let count++
let i++
let j++
done
if [[ $count -ge 5 ]]; then
echo $player
return
fi
# 右上到左下判断
count=1
i=$row
j=$col
while [[ $((i-1)) -ge 0 && $((j+1)) -lt 15 && ${chessboard[$((i-1)),$((j+1))]} == $player ]]; do
let count++
let i--
let j++
done
i=$row
j=$col
while [[ $((i+1)) -lt 15 && $((j-1)) -ge 0 && ${chessboard[$((i+1)),$((j-1))]} == $player ]]; do
let count++
let i++
let j--
done
if [[ $count -ge 5 ]]; then
echo $player
return
fi
echo "."
}
# 游戏开始
player=1
while true; do
print_chessboard
if [[ $player -eq 1 ]]; then
echo "请玩家1落子(例如:A1):"
else
echo "请玩家2落子(例如:B3):"
fi
read -r pos
row=$(echo "$pos" | cut -c2)
col=$(echo "$pos" | cut -c1)
let row--
case $col in
A) col=0;;
B) col=1;;
C) col=2;;
D) col=3;;
E) col=4;;
F) col=5;;
G) col=6;;
H) col=7;;
I) col=8;;
J) col=9;;
K) col=10;;
L) col=11;;
M) col=12;;
N) col=13;;
*) col=-1;;
esac
if [[ $row -lt 0 || $row -ge 15 || $col -lt 0 || $col -ge 15 ]]; then
echo "无效的位置!"
continue
fi
if [[ ${chessboard[$row,$col]} != "." ]]; then
echo "此位置已有子!"
continue
fi
if [[ $player -eq 1 ]]; then
chessboard[$row,$col]=X
else
chessboard[$row,$col]=O
fi
winner=$(check_win $row $col)
if [[ $winner != "." ]]; then
print_chessboard
if [[ $winner == "X" ]]; then
echo "玩家1获胜!"
else
echo "玩家2获胜!"
fi
break
fi
if [[ $player -eq 1 ]]; then
player=2
else
player=1
fi
done
```
使用方法:
1. 将代码保存为一个文件(例如 `gobang.sh`);
2. 在终端中进入代码所在的目录;
3. 运行 `./gobang.sh` 命令即可开始游戏。
阅读全文