diff --git a/commands.go b/commands.go index 1a14678..5ab5fc3 100644 --- a/commands.go +++ b/commands.go @@ -278,6 +278,11 @@ func runCommand(conn *Connection, name string, args ...string) { fmt.Fprintf(conn, "command %s can not be used while in transit\n", name) return } + + if conn.IsMining() { + conn.StopMining() + } + cmd.handler(conn, args...) } diff --git a/connection.go b/connection.go index ec96758..370f4b9 100644 --- a/connection.go +++ b/connection.go @@ -3,6 +3,7 @@ package main import ( "bufio" "fmt" + "io" "net" "strings" "time" @@ -137,6 +138,28 @@ func (c *Connection) SendBomb(target *System) { fmt.Fprintf(c, "sending bomb to system %v\n", target.Label()) } +func (c *Connection) ReadLines(out chan []string) { + defer close(out) + + for { + line, err := c.ReadString('\n') + switch err { + case io.EOF: + return + case nil: + break + default: + log_error("unable to read line on connection: %v", err) + return + } + line = strings.TrimSpace(line) + if line == "" { + continue + } + out <- strings.Split(line, " ") + } +} + func (c *Connection) land() { fmt.Fprintf(c, "you have arrived at %v\n", c.dest.Label()) c.location = c.dest diff --git a/main.go b/main.go index 625a638..42cb7ad 100644 --- a/main.go +++ b/main.go @@ -3,12 +3,10 @@ package main import ( "flag" "fmt" - "io" "log" "math/rand" "net" "os" - "strings" "time" ) @@ -52,28 +50,11 @@ func handleConnection(conn *Connection) { conn.Login() conn.Respawn() - for { - line, err := conn.ReadString('\n') - switch err { - case io.EOF: - return - case nil: - break - default: - log_error("failed to read line from player %s: %v", conn.PlayerName(), err) - return - } - line = strings.TrimSpace(line) - if conn.IsMining() { - conn.StopMining() - } - - if line == "" { - continue - } - parts := strings.Split(line, " ") + c := make(chan []string) + go conn.ReadLines(c) + for parts := range c { if isCommand(parts[0]) { runCommand(conn, parts[0], parts[1:]...) continue @@ -85,6 +66,7 @@ func handleConnection(conn *Connection) { default: fmt.Fprintf(conn, "hmm I'm not sure I know that one.\n") } + } }