package main
import (
"fmt"
"os/exec"
"os"
"time"
)
//定义全局变量
var(
//定义变量保存R当前位置
currentRow = 1
currentCol = 1
//定义变量保存迷宫出口位置(索引)
endRow = 1
endCol = 5
)
func main() {
//1.定义一个二维数组保存迷宫地图
sce := [][] byte{
{'*','*','*','*','*','*'},
{'*','R',' ','*',' ',' '},
{'*',' ','*','*',' ','*'},
{'*',' ',' ','*',' ','*'},
{'*','*',' ',' ',' ','*'},
{'*','*','*','*','*','*'},
}
//2.定义一个函数打印地图
printMap(sce)
for{
//1.提示用户如何输入
fmt.Println("请输入w a s d,以回车结束")
fmt.Println("w-->上 a-->左 s-->下 d-->右")
//2.接收用户输入的数据
ch := input()
//3.定于函数让R根据用户输入行走
move(sce,ch)
//4.判断是否已经走出迷宫
if(currentRow == endRow && currentCol == endCol){
break
}
//5.打印地图
printMap(sce)
}
fmt.Println("恭喜你通过关卡...")
time.Sleep(5000)
}
func move(m[][]byte,ch string){
switch ch {
case "w","W":
fmt.Println("向上走")
if m[currentRow -1][currentCol] != '*'{
m[currentRow][currentCol] = ' '
m[currentRow - 1][currentCol] = 'R'
currentRow --
}
case "a","A":
fmt.Println("向左走")
if m[currentRow][currentCol - 1] != '*'{
m[currentRow][currentCol] = ' '
m[currentRow][currentCol - 1] = 'R'
currentCol --
}
case "s","S":
fmt.Println("向下走")
if m[currentRow + 1][currentCol] != '*'{
m[currentRow][currentCol] = ' '
m[currentRow + 1][currentCol] = 'R'
currentRow ++
}
case "d","D":
fmt.Println("向右走")
if m[currentRow][currentCol + 1] != '*'{
m[currentRow][currentCol] = ' '
m[currentRow][currentCol + 1] = 'R'
currentCol ++
}
}
}
func input() (ch string){
//1.接收用户输入的数据
fmt.Scanln(&ch)
//2.将接收到的数据返回给调用者
return
}
func printMap(m[][]byte){
//清空屏幕代码
cmd := exec.Command("cmd","/c","cls")
cmd.Stdout = os.Stdout
cmd.Run()
//循环打印地图
for _,v1 := range m{
for _, v2 := range v1{
fmt.Printf("%c",v2)
}
fmt.Printf("\n")
}
}
Go语言实现走迷宫
猜你喜欢
转载自blog.csdn.net/FengyCoder/article/details/82991785
今日推荐
周排行