go语言设计模式之state
2024-10-18 22:01:13
state.go
package main import ( "fmt" "math/rand" "os" "time" ) type GameState interface { executeState(*GameContext) bool } type GameContext struct { SecretNumber int Retries int Won bool Next GameState } type StartState struct{} func (s *StartState) executeState(c *GameContext) bool { c.Next = &AskState{} rand.Seed(time.Now().UnixNano()) c.SecretNumber = rand.Intn(10) fmt.Println("Introduce a number of retries to set the difficulty:") fmt.Fscanf(os.Stdin, "%d\n", &c.Retries) return true } type AskState struct{} func (a *AskState) executeState(c *GameContext) bool { fmt.Printf("Introduce a number between 0 and 10, you have %d tries left\n", c.Retries) var n int fmt.Fscanf(os.Stdin, "%d", &n) c.Retries = c.Retries - 1 if n == c.SecretNumber { c.Won = true c.Next = &FinishState{} } if c.Retries == 0 { c.Next = &FinishState{} } return true } type FinishState struct{} func (f *FinishState) executeState(c *GameContext) bool { if c.Won { println("Congrats, you won") } else { fmt.Printf("You lose, The correct number was: %d\n", c.SecretNumber) } return false } func main() { start := StartState{} game := GameContext{ Next: &start, } for game.Next.executeState(&game) { } }
最新文章
- [网络技术][转]路由表查找过程(ip_route_input_slow)
- C++C#时间转换
- apk反编译(3)smali语法
- 【转】java静态代码块和构造方法执行顺序
- C#基础(二)——C#中的构造函数
- Python判断上传文件类型
- oracle之case when
- WF编译报错
- Clock Pictures
- hdu4597 Play Game DP
- 如何使用Androidstudio创建一个新项目
- python环境搭建--pycharm的安装及使用
- Python笔记-高阶函数
- Python Faker的使用(1):基础使用方法与函数速查,生成随机数据
- 我的Android之路——底部菜单栏的实现
- Ambiguous handler methods mapped for HTTP
- linux内核工作队列使用总结
- NW.js安装原生node模块node-printer控制打印机
- Android的layout_weight和weightSum
- ZOJ 3203 Light Bulb (三分+计算几何)