From fd40042ed3ddd7c41c3e0248f752787e5b73cbc7 Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Sat, 8 Nov 2014 05:55:14 -0500 Subject: [PATCH] revamp command structure --- commands.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 5 +++++ session.go | 11 ++++++++++- system.go | 1 + 4 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 commands.go diff --git a/commands.go b/commands.go new file mode 100644 index 0000000..66b7300 --- /dev/null +++ b/commands.go @@ -0,0 +1,51 @@ +package main + +import ( + "fmt" +) + +var commandRegistry map[string]*Command + +type Command struct { + name string + help string + handler func(*Connection, ...string) +} + +// var scanCommand = &Command{ +// name: "scan", +// help: "scans for resources", +// handler: func(conn *Connection, args ...string) { +// }, +// } + +var infoCommand = &Command{ + name: "info", + help: "gives you some info about your current position", + handler: func(conn *Connection, args ...string) { + fmt.Fprintf(conn, "current planet: %s\n", conn.System().name) + }, +} + +func isCommand(name string) bool { + _, ok := commandRegistry[name] + return ok +} + +func runCommand(conn *Connection, name string, args ...string) { + cmd, ok := commandRegistry[name] + if !ok { + fmt.Fprintf(conn, "no such command: %s\n", name) + return + } + cmd.handler(conn, args...) +} + +func registerCommand(c *Command) { + commandRegistry[c.name] = c +} + +func init() { + commandRegistry = make(map[string]*Command, 16) + registerCommand(infoCommand) +} diff --git a/main.go b/main.go index 25d24b2..7ad22a2 100644 --- a/main.go +++ b/main.go @@ -63,6 +63,11 @@ func handleConnection(conn *Connection) { } line = strings.TrimSpace(line) parts := strings.Split(line, " ") + if isCommand(parts[0]) { + runCommand(conn, parts[0], parts[1:]...) + continue + } + switch parts[0] { case "scan": for _, otherPlanet := range index { diff --git a/session.go b/session.go index cdb7715..7478c5c 100644 --- a/session.go +++ b/session.go @@ -10,7 +10,8 @@ import ( type Connection struct { net.Conn *bufio.Reader - player *Player + player *Player + location *System } func NewConnection(conn net.Conn) *Connection { @@ -52,6 +53,14 @@ func (c *Connection) Login() { } +func (c *Connection) SetSystem(s *System) { + c.location = s +} + +func (c *Connection) System() *System { + return c.location +} + func (c *Connection) Close() error { log_info("player disconnecting: %s", c.PlayerName()) return c.Conn.Close() diff --git a/system.go b/system.go index 341ecb7..a435eb3 100644 --- a/system.go +++ b/system.go @@ -21,6 +21,7 @@ type System struct { } func (s *System) Arrive(p *Connection) { + p.SetSystem(s) log_info("player %s has arrived at system %s", p.PlayerName(), s.name) if s.players == nil { s.players = make(map[*Connection]bool, 8)