Skip to content

Commit

Permalink
Add error handling to fmt.Fprintln()
Browse files Browse the repository at this point in the history
  • Loading branch information
lfcd85 committed Jun 18, 2019
1 parent 401c362 commit f947f81
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions kadai3-1/lfcd85/typinggame/typinggame.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"math/rand"
"os"
"time"

"github.com/hashicorp/go-multierror"
)

// Words stores a slice of words which is used for the game.
Expand All @@ -21,38 +23,42 @@ type Game struct {

// Execute starts the game using standard input and output.
func Execute(g Game) error {
g.run(inputChannel(os.Stdin), os.Stdout)
return nil
err := g.run(inputChannel(os.Stdin), os.Stdout)
return err
}

func (g *Game) run(ch <-chan string, w io.Writer) {
func (g *Game) run(ch <-chan string, w io.Writer) error {
var result error

bc := context.Background()
ctx, cancel := context.WithTimeout(bc, g.TimeLimit)
defer cancel()

fmt.Fprintln(w, "Let's type the standard package names! ( Time limit:", g.TimeLimit, ")")
result = printWithMultiErr(w, result, "Let's type the standard package names! ( Time limit:", g.TimeLimit, ")")

var score int
rand.Seed(time.Now().UnixNano())
word := g.Words[rand.Intn(len(g.Words))]
LOOP:
for {
fmt.Fprintln(w, ">", word)
result = printWithMultiErr(w, result, ">", word)
select {
case input := <-ch:
if input == word {
score++
fmt.Fprintln(w, input, "... OK! current score:", score)
result = printWithMultiErr(w, result, input, "... OK! current score:", score)
word = g.Words[rand.Intn(len(g.Words))]
} else {
fmt.Fprintln(w, input, "... NG: try again.")
result = printWithMultiErr(w, result, input, "... NG: try again.")
}
case <-ctx.Done():
fmt.Fprintln(w)
fmt.Fprintln(w, g.TimeLimit, "has passed: you correctly typed", score, "package(s)!")
result = printWithMultiErr(w, result)
result = printWithMultiErr(w, result, g.TimeLimit, "has passed: you correctly typed", score, "package(s)!")
break LOOP
}
}

return result
}

func inputChannel(r io.Reader) <-chan string {
Expand All @@ -66,3 +72,10 @@ func inputChannel(r io.Reader) <-chan string {
}()
return ch
}

func printWithMultiErr(w io.Writer, result error, a ...interface{}) error {
if _, err := fmt.Fprintln(w, a...); err != nil {
result = multierror.Append(result, err)
}
return result
}

0 comments on commit f947f81

Please sign in to comment.