GO贪食蛇综合学习案例
需要调用C语言库作为API在GO中调取,最后文件将拆分为snake config main 详见压缩包
代码实现
package main
import (
"Clib"
"fmt"
"math/rand"
"os"
"time"
)
const WIDE int = 40
const HIGH int = 20
var food Food
var score int = 0
//初始化坐标
type Position struct {
X int
Y int
}
//初始化蛇
type Snake struct {
pos [WIDE * HIGH]Position //定义数组存储每一节蛇坐标
long int
fx byte
}
//初始化食物
type Food struct {
Position
}
//初始化地图
func MapInit() {
// 输出初始画面
fmt.Fprintln(os.Stderr,
`
#-----------------------------------------#
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
#-----------------------------------------#
`)
}
func ShowUI(X int,Y int,ch byte){
//调用C语言代码设置控制台光标
Clib.GotoPostion(X+2,Y+1) //加空格偏移量
fmt.Fprintf(os.Stderr,"%c",ch)
}
//初始化蛇
func (s *Snake) SnakeInit(){
s.long = 2 //长度
s.fx = 'R' //U 上D 下 L左 R右
//蛇头位置
s.pos[0].X = WIDE/2
s.pos[0].Y = HIGH/2
s.pos[1].X = WIDE/2 -1
s.pos[1].Y = HIGH/2
var ch byte
for i:=0;i= WIDE || s.pos[0].Y-1 >= HIGH{
return
}
//蛇头和身体碰撞
for i := 1; i 0;i--{
//蛇块递减
s.pos[i].X = s.pos[i-1].X
s.pos[i].Y = s.pos[i-1].Y
}
//蛇头处理 根据方向控制 去带动蛇头的运动
s.pos[0].X = s.pos[0].X+dx
s.pos[0].Y = s.pos[0].Y+dy
//绘制蛇
var ch byte
for i:=0;i < s.long;i++{
//区分蛇头和身体
if i==0{
ch = '@'
}else{
ch = '*'
}
ShowUI(s.pos[i].X,s.pos[i].Y,ch)
}
//清空蛇尾巴
ShowUI(lx,ly,' ')
}
}
//初始化随机食物
func RandomFood() {
food.X = rand.Intn(WIDE)+2
food.Y = rand.Intn(HIGH)+1
}
func main() {
//设置随机数种子用于混淆
rand.Seed(time.Now().UnixNano())
//隐藏控制台光标
Clib.HideCursor()
//初始化地图
MapInit()
//随机食物
RandomFood()
ShowUI(food.X,food.Y,'#')
//创建蛇
var s Snake
//初始化蛇
s.SnakeInit()
//玩游戏
s.PlayGame()
//分数显示
Clib.GotoPostion(0,23)
fmt.Fprintln(os.Stderr,"分数:",score)
time.Sleep(time.Second*5)
}
Clib/CCodego
package Clib /* #include#include // 使用了WinAPI来移动控制台的光标 void gotoxy(int x,int y) { COORD c; c.X=x,c.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); } // 从键盘获取一次按键,但不显示到控制台 int direct() { return _getch(); } //去掉控制台光标 void hideCursor() { CONSOLE_CURSOR_INFO cci; cci.bVisible = FALSE; cci.dwSize = sizeof(cci); SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); } */ import "C" // go中可以嵌入C语言的函数 //设置控制台光标位置 func GotoPostion(X int, Y int) { //调用C语言函数 C.gotoxy(C.int(X), C.int(Y)) } //无显获取键盘输入的字符 func Direction() (key int) { key = int(C.direct()) return } //设置控制台光标隐藏 func HideCursor() { C.hideCursor() }