爽!用golang 手撸了个简单的贪吃蛇

背景

题主现在是php程序员, 学了一周的golang, 深刻的感受到了其特性的优雅及功能的强大, 为了增强熟练度, 决定来写个贪吃蛇来践行下.(底部有github项目链接)

需求构思

1. 确定元素
    --- 食物
    - 分数
    - 基本的提示信息

2. 用户故事
    - 蛇撞墙, 死亡
    - 蛇吃蛋分数加1, 身体增加一格长度.
    - 点击键盘左键, 蛇向左走
    - 点击键盘右键, 蛇向右走
    - 点击键盘上键, 蛇向上走
    - 点击键盘下键, 蛇向下走
    - 点esc, 退出游戏

逻辑构思

元素用户故事都确定了, 就要开始写代码吗? 写项目不是这样的!要践行以终为始(很重要!, 否则可能会造成代码的荒草丛生), 先去思考一下我们的代码结构是什么样子的.

手持游戏机为例.

  • 游戏机其实就是一个服务(Service), 然后屏幕键盘统一由游戏机调配.
    • 屏幕(provider)
    • 键盘控制(provider)

然后我们细分一下屏幕和键盘控制的元素:

  • 屏幕: 蛇,食物,屏幕宽及高,得分.
  • 键盘控制: 用户移动指令,用户退出指令, 蛇死亡指令.

代码结构

//game control 游戏数据结构
type game struct {
   //控制
   control *control
   //屏幕
   screen *screen
}
//control 键盘控制
type control struct {
   moveChannel           chan int
   quitChannel           chan int
   playGameStatusChannel chan bool
   gameOver              bool
   direction             int
}
//screen 屏幕相关参数
type screen struct {
   snakes    *snake
   foodPoint *scope
   width     int
   height    int
   score     int
}
//NewGameService 实例化游戏服务
func NewGameService() *gameService {
   return &gameService{screenApp: newScreenApp(), monitorApp: newMonitorApp()}
}
//newScreenApp 屏幕实例化
func newScreenApp() *screenApp {
   return &screenApp{Screen: initScreenHandle()}
}
//newMonitorApp 实例化
func newMonitorApp() *monitorApp {
   return &monitorApp{Monitor: initMonitor()}
}

小结

个人认为项目的代码的结构写的还算清晰,所以不放过多代码了, 只是把一个全局的结构图景放到这里, 留给你去探索. 这个小项目的代码逻辑肯定还不完善,你如果有什么想法或者吐槽, 可以在下方留言,每个我都会认真阅读和回复.😃

最后放上项目链接(🌺🌺🌺🌺🌺🌺 感觉不错, 别忘star哦 🌺🌺🌺🌺🌺🌺):
github.com/TheOnlines/golang_snake...

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 1年前 自动加精
讨论数量: 14

:+1:

1年前 评论
xiaomifdsa (楼主) 1年前

横着走居然是个胖蛇 :relaxed:

1年前 评论
xiaomifdsa (楼主) 1年前
working (作者) 1年前
xiaomifdsa (楼主) 1年前

:+1:

1年前 评论
xiaomifdsa (楼主) 1年前

很会玩 :full_moon_with_face:

1年前 评论
xiaomifdsa (楼主) 1年前

厉害啊,向技术大牛学习。我还在研究curd呢cloud.tencent.com/developer/articl...

1年前 评论
xiaomifdsa (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!