func (h *Human) Status() { c_ptr := console.GetPtr() c_ptr.Printf("name: %s", h.Name) c_ptr.Printf("gender: %s", h.Gender) c_ptr.Printf("location: %s", h.Location) c_ptr.Printf("motion: %s", h.GetCurrentMotion()) }
func (h *hub) run() { console := console.GetPtr() console.Output(h) quitAll := func() { if len(h.connections) == 0 { fmt.Println("quit all") //... fmt.Println("ok") } } for { select { // запрос на регистранцию // отметить что он зарегистрирован case c := <-h.Register: h.connections[c] = true fmt.Printf("client register\n") fmt.Printf("total clients: %d\n", len(h.connections)) // запрос Отменить регистрацию // удалить запись о регистрации из массива // закрываем канал case c := <-h.unregister: delete(h.connections, c) fmt.Printf("client unregister\n") fmt.Printf("total clients: %d\n", len(h.connections)) close(c.Send) quitAll() // широковещательные сообщения // перебрать всех зарегистрированных, // и отправить каждому это сообщение // если в канале больше нет сообщений // ???? не понял // закрыть канал и отменить регистрацию case m := <-h.broadcast: for c := range h.connections { select { case c.Send <- m: default: // если слушателей больше нет, отключим сервис quitAll() close(c.Send) delete(h.connections, c) } } case m := <-h.command: for _, val := range m { console.Exec(string(val)) } } } }
func people(key, value string, help *string) { if value == "help" { *help = "get human list" return } c_ptr := console.GetPtr() cmd := strings.Split(value, " ") if len(cmd) != 1 || value == "" { c_ptr.Printf("usage: list <bar|dance|total>") return } for _, human := range nightclub.GetPeople() { if human.Location == cmd[0] || cmd[0] == "total" { c_ptr.Printf(human.Name) } } }
func getHumanStatus(key, value string, help *string) { if value == "help" { *help = "get human status" return } c_ptr := console.GetPtr() if value == "" { c_ptr.Printf("usage: status <full name>") return } if human, ok := nightclub.GetHuman(value); ok { human.Status() } else { c_ptr.Printf("human not found") } }
func currentTrack(key, value string, help *string) { if value == "help" { *help = "get current music track" return } c_ptr := console.GetPtr() ct, err := nightclub.GetCurrentTrack() if err != nil { c_ptr.Printf(err.Error()) return } c_ptr.Printf("Name: %s", ct.Name) c_ptr.Printf("Album: %s", ct.Album) c_ptr.Printf("Group: %s", ct.Group) c_ptr.Printf("Type: %s", ct.Type) c_ptr.Printf("Duration: %v", ct.Duration) }
func openClose(key, value string, help *string) { if value == "help" { *help = "<open|close> night club" } c_ptr := console.GetPtr() cmd := strings.Split(value, " ") if len(cmd) != 1 || value == "" { c_ptr.Printf("usage: club <open|close>") return } switch cmd[0] { case "open": nightclub.Open() c_ptr.Printf("club is openned") c_ptr.Exec("people total") case "close": c_ptr.Printf("club closed") nightclub.Close() } }
func run() { nightclub.Capacity = 20 console := console.GetPtr() console.AddInt("capacity", &nightclub.Capacity) console.Printf("-------------------------------") console.Printf("Night club v1.0") console.Printf("-------------------------------") console.Printf("Use help command for more info") console.Printf("First your need open club") console.AddCommand("exit", exit) console.AddCommand("club", openClose) console.AddCommand("ct", currentTrack) console.AddCommand("status", getHumanStatus) console.AddCommand("people", people) go func() { c := time.Tick(1 * time.Second) for now := range c { nightclub.DjUpdate(now) } }() for { reader := bufio.NewReader(os.Stdin) fmt.Print("#~: ") str, _ := reader.ReadString('\n') console.Exec(strings.Split(str, "\n")[0]) if quit { break } } }
func init() { h := &handler{} c_ptr := console.GetPtr() c_ptr.Output(h) }
func (n *Nightclub) DjUpdate(now time.Time) { if !n.isOpen { return } dt := n.trackSwitch.Add(n.playlist[n.curTrack].Duration) if !strings.Contains(time.Now().Sub(dt).String(), "-") { c_ptr := console.GetPtr() c_ptr.Printf("switch track") n.trackSwitch = time.Now() n.curTrack++ if n.curTrack+1 >= len(n.playlist) { n.curTrack = 0 } } // check human exp for _, human := range n.people { dances := human.GetDances() exist := false for _, dance := range dances { if n.playlist[n.curTrack].Type == dance.MusicType[0] { exist = true } } // to dancing if exist { func(new_human *Human) { // save exist := false for _, human := range n.dancing { if human == new_human { exist = true } } if !exist { n.dancing = append(n.dancing, new_human) human.Location = "dance" } // remove exist = false var pos int for human_pos, human := range n.bar { if human == new_human { exist = true pos = human_pos } } if exist { n.bar = append(n.bar[:pos], n.bar[pos+1:]...) } }(human) // goto bar } else { func(new_human *Human) { // save exist := false for _, human := range n.bar { if human == new_human { exist = true } } if !exist { n.bar = append(n.bar, new_human) human.Location = "bar" } // remove exist = false var pos int for human_pos, human := range n.dancing { if human == new_human { exist = true pos = human_pos } } if exist { n.dancing = append(n.dancing[:pos], n.dancing[pos+1:]...) } }(human) } } // dance for _, human := range n.dancing { human.Dance(n.playlist[n.curTrack].Type) } }
func (n *Nightclub) Open() { if n.isOpen { return } n.timeOpen = time.Now() n.trackSwitch = time.Now() n.curTrack = 0 n.isOpen = true makePlaylist := func() { rap := &Music{Type: "rap", Duration: 2 * time.Minute, Name: "Wakedafucup Intro", Group: "Onyx", Album: "Wakedafucup"} rap2 := &Music{Type: "rap", Duration: 3 * time.Minute, Name: "Fight The Power", Group: "Public Enemy", Album: "Power To The People And The Beats - Public Enemy's Greatest Hits"} hiphop := &Music{Type: "hiphop", Duration: 40 * time.Second, Name: "Peter Piper", Group: "Run-D.M.C.", Album: "Raising Hell"} hiphop2 := &Music{Type: "hiphop", Duration: 120 * time.Second, Name: "It's Tricky", Group: "Run-D.M.C.", Album: "Raising Hell"} pop := &Music{Type: "pop", Duration: 70 * time.Second, Name: "Stonemilker", Group: "bjork", Album: "Vulnicura"} pop2 := &Music{Type: "pop", Duration: 300 * time.Second, Name: "Lionsong", Group: "bjork", Album: "Vulnicura"} house := &Music{Type: "house", Duration: 200 * time.Second, Name: "Give Life Back to Music", Group: "Daft Punk", Album: "Random Access Memories"} house2 := &Music{Type: "house", Duration: 250 * time.Second, Name: "The Game of Love", Group: "Daft Punk", Album: "Random Access Memories"} n.PushMusicTrack(rap) n.PushMusicTrack(rap2) n.PushMusicTrack(hiphop) n.PushMusicTrack(hiphop2) n.PushMusicTrack(pop) n.PushMusicTrack(pop2) n.PushMusicTrack(house) n.PushMusicTrack(house2) _, err := n.GenPlaylist() if err != nil { console := console.GetPtr() console.Printf(err.Error()) } } makeDance := func(musicType string) (dance *Dance) { dance = new(Dance) dance.Name = musicType dance.MusicType = []string{musicType} switch musicType { case "hiphop": dance.Motions = []string{"покачивания телом вперед и назад", "ноги в полу-присяде", "руки согнуты в локтях", "головой вперед-назад"} case "rap": dance.Motions = []string{"покачивания телом вперед и назад", "ноги в полу-присяде", "руки согнуты в локтях", "головой вперед-назад"} case "pop": dance.Motions = []string{"покачивания телом вперед и назад", "ноги в полу-присяде", "руки согнуты в локтях", "головой вперед-назад"} case "house": dance.Motions = []string{"покачивания телом вперед и назад", "ноги в полу-присяде", "руки согнуты в локтях", "головой вперед-назад"} } return } makePeople := func() { musicTypes := []string{"rap", "hiphop", "pop", "house"} musicTypes_length := len(musicTypes) nameGen := new(vydumschik.Name) // console := console.GetPtr() capacity := n.Capacity for capacity > 0 { gender := RandomGender() human := new(Human) human.Name = nameGen.Full_name(gender) human.Gender = gender type_size := Random(1, musicTypes_length) for type_size > 0 { musicType := musicTypes[Random(0, musicTypes_length)] human.PushDance(makeDance(musicType)) type_size-- } if ok := n.PushHuman(human); ok { // console.Printf("added human: %s", human.Name) } capacity-- } } makePlaylist() makePeople() }
func init() { quitParserChan = make(chan bool, 99) statusChan = make(chan int) totalChan = make(chan int) errorChan = make(chan error) c_ptr := console.GetPtr() c_ptr.AddCommand("scan", func(key, value string, help *string) { if value == "help" { *help = "start scanning http://mds-club.ru, very slow process" } usage_start := "usage: scan <start|stop:string> <start:int> <stop:int>" cmd := strings.Split(value, " ") if (cmd[0] == "start" && len(cmd) != 3) || (cmd[0] == "stop" && len(cmd) != 1) { c_ptr.Printf(usage_start) return } info := func(s string) { c_ptr.Printf("{\"scan_status\":{\"info\":\"%s\"}}", s) } launched := func() { status = "launched" c_ptr.Printf("{\"scan_status\":{\"status\":\"launched\"}}") } stopped := func() { status = "stopped" c_ptr.Printf("{\"scan_status\":{\"status\":\"stopped\"}}") } switch cmd[0] { case "start": start, err := strconv.Atoi(cmd[1]) stop, err := strconv.Atoi(cmd[2]) if err != nil { c_ptr.Printf(usage_start) return } if status == "launched" { return } launched() current_element = 0 go func() { info("get the number of records") total, err := GetTotalElements(URL) if err != nil { errorChan <- err return } totalChan <- total info(fmt.Sprintf("total records: %d", total)) // scan err = scanCatalog(URL, start, stop) if err != nil { errorChan <- err } stopped() }() case "stop": if status != "launched" { return } quitParserChan <- true case "status": c_ptr.Printf("{\"scan_status\":{\"status\":\"%s\"}}", status) default: } }) go func() { current_element = 0 var total int for { select { case current := <-statusChan: c_ptr.Printf("{\"scan_status\":{\"total\":%d,\"current\":%d}}", total, current) case t := <-totalChan: total = t case err := <-errorChan: c_ptr.Printf("{\"scan_status\":{\"error\":\"%s\"}}", err.Error()) default: time.Sleep(time.Millisecond * 500) } } }() }