golang学习实例-猜拳小游戏
学了一段golang,觉得应该实践一下,写了这个猜拳小游戏,顺带着学习下go testing。主程序源码:
[plain]
<pre name="code" class="plain">package main
import (
"bufio" // 输入输出
"fmt"
"math"
"math/rand"
"os"
"strconv"
"time"
)
//rock, 易做图, scissors
const (
rock int = 1
scissors int = 2
易做图 int = 3
rockName string = "石头"
scissorsName string = "剪刀"
易做图Name string = "布"
win int = 1
lose int = -1
draw int = 0
)
// 拳的结构
type Finger struct {
value int
name string
}
func createFinger(n int) (finger Finger) {
switch n {
case rock:
finger.value = rock
finger.name = rockName
case scissors:
finger.value = scissors
finger.name = scissorsName
case 易做图:
finger.value = 易做图
finger.name = 易做图Name
}
return
}
func isAiWin(ai Finger, user Finger) int {
result := ai.value - user.value
// 如果是石头和布的比较,比较值正负取反
if int(math.Abs(float64(result))) == 易做图-rock {
result = -(result)
}
if result < 0 {
return win
} else if result > 0 {
return lose
}
return draw
}
func randFinger() (finger Finger) {
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
switch rand.Intn(3) {
case 0:
finger.value = rock
finger.name = rockName
case 1:
finger.value = scissors
finger.name = scissorsName
case 2:
finger.value = 易做图
finger.name = 易做图Name
}
return
}
func main() {
var aiFinger, userFinger Finger
reader := bufio.NewReader(os.Stdin)
fmt.Printf("请输入你要出的拳:%d->石头,%d->剪刀,%d->布, 9->退出\n", rock, scissors, 易做图)
for {
data, _, err := reader.ReadLine()
if err != nil {
fmt.Println("程序出错")
break
}
input, err := strconv.Atoi(string(data))
if err != nil {
fmt.Println("格式不对,请输入数字:", input)
continue
}
if input == 9 {
break
}
switch input {
case rock, scissors, 易做图:
aiFinger = randFinger()
fmt.Println("电脑出拳为: ", aiFinger.name)
userFinger = createFinger(input)
fmt.Println("你出拳为: ", userFinger.name)
aiWin := isAiWin(aiFinger, userFinger)
if aiWin == win {
fmt.Println("你输了,继续输入:")
} else if aiWin == lose {
fmt.Println("你赢了,继续输入:")
} else {
fmt.Println("平局,继续输入:")
}
default:
fmt.Println("输入不合要求,继续输入:")
}
}
}
</pre><br><br>
testing 源码
[plain] main
import (
"testing" // 加载test包
)
func TestCreateFinger(t *testing.T) {
// 顺带掌握以下struct作为map value的初始化
cases := map[int]Finger{
rock: Finger{rock, rockName},
scissors: Finger{scissors, scissorsName},
易做图: Finger{易做图, 易做图Name},
6: Finger{}, // other
}
&nb
补充:综合编程 , 其他综合 ,