linux井字棋shell脚本
时间: 2023-09-01 22:11:01 浏览: 218
井字棋小游戏源代码
4星 · 用户满意度95%
以下是一个简单的 Linux 井字棋 shell 脚本:
```bash
#!/bin/bash
# 初始化游戏面板
board=(1 2 3 4 5 6 7 8 9)
player=1
game_on=true
# 打印游戏面板
function print_board() {
printf "\n"
printf "\t %s | %s | %s\n" "${board[0]}" "${board[1]}" "${board[2]}"
printf "\t -----------\n"
printf "\t %s | %s | %s\n" "${board[3]}" "${board[4]}" "${board[5]}"
printf "\t -----------\n"
printf "\t %s | %s | %s\n" "${board[6]}" "${board[7]}" "${board[8]}"
printf "\n"
}
# 检查是否有玩家获胜
function check_win() {
if [[ "${board[0]}" == "${board[1]}" && "${board[1]}" == "${board[2]}" ]] ||
[[ "${board[3]}" == "${board[4]}" && "${board[4]}" == "${board[5]}" ]] ||
[[ "${board[6]}" == "${board[7]}" && "${board[7]}" == "${board[8]}" ]] ||
[[ "${board[0]}" == "${board[3]}" && "${board[3]}" == "${board[6]}" ]] ||
[[ "${board[1]}" == "${board[4]}" && "${board[4]}" == "${board[7]}" ]] ||
[[ "${board[2]}" == "${board[5]}" && "${board[5]}" == "${board[8]}" ]] ||
[[ "${board[0]}" == "${board[4]}" && "${board[4]}" == "${board[8]}" ]] ||
[[ "${board[2]}" == "${board[4]}" && "${board[4]}" == "${board[6]}" ]]; then
printf "Player %s wins!\n" "$player"
game_on=false
fi
}
# 检查是否平局
function check_tie() {
if [[ "${board[0]}" != 1 && "${board[1]}" != 2 && "${board[2]}" != 3 &&
"${board[3]}" != 4 && "${board[4]}" != 5 && "${board[5]}" != 6 &&
"${board[6]}" != 7 && "${board[7]}" != 8 && "${board[8]}" != 9 ]]; then
printf "It's a tie!\n"
game_on=false
fi
}
# 询问玩家下棋位置
function ask_player() {
printf "Player %s, choose a spot: " "$player"
read spot
if [[ "${board[spot-1]}" != "X" && "${board[spot-1]}" != "O" ]]; then
board[spot-1]=$mark
else
printf "Spot already taken, choose another spot.\n"
ask_player
fi
}
# 切换玩家
function switch_player() {
if [ $player -eq 1 ]; then
player=2
mark="O"
else
player=1
mark="X"
fi
}
# 游戏循环
while [ $game_on == true ]; do
print_board
ask_player
check_win
check_tie
switch_player
done
print_board
```
这个脚本实现了一个简单的井字棋游戏,玩家可以通过输入数字来下棋。该脚本使用了数组来表示游戏面板,并使用函数来检查玩家是否获胜、检查是否平局、询问玩家下棋位置以及切换玩家。游戏循环会一直运行,直到有一方玩家获胜或者平局。
阅读全文