前端之家收集整理的这篇文章主要介绍了
Golang语言实现-贪吃蛇,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"fmt"
"math/rand"
"os"
"time"
)
import "C"
type loct struct {
i,j int
}
var (
area = [20][20]byte{}
food bool
lead byte
head loct
tail loct
size int
)
func place() loct {
k := rand.Int() % 400
return loct{k / 20,k % 20}
}
draw(p loct,c byte) {
C.gotoxy(C.int(p.i*2+4),C.int(p.j+2))
fmt.Fprintf(os.Stderr,"%c",c)
}
init() {
head,tail = loct{4,4},loct{4}
lead,size = 'R',31);">1
area[4][4] = 'H'
rand.Seed(int64(time.Now().Unix()))
fmt.Fprintln(os.Stderr,0);">` #-----------------------------------------# | | | | | | | | | * | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | #-----------------------------------------# `)
go func() {
for {
switch byte(C.direct()) {
case 72:
lead = 'U'
75:
lead = 'L'
77:
lead = 'R'
80:
lead = 'D'
32:
lead = 'P'
}
}
}()
}
main// 主程序
for {
time.Sleep(time.Millisecond * 400)
if lead == 'P' {
continue
}
if !food {
give := place()
if area[give.i][give.j] == 0 {
area[give.i][give.j] = 'F'
draw(give,0);">'$')
food = true
}
}
area[head.i][head.j] = lead
switch lead {
case 'U':
head.j--
'L':
head.i--
'R':
head.i++
'D':
head.j++
}
if head.i < 0 || head.i >= 20 || head.j < 0 || head.j >= 20 {
C.gotoxy(0,31);">23)
break
}
eat := area[head.i][head.j]
if eat == 'F' {
food = false
size++
} else if eat == // 普通移动
draw(tail,0);">' ')
dir := area[tail.i][tail.j]
area[tail.i][tail.j] = 0
switch dir {
'U':
tail.j--
'L':
tail.i--
'R':
tail.i++
'D':
tail.j++
}
} else {
C.gotoxy(23)
break
}
draw(head,0);">'*')
}
switch {
case size < 22:
fmt.Fprintf(os.Stderr,0);">"Faild! You've eaten %d $\\n",size-1)
42:
fmt.Fprintf(os.Stderr,0);">"Try your best! You've eaten %d $\\n",168);">default:
fmt.Fprintf(os.Stderr,0);">"Congratulations! You've eaten %d $\\n",31);">-1)
}
}
原文链接:https://www.f2er.com/go/187369.html