我想要一段linux下可运行的shell编程实现推箱子小游戏的代码
时间: 2023-12-10 11:37:41 浏览: 75
好的,推箱子游戏是一个非常经典的小游戏,下面是一个简单的shell脚本实现:
```shell
#!/bin/bash
# 初始化地图
map=(
"#########"
"#@ $ #"
"###$#$###"
"# $ #"
"# $ ###"
"#####$ #"
"# $#"
"### #@ #"
"#########"
)
# 找到玩家和箱子的位置
find_player_and_box() {
player_x=0
player_y=0
box_x=0
box_y=0
for ((i=0;i<${#map[@]};i++))
do
for ((j=0;j<${#map[i]};j++))
do
if [ "${map[i]:j:1}" = "@" ]; then
player_x=$j
player_y=$i
elif [ "${map[i]:j:1}" = "$" ]; then
box_x=$j
box_y=$i
fi
done
done
}
# 移动玩家
move_player() {
dx=$1
dy=$2
if [ "${map[player_y+dy]:player_x+dx:1}" = " " -o "${map[player_y+dy]:player_x+dx:1}" = "." ]; then
map[player_y]=${map[player_y]:0:player_x}" "${map[player_y]:player_x+1}
player_x=$((player_x+dx))
player_y=$((player_y+dy))
map[player_y]=${map[player_y]:0:player_x}"@"${map[player_y]:player_x+1}
elif [ "${map[player_y+dy]:player_x+dx:1}" = "$" ]; then
if [ "${map[player_y+dy*2]:player_x+dx*2:1}" = " " -o "${map[player_y+dy*2]:player_x+dx*2:1}" = "." ]; then
map[player_y+dy]=${map[player_y+dy]:0:player_x+dx}" "${map[player_y+dy]:player_x+dx+1}
map[player_y]=${map[player_y]:0:player_x}" "${map[player_y]:player_x+1}
player_x=$((player_x+dx))
player_y=$((player_y+dy))
map[player_y]=${map[player_y]:0:player_x}"@"${map[player_y]:player_x+1}
map[player_y+dy*2]=${map[player_y+dy*2]:0:player_x+dx}"$"${map[player_y+dy*2]:player_x+dx+1}
fi
fi
}
# 判断是否完成
is_win() {
for ((i=0;i<${#map[@]};i++))
do
for ((j=0;j<${#map[i]};j++))
do
if [ "${map[i]:j:1}" = "$" ]; then
return 1
fi
done
done
return 0
}
# 打印地图
print_map() {
clear
for ((i=0;i<${#map[@]};i++))
do
echo ${map[i]}
done
}
# 游戏循环
while true
do
find_player_and_box
print_map
read -s -n1 key
case "$key" in
"w") move_player 0 -1;;
"s") move_player 0 1;;
"a") move_player -1 0;;
"d") move_player 1 0;;
*) continue;;
esac
is_win
if [ $? -eq 0 ]; then
echo "You win!"
break
fi
done
```
使用方法:
1. 将以上代码保存为一个文件,例如`push_box.sh`
2. 在终端中进入到该文件所在目录并运行`./push_box.sh`
3. 使用`w`、`a`、`s`、`d`来控制玩家移动,将所有箱子推到目标位置即可胜利
注意:以上代码只是一个简单实现,仅供参考。
阅读全文