Ejemplo n.º 1
0
// Attack an enemy during an encounter.
func (c *Character) Attack(e Enemy) {
	// Fight until enemy is dead, or player is below 25%.
	red := color.New(color.FgRed, color.Bold).SprintFunc()
	log.Printf("Attacking enemy: %s\n", red(e.Name))
	playerHpLimit := int(float64(c.Hp) * 0.25)
	playerDamage := c.Body.Weapond.Dmg - e.Armor
	if playerDamage <= 0 {
		playerDamage = 1
	}
	enemyDamage := e.Damage - (c.Body.Head.Armor + c.Body.Armor.Armor + c.Body.Shield.Armor + c.Body.LRing.Armor + c.Body.RRing.Armor)
	if enemyDamage <= 0 {
		enemyDamage = 1
	}
	for c.Hp > playerHpLimit && e.Hp > 0 {
		e.Hp -= playerDamage
		c.Hp -= enemyDamage
	}
	if e.Hp <= 0 {
		color.Set(color.FgCyan)
		log.Println("Player won!")
		color.Unset()
		c.CurrentXp += e.Xp
		displayProgressBar(c.CurrentXp, c.NextLevelXp)
		c.awardItems(e)
		mdb.Update(*c)
		return
	}
	color.Set(color.FgHiRed)
	log.Println("Enemy won. Player has fled with hp: ", c.Hp)
	color.Unset()
	mdb.Update(*c)
}
Ejemplo n.º 2
0
func (r Results) print(limit int) {
	i := 0
	if r.ResultType == "exact" {
		for _, def := range r.List {
			if limit == -1 || i < limit {
				// ugly code for windows!
				color.Set(color.FgBlue)
				fmt.Printf("%d)\n", i+1)
				color.Unset()

				color.Set(color.FgGreen)
				fmt.Printf("%s\n", "Def:")
				color.Unset()
				fmt.Println(def.Definition)

				color.Set(color.FgGreen)
				fmt.Printf("%s\n", "Eg:")
				color.Unset()
				fmt.Printf("%s\n\n", def.Example)
				i++
			}
		}
	} else {
		color.Red("No definitions.\n")
		return
	}
}
Ejemplo n.º 3
0
func (state *state) printBoard() {
	board := state.board
	fmt.Println()
	fmt.Print("    ")
	for _, c := range "abcdefgh" {
		fmt.Print(fmt.Sprintf("%c    ", c))
	}
	fmt.Println()
	for i := 0; i < N; i++ {
		for k := 0; k < 3; k++ {
			if k == 1 {
				fmt.Print(fmt.Sprintf(" %d", N-i))
			} else {
				fmt.Print("  ")
			}
			for j := 0; j < N; j++ {
				cp := colors[boardColors[i][j]]
				color.Set(cp.bg)
				fmt.Print("  ")
				piece := board[i][j]
				if k == 1 && piece != nil {
					color.Unset()
					color.Set(colors[piece.Color].fg)
					if piece.Player == humanPlayer {
						fmt.Print("X")
					} else {
						fmt.Print("O")
					}
				} else {
					fmt.Print(" ")
				}
				color.Set(cp.bg)
				fmt.Print("  ")
			}
			color.Unset()
			if k == 1 {
				fmt.Print(N - i)
			}
			fmt.Println()
		}
	}
	fmt.Print("    ")
	for _, c := range "abcdefgh" {
		fmt.Print(fmt.Sprintf("%c    ", c))
	}
	fmt.Println()
	fmt.Println()
}
Ejemplo n.º 4
0
// all logging functions call this `log` function
func (console *Logger) log(d logDetails, colorAttr color.Attribute, isBold bool, format string, args ...interface{}) {
	// Only print out, logs that are the selected level or higher
	if console.level >= d.level {
		newlog := color.Set(colorAttr)
		defer color.Unset()

		// if the request is to log bold text
		if isBold {
			newlog.Add(color.Bold)
		}

		// Check to see if we are to add background color
		// Alert and Fatal have background colors
		switch d.level {
		case 1: // for Fatal
			color.Set(color.BgRed)
			break
		case 2: // for Alerts
			color.Set(color.BgMagenta)
			break
		}

		// I want it log both into the file and on the console
		console.LogFile.Printf(format, args...)
		log.Printf(format, args...)
	}
}
Ejemplo n.º 5
0
func (selector *Selector) Select() (err error) {
	var choice int
	var input string
	retValue := selector.ConfKeeper.Get(bConfList)
	err = retValue.Error
	if err != nil {
		return
	}
	lenConfList := len(retValue.Value.([]interface{}))
	err = fmt.Errorf("")
	stdin := bufio.NewReader(os.Stdin)
	for err != nil {
		err = selector.OutputChoices()
		if err != nil {
			return
		}
		_, err = fmt.Scanf("%s", &input)
		stdin.ReadString('\n')

		if err != nil {
			Out("Error:", err.Error(), "\n\n")
			Out("\n", bigseparator, "\n\n")
			continue
		}
		input = strings.TrimSpace(input)
		var outputColor color.Attribute
		switch input {
		case "q", "--":
			choice = -1
			err = nil
		default:
			choice, err = strconv.Atoi(input)
			if err != nil {
				outputColor = color.FgRed
				err = fmt.Errorf("Your input is not integer number or code to exit!")
			}
		}
		if err == nil {
			switch {
			case choice < -1 || choice >= lenConfList:
				outputColor = color.FgMagenta
				err = fmt.Errorf("%d is out of range [ -1, %d ]!", choice, lenConfList-1)
			default:
				outputColor = color.FgCyan
				err = nil
			}
		}
		Out("\nYou selected ")
		color.Set(outputColor, color.Bold)
		Out(input)
		color.Unset()
		Out(".\n\n")
		if err != nil {
			Out(err.Error(), "\n")
			Out("\n", bigseparator, "\n\n")
		}
	}
	err = selector.ConfKeeper.Set(bSelected, strconv.Itoa(choice)).Error
	return
}
Ejemplo n.º 6
0
func exec(cmd *cobra.Command, args []string) {
	if len(args) == 1 {
		color.Green("Creando nueva aplicacion " + args[0])
		gopath := os.Getenv("GOPATHs")
		if gopath == "" {
			color.Set(color.FgRed)
			defer color.Unset()
			log.Fatalln("GOPATH no found :(")

			os.Exit(2)
		}
		src := fmt.Sprintf("%s\\src", gopath)
		appName := args[0]
		appDir := fmt.Sprintf("%s\\%s", src, appName)

		createAppFolder(appDir, []string{})
		fmt.Printf("appDir: %s\n", appDir)
		createAppFolder(fmt.Sprintf("%s\\%s", appDir, "public"), []string{"assets"})
		createAppFolder(fmt.Sprintf("%s\\%s", appDir, "app"), []string{"controllers", "models"})

		createSubFolder(fmt.Sprintf("%s\\%s\\%s", appDir, "public", "assets"), []string{"js", "scss", "img", "fonts"})
		// creamos la estructura basica

	}
}
Ejemplo n.º 7
0
func debugResponse(res *http.Response) {
	if debug {
		color.Set(color.FgCyan)
		doDebug(httputil.DumpResponse(res, true))
		color.Unset()
	}
}
Ejemplo n.º 8
0
func debugRequest(req *http.Request) {
	if debug {
		color.Set(color.FgMagenta)
		doDebug(httputil.DumpRequestOut(req, true))
		color.Unset()
	}
}
Ejemplo n.º 9
0
// returns a function that will format and writes the line extracted from the logs of a given container
func write(prefix string, color *ansi.Color, timestamps bool) func(dest io.Writer, token []byte) (n int, err error) {
	return func(dest io.Writer, token []byte) (n int, err error) {
		countingWriter := countingWriter{Writer: dest}
		if color != nil {
			ansi.Output = &countingWriter
			color.Set()
		}
		_, err = countingWriter.Write([]byte(prefix))
		if err == nil {
			if !timestamps {
				// timestamps are always present in the incoming stream for
				// sorting purposes, so we strip them if the user didn't ask
				// for them
				const timestampPrefixLength = 31
				strip := timestampPrefixLength
				if string(token[0]) == "[" {
					// it seems that timestamps are wrapped in [] for events
					// streamed  in real time during a `docker logs -f`
					strip = strip + 2
				}
				token = token[strip:]
			}
			_, err = countingWriter.Write(token)
		}
		if err == nil {
			if color != nil {
				ansi.Unset()
			}
			_, err = dest.Write([]byte("\n"))
		}
		return countingWriter.written, err

	}
}
Ejemplo n.º 10
0
func printResult(message string, c color.Attribute) {
	print("[")
	color.Set(c)
	print(message)
	color.Unset()
	println("]")
}
Ejemplo n.º 11
0
// Rest will Replenish Health.
func (c *Character) Rest() {
	c.Hp = c.MaxHp
	color.Set(color.FgBlue)
	log.Println("Player is fully rested.")
	color.Unset()
	mdb.Update(*c)
}
Ejemplo n.º 12
0
func OutputTests() {
	for _, test := range tests {
		fmt.Printf("%s: expected ", test.function)

		if len(test.attributes) > 0 {
			color.Set(test.attributes...)
		}
		fmt.Print(test.expected)
		if len(test.attributes) > 0 {
			color.Unset()
		}
		fmt.Print(", actual ")
		switch test.function {
		case "Debug":
			Debug(test.input...)
		case "Log":
			Log(test.input...)
			fmt.Print("\nFor output, look at file ", logFileName)
		case "Print":
			Print(test.input...)
		case "Out":
			Out(test.input...)
			fmt.Print("\nFor other output, look at file ", logFileName)
		}
		fmt.Println()
	}
}
Ejemplo n.º 13
0
func printDiffYaml(m map[interface{}]interface{}, indent string) {
	sortedMap := make([]string, len(m))
	i := 0
	for k, _ := range m {
		sortedMap[i] = k.(string)
		i++
	}
	sort.Strings(sortedMap)

	for _, v := range sortedMap {
		key := v
		value := m[key]
		if reflect.TypeOf(value).Kind() == reflect.Map {
			println(indent + key + ":")
			printDiffYaml(m[key].(map[interface{}]interface{}), indent+"    ")
		} else {
			tmp := value.(Comparer)
			println(indent + key + ":")
			color.Set(color.FgRed)
			printValue(tmp.leftValue, indent+"  - ")
			color.Set(color.FgGreen)
			printValue(tmp.rightValue, indent+"  + ")
			color.Unset()
		}

	}
}
Ejemplo n.º 14
0
Archivo: log.go Proyecto: gocore/goal
// Write is used for writing to predefined output using
// foreground color we want.
func (c *context) Write(p []byte) (n int, err error) {
	// Set the color that has been registered for this logger.
	c.c.Set()
	defer color.Unset() // Don't forget to stop using after we're done.

	// Write the result to writer.
	return c.w.Write(p)
}
Ejemplo n.º 15
0
func writeError(format string, err error, a ...interface{}) {
	color.Set(color.FgRed)
	fmt.Fprintf(os.Stderr, format+"\n", a...)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
	color.Unset()
}
Ejemplo n.º 16
0
// Ask the amount of the selected ingredient
func (b *bread) askAmount(starter string) int {
	color.Set(color.FgWhite)
	fmt.Printf("Enter the amount of %s in grams: ", starter)
	color.Unset()

	var amount, _ = b.reader.ReadString('\n')
	var intAmount, err = strconv.Atoi(strings.TrimSpace(amount))

	if err != nil {
		color.Set(color.FgRed)
		fmt.Println("Wrong amount. Try again!")
		color.Unset()
		return b.askAmount(starter)
	}

	return intAmount
}
Ejemplo n.º 17
0
func sshKeysHelp() {
	color.Set(color.FgYellow)
	print("")
	print("a - Add")
	print("D - Delete")
	print("? - Help")
	print("b - Back")
	color.Unset()
}
Ejemplo n.º 18
0
func variableMenu() {
	color.Set(color.FgYellow)
	print("")
	print("a - Add")
	print("D - Delete")
	print("? - Help")
	print("b - Back")
	color.Unset()
}
Ejemplo n.º 19
0
Archivo: hn.go Proyecto: sspencer/go-hn
func displayRSS(items []Item) {
	for i, item := range items {
		index := i + 1
		color.Set(color.FgRed)
		fmt.Printf("%2d.", index)
		color.Unset()
		fmt.Printf(" %s\n", item.Title)
	}
}
Ejemplo n.º 20
0
func Print(args ...interface{}) {
	formated := Format(args...)
	if len(formated.Attributes) > 0 {
		color.Set(formated.Attributes...)
	}
	fmt.Print(formated.Text)
	if len(formated.Attributes) > 0 {
		color.Unset()
	}
}
Ejemplo n.º 21
0
// Ask for the type of bread
func (b *bread) askType() int {
	color.Set(color.FgWhite)
	fmt.Println("What type of bread are you making?")
	color.Unset()

	// Print each type of bread sequentially
	for i, v := range breadIndex {
		fmt.Printf("%d. %s\n", i+1, strings.Title(v))
	}

	color.Set(color.FgWhite)
	fmt.Print("Type the corresponding number (Default: Standard): ")
	color.Unset()

	var breadType, _ = b.reader.ReadString('\n')
	breadType = strings.TrimSpace(breadType)

	// No input sets the default type of bread
	if breadType == "" {
		return 0
	}

	var breadTypeInt, err = strconv.Atoi(breadType)

	if err != nil {
		color.Set(color.FgRed)
		fmt.Println("Wrong input. Try again!")
		color.Unset()
		b.askType()
	}

	if breadTypeInt == 0 || breadTypeInt > len(breadIndex) {
		color.Set(color.FgRed)
		fmt.Println("No bread type with the input number. Try again!")
		color.Unset()
		b.askType()
	}

	// Convert the input to a 0-based index for
	// the types of bread slice
	return breadTypeInt - 1
}
Ejemplo n.º 22
0
// SellItems will clear the inventory.
func (c *Character) SellItems() {
	for _, v := range c.Inventory.Items {
		c.Gold += v.Value
	}
	yellow := color.New(color.FgYellow).SprintFunc()
	color.Set(color.FgBlue)
	log.Printf("Player has sold all items. Current gold is: %s\n", yellow(c.Gold))
	color.Unset()
	c.Inventory.Items = []Item{}
	mdb.Update(*c)
}
Ejemplo n.º 23
0
func mainMenu() {
	color.Set(color.FgYellow)
	print("")
	print("a - AWS Key")
	print("s - SSH Keys")
	print("v - Variables")
	print("d - Environment Duration")
	print("? - Help")
	print("q - Quit")
	color.Unset()
}
Ejemplo n.º 24
0
// Render table output
func (t Table) Render() {
	if t.border {
		t.printLine(true)
	}
	color.Set(color.BgBlue)
	color.Set(color.Bold)
	color.Set(color.CrossedOut)
	t.printHeading()
	color.Unset()
	color.Set(color.BgCyan)
	color.Set(color.FgBlack)
	t.printRows()
	color.Unset()

	if !t.rowLine && t.border {
		t.printLine(true)
	}
	t.printFooter()

}
Ejemplo n.º 25
0
func (selector *Selector) OutputChoices() (err error) {
	var confList []interface{}
	retValue := selector.ConfKeeper.Get(bConfList)
	confList, err = retValue.Value.([]interface{}), retValue.Error
	if err != nil {
		return
	}

	Out("Choose your application:\n\n")
	var (
		curAppName, curConfSrc string
		appName                interface{}
	)

	retValue = selector.ConfKeeper.Get(Key(bCurrent, kApp))
	err = retValue.Error
	if err == nil {
		curAppName = retValue.Value.(map[string]interface{})[kName].(string)
		curConfSrc = retValue.Value.(map[string]interface{})[kConfSrc].(string)
	}
	color.Set(color.FgGreen, color.Bold)
	for key, value := range confList {
		retValue = selector.ConfKeeper.Get(Key(bConfData, key, kApp, kName))
		appName, err = retValue.Value, retValue.Error
		if err != nil {
			color.Unset()
			return
		}
		if curAppName == appName && curConfSrc == value {
			color.Set(color.FgYellow, color.Bold)
			Out("?:Current: %2d. %-30v == %v\n", key, appName, value)
			color.Set(color.FgGreen, color.Bold)
		} else {
			Out("?:         %2d. %-30v == %v\n", key, appName, value)
		}
	}
	//Out(bigseparator, "\n\n")
	color.Unset()
	Out("\nWrite number of selected application from list printed above\n\nor q, -- or -1 to exit: ")
	return
}
Ejemplo n.º 26
0
func awsMenu() {
	color.Set(color.FgYellow)
	print("")
	print("k - Key")
	print("m - MFA")
	print("r - Role")
	print("s - Show Key")
	print("D - Delete")
	print("? - Help")
	print("b - Back")
	color.Unset()
}
Ejemplo n.º 27
0
func sendSMS(dev *gsmmodem.Device, message string, phoneNumber string) {
	defer color.Unset()
	log.Printf("Отправка сообщения на номер: %s\n", phoneNumber)
	err := dev.SendLongSMS(message, sms.PhoneNumber(phoneNumber))
	if err != nil {
		color.Set(color.FgHiRed)
		log.Printf("Ошибка отправки сообщения: %s\n", err.Error())
	} else {
		color.Set(color.FgHiGreen)
		log.Printf("Сообщение отправлено на номер: " + phoneNumber)
	}
}
Ejemplo n.º 28
0
// StateMonitor provides a sane way to listen for state changes in the
// application. New state is passed via channels outputting logs from anywhere
// in the application.
func StateMonitor() {
	for {
		select {
		case worker := <-WorkerStarted:
			color.Set(color.Bold, color.FgBlue)
			log.Println("Started Worker", worker.id)
			color.Unset()
		case worker := <-WorkerSleeping:
			color.Set(color.Faint)
			log.Println("Worker", worker.id, "sleeping for", AppConfig.WorkInterval, "seconds")
			color.Unset()
		case task := <-TaskScheduled:
			color.Set(color.Bold, color.FgYellow)
			log.Println("Task", task.id, "scheduled to run at", task.nextRun.Format(time.UnixDate))
			color.Unset()
		case task := <-TaskDequeued:
			color.Set(color.Bold, color.FgRed)
			log.Println("Task", task.id, "dequeued")
			color.Unset()
		case data := <-TaskStarted:
			color.Set(color.Bold)
			for worker, task := range data {
				log.Println("Worker", worker.id, "picked up task", task.id)
			}
			color.Unset()
		case data := <-TaskFinished:
			color.Set(color.Bold, color.FgGreen)
			for worker, task := range data {
				log.Println("Worker", worker.id, "finished task", task.id)
			}
			color.Unset()
		}
	}
}
Ejemplo n.º 29
0
func (b *bread) print(formula map[string]int) {
	fmt.Println("---------------------------------------")

	color.Set(color.FgWhite)
	fmt.Println("Formula:")
	color.Unset()

	color.Set(color.FgCyan)
	fmt.Printf("%s: %d gr\n", strings.Title(WATER), formula[WATER])
	fmt.Printf("%s: %d gr\n", strings.Title(FLOUR), formula[FLOUR])
	fmt.Printf("%s: %d gr\n", strings.Title(YEAST), formula[YEAST])
	fmt.Printf("%s: %d gr\n", strings.Title(SALT), formula[SALT])
	color.Unset()

	fmt.Println()

	color.Set(color.FgWhite)
	fmt.Println("General Guidelines:")
	color.Unset()

	fmt.Println("Knead for 10-12 minutes with a stand mixer, or up to 20 minutes by hand. Bake for 15 minutes in 215°C by spraying water every 5 minutes, then bake for another 15 minutes in 230°C.")
}
Ejemplo n.º 30
0
func consoleInputNumber(dev *gsmmodem.Device, message string) {
	defer color.Unset()
	fmt.Print("Введите номер для отправки смс: ")
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		text := scanner.Text()
		if isExitCommand(text) {
			break
		}

		phoneNumber, err := normalizePhoneNumber(text)
		if err != nil {
			color.Set(color.FgHiRed)
			fmt.Println(err)
			color.Unset()
			fmt.Print("Введите номер заново: ")
			continue
		}

		sendSMS(dev, message, phoneNumber)
		fmt.Print("Введите номер для отправки смс: ")
	}
}