selector

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2024 License: MIT Imports: 6 Imported by: 0

README

Selector

在由N个Action构成的Event中,根据Action的反馈结果以及Action优先级定时决策出当前能够代表Event执行的Action。

典型使用场景: 麻将中多个玩家可以吃碰杠胡同一张牌。

Event可复用

Usage

package main

import (
    "fmt"
    "time"
    
    "github.com/pyihe/go-selector"
)

func main() {
    event := selector.NewEvent(func() {
        fmt.Println("没有玩家选择操作, 继续摸牌...")
    })
    chi, _ := event.AddActionWithHandler(1, selector.Handler{
        selector.StateAgree: func() {
            fmt.Println("吃牌...")
        },
        selector.StateRefuse: func() {
            fmt.Println("拒绝吃牌...")
        },
        selector.StateTimeout: func() {
            fmt.Println("吃牌超时...")
        },
    })
    
    peng, _ := event.AddAction(2)
    peng.AddHandler(selector.StateAgree, func() {
        fmt.Println("碰牌...")
    })
    peng.AddHandler(selector.StateRefuse, func() {
        fmt.Println("拒绝碰牌...")
    })
    peng.AddHandler(selector.StateTimeout, func() {
        fmt.Println("碰牌超时...")
    })
    
    hu, _ := event.AddActionWithHandler(3, selector.Handler{
        selector.StateAgree: func() {
            fmt.Println("胡牌...")
        },
        selector.StateRefuse: func() {
            fmt.Println("拒绝胡牌...")
        },
        selector.StateTimeout: func() {
            fmt.Println("胡牌超时...")
        },
    })
    
    event.Start(5 * time.Second)
    
    chi.Agree()
    peng.Refuse()
    hu.Refuse()
    
    time.Sleep(10 * time.Second)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEventIsRunning = errors.New("cannot add action when event running")
)

Functions

This section is empty.

Types

type Action

type Action interface {
	Agree()
	Refuse()
	Deadline() time.Time
	AddHandler(State, func())
}

type Event

type Event struct {
	OnTimeout func() // Event超时后默认执行的Handler
	// contains filtered or unexported fields
}

func NewEvent

func NewEvent(handler func()) *Event

func (*Event) AddAction

func (e *Event) AddAction(priority uint) (Action, error)

func (*Event) AddActionWithHandler

func (e *Event) AddActionWithHandler(priority uint, handler Handler) (Action, error)

func (*Event) Reset

func (e *Event) Reset()

func (*Event) Start

func (e *Event) Start(timeout time.Duration)

type Handler

type Handler map[State]func()

type State

type State uint8 // 动作状态
const (
	StateAgree   State // 同意
	StateRefuse        // 拒绝
	StateTimeout       // 超时

)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL