package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
//wg用来等待程序
var wg sync.WaitGroup
func init() {
//设置随机数种子,加上这行代码,可以保证每次随机都是随机的
rand.Seed(time.Now().UnixNano())
}
func main() {
//无缓冲的通道
court := make(chan int)
//计数加2,表示要等待两个goroutine
wg.Add(2)
go player("Nadal", court)
go player("Djokovic", court)
//发球
court <- 1
//等待游戏结束
wg.Wait()
}
func player(name string, court chan int) {
//在函数退出时调用Done来通知函数工作完成
defer wg.Done()
for {
ball, ok := <-court
if !ok {
//等待球被击打过来
fmt.Printf("Player %s Won\n",name)
return
}
//选随机数,然后用这个数判断我们是否丢球
n := rand.Intn(100)
fmt.Printf("n=%d\n",n)
if n%13 == 0 {
fmt.Printf("player %s Missed\n", name)
close(court)
return
}
fmt.Printf("Player %s Hit %d\n", name, ball)
ball++
//将球打向对手
court <- ball
}
}