1. 程式人生 > >Go語言實現走迷宮

Go語言實現走迷宮

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")
	}
}