Skip to content

Instantly share code, notes, and snippets.

@marioidival
Last active July 28, 2017 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marioidival/6b1c6086e8a846fbb286e630d333b35d to your computer and use it in GitHub Desktop.
Save marioidival/6b1c6086e8a846fbb286e630d333b35d to your computer and use it in GitHub Desktop.
Go Context - IDEIAS

Criar um programa para simular os personagens de Dragon Ball aumentando o Ki...

package main
import (
"context"
"fmt"
"log"
"time"
)
type Person interface {
Name() string
Power() int
RaisePower()
}
type Sayajin struct {
PName string
Ki int
Race string
}
func (s *Sayajin) Power() int {
return s.Ki
}
func (s *Sayajin) RaisePower() {
s.Ki = s.Ki * 2
}
func (s *Sayajin) Name() string {
return s.PName
}
type Human struct {
PName string
Ki int
Race string
}
func (h *Human) RaisePower() {
h.Ki = h.Ki + (h.Ki / 8)
}
func (h *Human) Name() string {
return h.PName
}
func (h *Human) Power() int {
return h.Ki
}
func RaisePersonKi(p Person) {
log.Printf("%s raising your power!", p.Name())
p.RaisePower()
log.Printf("KI %d\n", p.Power())
}
func main() {
goku := &Sayajin{PName: "Son Goku", Ki: 1000, Race: "Sayajin"}
kuririn := &Human{PName: "Kuririn", Ki: 1000, Race: "Human"}
persons := []Person{goku, kuririn}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for {
go func(ctx context.Context, cancel context.CancelFunc, ps []Person) {
for _, p := range ps {
RaisePersonKi(p)
if p.Power() > 8000 {
cancel()
}
}
}(ctx, cancel, persons)
select {
case <-time.After(1 * time.Second):
fmt.Println("Raising...")
case <-ctx.Done():
fmt.Println("Cancel")
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment