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

  

最新文章

  1. [网络技术][转]路由表查找过程(ip_route_input_slow)
  2. C++C#时间转换
  3. apk反编译(3)smali语法
  4. 【转】java静态代码块和构造方法执行顺序
  5. C#基础(二)——C#中的构造函数
  6. Python判断上传文件类型
  7. oracle之case when
  8. WF编译报错
  9. Clock Pictures
  10. hdu4597 Play Game DP
  11. 如何使用Androidstudio创建一个新项目
  12. python环境搭建--pycharm的安装及使用
  13. Python笔记-高阶函数
  14. Python Faker的使用(1):基础使用方法与函数速查,生成随机数据
  15. 我的Android之路——底部菜单栏的实现
  16. Ambiguous handler methods mapped for HTTP
  17. linux内核工作队列使用总结
  18. NW.js安装原生node模块node-printer控制打印机
  19. Android的layout_weight和weightSum
  20. ZOJ 3203 Light Bulb (三分+计算几何)

热门文章

  1. Shell命令的执行优先级
  2. GO汇总
  3. DevExpress MVVM<1>
  4. Chilkat9.5.0.75(x86+x64)ActiveX+注册机
  5. Linux(Centos7)下Mysql的安装
  6. Oracle处理关于sysaux表空间爆满的问题---更新最新方法!!
  7. STM32 HAL_Deleay() 函数 导致程序卡死
  8. Jmeter脚本录制攻略
  9. Django中的sql注入
  10. jmeter 中使用正则表达式提取依赖参数