Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: languages

Concurrency in Go with Channels and Goroutines

So far I’ve been walking myself through learning some of the basic features of the Go language and I’ve been impressed with what I’ve seen. I still have this nagging feeling that Go is a solution looking for a problem and I haven’t decided if that’s because I haven’t yet had that “a-ha!” moment where I figure out what problem Go solves miraculously or if it’s just because I’ve only been poking around with it for a few days.

Concurrency is one of the more heavily lauded features of the language, but the community is quick to remind you that concurrency is not parallelism. I won’t go into detail on that subject because it’s a really meaty one and I just want to provide a quick introduction to concurrency here.

The way to think about goroutines is that they are very small, light-weight chunks of processing that you compose in order to chew up a larger task. There may be a correlation here between goroutines and actors and in terms of design, I’ve noticed a near 1:1 correlation between what I would normally code into an actor with what I find being coded into goroutines in samples. The way goroutines communicate with each other and the rest of your code is through channels which can send and receive messages.

One distinction that I think is unique to Go is that sending and receiving on channels is a synchronizing operation. In other words, if you use the arrow notation (<-) to receive a value from a channel, you will block until you receive that value. Conversely, if you send a value on a channel, the code that sent the value will be blocked until some other goroutine plucks that value off the channel .You can get around this with buffered channels, but it seems to be a fundamental thing that goroutines synchronize via communication rather than shared memory.

In my little sample, I decided to take the synchronization “hello world” of a producer and a consumer and implement it in Go. In the following code, I’ve got a type called StockTick and I’ve created a channel that carries stock ticks (channels are strongly typed). I invoke a producer and a consumer and thus have two separate blocks of code communicating with each other:

package main

import (
	"fmt"
	"math/rand"
)

type StockTick struct {
	Ask		float32
	Bid		float32
	Symbol	string
}

func genTick() (tick StockTick) {
	tick.Ask = 45 * rand.Float32()
	tick.Bid = 42.50 * rand.Float32()
	tick.Symbol = "IBM"
	return tick
}

func produceTicks(stocks chan StockTick) {
	for x:=1; x<100; x++ {
		stocks <- genTick()
	}
	close(stocks)
}

func consumeTicks(stocks chan StockTick) {
	for stock := range stocks {
		fmt.Printf("Consumed a tick %v\n", stock)
	}
}

func main() {
	fmt.Printf("Stock Channels FTW\n\n")
	stocks := make(chan StockTick)
	go produceTicks(stocks)
	consumeTicks(stocks)
}

There are a couple of things that I found interesting in this code that caught me by surprise. The first is that I had to close the stocks channel when I was done producing. This is because the range operator creates a deadlock if the code reaches a point where it knows that there can be no more values to consume (the producer goroutine is done). You can get around this in real-world apps where you plan on consuming all day with an infinite loop, but in this case I knew I was done so calling close(stocks) is actually what allows the range operator to terminate in a friendly way without a deadlock.

Next, notice that I used the go keyword to fire off the produceTicks method as an asynchronous goroutine but I didn’t do that for consumeTicks. This is because if I let them both be asynchronous in the background, the main() function would terminate, which kills the go application. In a go app, as soon as main() exits, the entire app quits, even if you have active goroutines.

There are a number of higher-level patterns that you can implement with channels such as sync’ing on acknowledgements sent back on the channel from which a value is received and using a “fan-in” approach where you’re pulling from multiple channels to produce values on a single channel so that you aren’t waiting in lock-step for values to arrive in sequence across channels. As this is still just a series of blog posts covering my introduction to the language, I won’t cover those yet.

As I said, I am still unsure whether I have any problems that Go would be ideal to solve, but I am going to keep plugging away until I decide one way or the other.

Implicit Interfaces in Go

In my continuing obsession with learning a new language, I’ve gotten to the point in experimenting with Go that I want to know what all this implicit interface stuff is about. In my previous blog post, I talked about how Go doesn’t actually have classes, but rather it has explicit receiver functions that look like they are methods being invoked on an object.

The rumor on the street is that Go has a facility similar to duck typing in that when you declare an interface, anything can be said to implement that interface as long as that thing has all of the method definitions declared in the interface. This isn’t entirely unique – dynamic languages are full of stuff like this and Scala’s got the ability to define type aliases that do the same thing. The curious thing about Go’s implicit interface satisfaction is that it is compile-time checked. That’s right – your code won’t compile if you have code that attempts to convert an object into an interface that it can’t satisfy.

Let’s take a real-world example: wielding a chair (what, that’s not real-world to you?). When building MUDs and even some more modern game types, you often run into this type of thing. If a developer didn’t originally intend for an object to be used as a weapon, it can’t be treated like one. But, what if you want to make it so that the player can wield a chair as easily as a sword? Sure, they will have different behavioral characteristics, but you should still be able to wield either.

In a classic programming language problem, this is easy to solve: Create an interface called Wieldable (or IWieldable if you’re a .NET person) and then two classes that both implement that interface: Chair and Sword. In Go, you still create a Wieldable interface that defines a Wield() method, but the difference is you never create a class nor do you explicitly indicate what interface you’re implementing. If there’s an explicit receiver in scope called Wield() for that object, then your code can treat it as a wieldable.

Let’s take a look at some code:

// interfaces
package main

import (
	"fmt"
)

type Wieldable interface {
	Wield()
}

type Chair struct {
	Legs	int
	Wielded bool
	Name	string
}

type Sword struct {
	DamageRating	int
	Wielded			bool
	Name			string
}

type Test struct {
	Wieldy		Wieldable
}

func (s *Sword) Wield() {
	fmt.Printf("Wielding Sword %s\n", s.Name)
	s.Wielded = true
}

func (c *Chair) Wield() {
	fmt.Printf("Wielding Chair %s\n", c.Name)
	c.Wielded = true
}

func main() {
	fmt.Println("Hello World!")

	s := Sword{
		DamageRating: 12,
		Wielded: false,
		Name: "Sword of Doom",
	}

	c := Chair{
		Legs: 4,
		Wielded: false,
		Name: "Death Seat",
	}

	t := Test {
		Wieldy: &s,
	}

	t2 := Test {
		Wieldy: &c,
	}

	t.Wieldy.Wield()
	t2.Wieldy.Wield()
}

In this code I am creating a Sword struct and a Chair struct and then I created an interface called Wieldable and another struct called Wieldy which holds a Wieldable object. To prove that I can convert between Chair/Sword and Wieldable, I create two test objects – each holding a Wieldable converted from either a sword and I then call the Wield() method on each.

So here’s something unexpected – this is a one-way conversion. In a runtime managed language when you typecast a reference to an object from one type to another, the actual underlying object remains unchanged and you get a runtime-limited view onto that object. For example, if you’ve created some serializable object called Zombie, you can cast that to a Serializable and then still get back the original zombie. If you attempt to get a Sword object out of a Test.Wieldy field, you will get an error message from the compiler.

That said, you can still prove that the wield methods did actually change the value of the things you’re wielding:

fmt.Printf("Wield status: %s, %s", s.Wielded, c.Wielded)

The big take-away that I learned from this experiment is that while implicit interfaces are pretty damn awesome, you should not be using them so you can do a pile of random typecasting or to somehow treat your structs like the target for mixins (traits in Scala). They should be used to assert that a particular set of receiver methods exist for a particular data type. And since there are no classes and there is no inheritance, that data type is strictly enforced.

Further, I might have been better off just using embedding to contain a wieldable inside either my chair or sword objects, which would make them both wieldable. Also, interfaces cannot contain fields. So you might be tempted to try and model some statement like “anything wieldable should have a wielded boolean property”. You cannot model this with interfaces.

So I’m already starting to run into scenarios where it feels awkward or downright limiting to model things like business logic (or game logic) in Go. I will keep trying, however, to see if there’s a more Go-idiomatic way of doing things that I’m not seeing because I’m still knee-deep in the class-and-inheritance world.

Object-Oriented Design in Go

One of the first things I tend to look for in exploring a new language is OOD. What does a class look like? How does inheritance work? And, because I’m such a huge fan of Scala, I now ask questions like “Does it support mixins (traits)?”. The trick with Go is that there are no classes. That’s right, it’s a language that can be called object-oriented but you’ll never write a single class.

Let’s take a look at a little bit of sample code, where I’ve created a struct (remember those? Ah, the good old days…) called Mob and I’ve also created one called Coordinate:

type Coordinate struct {
	X	int
	Y	int
}

type Mob struct {
	Hitpoints	int
	Name		string
	AggroRadius	int
	Coordinate
}

Something worth noting here is that it might look like Mob inherits from Coordinate, but that’s not what’s happening. Instead, the Mob struct is embedding Coordinate struct. To really be object-oriented, I need to be able to write methods on my “objects”. Go supports this by allowing you to define functions that have something called an explicit receiver. In other words, when you invoke a method on a struct, that instance of that struct becomes the explicit receiver for that function.

Let’s create a method that moves our mob around a game board. In the process, you’ll see another one of Go’s differences from traditional C in that it can return multiple values. What happens if we invoke a method called MoveTo in a traditional OOP language and it fails? How do we know where the mob stopped en route to its original location? There are other classes we traditionally create like MoveResult or some junk like that, but that’s all ceremony slapped on top of the real problem. Here’s how to do it in Go:

func (mob *Mob) MoveTo(x, y int) (success bool, newLoc Coordinate) {
	success = true
	newLoc = Coordinate{x,y}

	mob.X = x
	mob.Coordinate.Y = y // can choose to be explicit about embed or not

	return success, newLoc
}

In the preceding code, the mob *Mob is declaring an explicit receiver of type Mob and it will be named mob (think of it as being able to provide a name for the traditional this in other OOP languages). X and Y are integer parameters to the method, and success and newLoc are the return values from the method.

Now let’s take a look at how to create a Mob and use it:

func main() {
	var brutus = Mob{
		Hitpoints: 500,
		Name: "Brutus",
		AggroRadius: 20,
		Coordinate: Coordinate{X: 100, Y: 200},
	}

	madeIt, newLoc := brutus.MoveTo(60, 50)
	fmt.Printf("Did I make it? %s\n", madeIt)
	fmt.Printf("Brutus is now at %d,%d\n", newLoc.X, newLoc.Y)

	// Can also shortcut through the embed:
	fmt.Printf("Brutus's X location - %d (or %d)\n", brutus.X, brutus.Coordinate.X)
}

I strongly encourage you, if you’re just learning Go, to copy this stuff in (remember each file needs a package) and run it with something like go run mob.go. Also remember that there’s absolutely no restriction on filename and it doesn’t need to correlate to the package it contains or the structs used. One subtle take-away from this is that you can add explicit receiver functions (methods) to any struct from anywhere in your code.

Here’s something subtle but important: Did you notice that it looked like I used a pointer in the MoveTo method? If you’ve got the code running, go ahead and delete the asterisk and run it again. Note that you don’t get any memory violations or null pointer exceptions or any of the usual crap you would expect from downgrading a pointer to a stack reference. BUT, what does happen is that the modification of the mob’s current location is ignored. Well, it’s not really ignored, but the modification is being made to a stack copy of the mob which is different than the mob reference sitting inside the main() function. To ensure that changes made inside the method actually happen to the shared instance of the mob between main() and the method, you need to use a pointer. This is because the method isn’t some vtable dispatched reflection-discovered shenanigan, it’s a legitimate C-style function that just happens to have been passed a value called mob. This is one of those dichotomies I mentioned in my previous blog post, about how it seems that Go is straddling the line between low-level, C-like functionality and modern awesomesauce like goroutines and asynchronous processing via communication over channels.

In my next post, I’ll show you some stuff about type inference and another cool feature: implicit interfaces.

First Impressions of the Go Language

I recently got a chance to hang out with some very brilliant people and one of the guys mentioned how fond he was of Go, a programming language most commonly associated with Google. To be honest, the fact that it was “yet another thing that came out of Google” is exactly why I hadn’t played with it up until this point. I’d seen a few blog posts but skimmed them. This time, however, I decided to give Go a more fair shake and so I downloaded it and started hacking away. What happened next shocked even me.

I’m not a coding newb, but even I know that there’s a learning curve to each language and recently the learning curves have been getting steeper – Scala and Clojure come to mind, as well as some of the UI frameworks that aren’t languages, but they have language-sized learning curves (AngularJS is the 800 pound gorilla of learning curves). That’s why when I had ‘Hello World’ compiled and running in about 12 minutes after my first click on golang.org, I was shocked.

If you are unfamiliar with Go, it takes a little getting used to because at first glance it seems like a hodgepodge of some features you would never expect to see in the same language. Here’s a quick list that I found over on this blog post entitled Why Go?:

  • Asynchronous – We’re all about reactive programming these days and all the hip kids are building non-blocking, asynchronous code. In fact, if I hear one more Node.js zealot shout “it’s non-blocking” one more time, I will stab him in the face with a web socket. Go has these things called Goroutines that are lightweight async execution blocks and they have channels that make my inner Erlang and Akka fanboy giggle. Bottom line is you write synchronous-looking code but it’s non-blocking and there are no callbacks. Callback hell needs to be avoided at all costs.
  • Concurrency – Paired with the asynchronous support features and support for multi-core with channels is very appealing, especially considering some of the other aspects of the language (check out the next bullet, you’re going to crap yourself)
  • Static Binaries – Oh that’s right. There’s no JVM. There’s no VM of any kind. You don’t have to wait for a runtime to go dig through classpath garbage and dynamically load a hojillion JAR files. These are compilednative binaries. Remember way back in the good old days when you could just pass around and executable and that worked?? Yeah, I had almost forgotten those times as well.
  • Language Features – In addition to looking like C, having asynchronous, actor-like support for concurrency and parallel programming, it also has a lot of the goodies that people think you can only get from some of the newer JVM or functional languages  like type inference and my personal favorite, implicitly satisfied interfaces … wait wait.. it gets better… the implicitly satisfied interfaces are checked and satisfied at compile-time… I almost shed a tear when I saw that.
  • Privacy indicated via case, not keywords – Capital lettered members are exported, lowercase ones are not.
  • Imperative, object-oriented language – You’d think this is contradictory, but with Go it just seems to work. I was very skeptical until I started playing with it. Go doesn’t have classes, yet it supports message passing via methods, polymorphism, and namespacing. Crazy, right?
  • Multiple return values – The language looks like C, but you can invoke methods that return multiple values and it looks just like a Scala unapply syntax. Me likey.

So, I sat down and I downloaded Go and got it working and followed the advice of setting up the $GOPATH environment variable that pointed to a single root under which all of my Go code would reside. It felt a little awkward, but there seemed to be some method to the madness, specifically relating to the fact that Go can fetch its dependencies directly from Github and that it can resolve transitive dependencies without the need for a make file, maven, or sbt. Holy crap – compiling to a native binary without maven or sbt? That’s cause for celebration.

So, let’s get to the hello world? (You can get the instructions to download Go and set up “Hello World” from here at golang.org.

package main

import "fmt"

func main() {
  fmt.Printf("Hello world.\n")
}

When you issue a go install command at the command line, this compiles your Go code. It doesn’t just create a JAR file or a DLL file that will be interpreted (JIT or otherwise) by a runtime like the .NET CLR or the Java Virtual Machine, it creates a static standalone self-executing binary. Ah but you say Java can create executable JARs too, right? This isn’t the same, this is a native executable whereas an executable JAR is just a regular JAR with the JVM launching bootstrapped in.

When I first sat down and started reading the docs on Go, I had mixed feelings and still do. On the one hand, it feels like a step back in that some of it looks like old school C (don’t get me wrong, I love me some old school C) whereas other parts are amazingly terse yet ridiculously powerful (channels, goroutines, slices, transitive no-makefile dependency resolution). I don’t know yet what my final thoughts are, but I know that right now it is appealing to my love of the C language (I think Go is one of the most C-pure looking syntaxes I’ve seen in a long time) with my love of Erlang, the actor pattern, and asynchronous back-end programming.

This is just hello world. If you’ve read this blog before then you know the real test I have to put Go through in order to vet it as a language and I’ll be posting a series of blog posts on that soon. The real question I ask of any new language is this: Can I create a MUD with this language?

I’m about to find out – stay tuned!

Building a MUD in Scala – Revisited

In my previous blog posts where I tried learning the Scala language through an interesting project, that of building a text-based multiplayer game (a MUD), I made lot of mistakes. Thankfully, that is the real purpose behind that kind of experimentation. We learn from our mistakes and we never really grow until we take risks and deliberately step outside our comfort zone.

Some time has passed and I’ve learned a little bit more of Scala so this time I’m going to take another stab at building a MUD in Scala. This time, however, I’m going about it in a slightly different way. Here’s a list of some of my new goals:

  • All of the code for the MUD will be written in Scala 2.9.1
  • Instead of using regular Scala Actors, I will be using Akka 1.3 Actors
  • Rather than manually executing Scala every time at the command line, I will be using Maven to build AND execute my MUD.
  • I will not tolerate ANY ugliness. Everything I consider done must be clean, concise, easy to read, and as Scala-ish as possible.
First, let’s take a look at the POM file I’m using in order to allow Maven to build, test, and execute my MUD:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.kotancode</groupId>
    <artifactId>scalamud</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>ScalaMUD</name>
    <url>http://kotancode.com/tag/mud</url>
    <repositories>
        <repository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </repository>
		<repository>
		  <id>akka.repository</id>
		  <name>Akka Maven Repository</name>
		  <url>http://akka.io/repository</url>
		</repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </pluginRepository>
    </pluginRepositories>
    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.9.1</version>
        </dependency>
		<dependency>
		  <groupId>se.scalablesolutions.akka</groupId>
		  <artifactId>akka-actor</artifactId>
		  <version>1.3</version>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sourceDir>src/main/scala</sourceDir>
                    <jvmArgs>
                        <jvmArg>-Xms64m</jvmArg>
                        <jvmArg>-Xmx1024m</jvmArg>
                    </jvmArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
If I were to drop a simple Scala hello world object in src/main/scala then running mvn clean install would compile that Scala object and I could then execute my Scala application with mvn scala:run -DmainClass=Hello (assuming I created an unpackaged Scala class named hello).
To start with, I created a root/bootstrapper object called Game:
package com.kotancode.scalamud

import akka.actor.{Actor, PoisonPill}
import Actor._

object Game extends App {
	val server = actorOf(new GameServer).start()
	server ! ServerStart
}
At first I thought I would just create a singleton actor GameServer, but because of the way you have to use the actorOf method to get an ActorRef instance for Akka Actors, you can’t just create self-starting singleton actors (well you can, but it looks like a hack). Note that because I didn’t declare server as private, that member variable is now visible to the rest of my application, giving all of my game objects access to the game server Actor.
The first task of the game server, once it receives the ServerStart message, is to fire up a telnet server and spin off a background thread that accepts inbound connections.
package com.kotancode.scalamud

import akka.actor.{Actor, PoisonPill,ActorRef}
import Actor._

import java.net._
import java.io._

import com.kotancode.scalamud.core.Player
import com.kotancode.scalamud.core.NewSocket
import com.kotancode.scalamud.core.TextMessage

case object ServerStart
case class PlayerLoggedIn(player:Player)

class GameServer extends Actor {
	private var allPlayers = List[Player]()

	def receive = {
		case ServerStart => {
			startSocketListener
		}
		case PlayerLoggedIn(player) => {
			handlePlayerLogin(player)
		}
	}

	private def handlePlayerLogin(player:Player) = {
		println("Player logged in: " + player)
		allPlayers ::= player
		allPlayers.foreach( p=> {
			if (p.name != player.name) {
				p.self ! TextMessage(player.name + " logged in.")
			}
		})
	}

	private def startSocketListener = {
		spawn {
			val serverSocket = new ServerSocket(8888)

	  		while(true) {
	   				println("Awaiting connection...")
   					val clientSocket = serverSocket.accept()
	   				val player = actorOf(new Player()).start()
	   				player ! NewSocket(clientSocket)
	   				println("Spun off echo handler for player")
	  			}
		}
	 }
}

At this point, I’m now using Akka actors (whose receive method syntax I like much better than standard Scala actors) and a Maven build with automatic dependency management to build and launch my MUD. With just a few minor changes from my previous Scala MUD, I’m in a much better position to grow this into a real application.

Also note the use of the spawn class here. This executes whatever code is inside the code block as an asynchronous background thread, much like the standard Scala actor actor { } syntax. So, for Akka we use spawn { } and for standard Scala Actors we use actor { }.

Another thing worth noting is the use of the .self member before sending a message to an Akka actor. Unlike regular Scala actors, you can’t use !, ?, !!, etc to send messages directly to instances of objects that derive from akka.Actor. Instead, you need an ActorRef instance, which you get from the actor’s self member. In this way, there’s a much clearer distinction between the class’ message-handling behavior (accessed from it’s ActorRef) and it’s regular java-like behavior accessed from standard class members.

In my next blog post, I will get some more features implemented in the MUD. Eventually, if I like the way things turn out I’ll start pushing my code to a Git repo so that you can read/download it there instead of just copy/pasting it from this blog.

Building a MUD in Scala, Part 5: Refactoring and Idiomatic Scala

So far, so good. My quest to learn Scala by virtue of attempting to build a MUD in that language is going pretty well. At this point, I can telnet to the game server, I can log in (albeit without validation or persistence), and in my last post I added the ability for players to be granted commands like ‘who’, ‘cmdsoul’ (to see the command souls assigned to them), ‘broadcast’, etc.

When we learn new programming languages, we always look at the new language through the filter of our past experiences. This isn’t a sign of a bad programmer – this is merely human nature. It’s how we learn and how our brains filter everything we see, do, and hear. As a result, if we approach a new language like Scala from the point of view of someone who has been doing hard-core OOP for the past several years and only tinkering with functional programming – we tend to rely on certain crutches or conventions.

For example, I have an Actor (a Player, to be exact) and that Actor has multiple mix-in traits. One of these traits manages the list of commands currently available for the player. I am exposing the list of commands as a public field so that the Wizard Command Soul can tell wizards which command souls are attached (this ability is supremely helpful for debugging chained command parsing.. trust me..):

var commandSouls: Map[String, CommandSoul] = Map.empty[String, CommandSoul]

And in the Wizard Command Soul, I do a couple of really hideous things in order to display this list of command souls to the wizard:

val cmdIssuer = soulOwner.asInstanceOf[CommandIssuer]
...
cmdIssuer.commandSouls.foreach( ... )

The first problem with this code is that I’m doing a very classic OOP-style typecast. I’m coercing the soul’s owner (the Actor to which the command soul has been attached) to the trait type CommandIssuer. This means that my Wizard Command Soul now has to have explicit knowledge of how I built my application. In short, it needs to know that the CommandIssuer trait is the one that carries a public field named commandSouls.

Allowing other objects unfettered access to a ‘var’ (mutable) field in Scala just seems wrong. It’s certainly not thread-safe and it feels just wrong to me. This blog is about the pursuit of elegant simplicity and this seems neither elegant nor simple.

I could pull out another classic OOP principle: encapsulation, and wrap that var in a function that returns an immutable map:

	def getCommandSouls = {
		val cmdTemp = commandSouls.toMap
		cmdTemp
	}

When you call toMap and assign that value to a val , it automatically gives you an immutable map. This takes care of some of our thread-safety issues and also prevents other people from tampering with the internal list of commands. But, it’s still just a method wrapper and I still don’t like it because I still have to coerce the actor into the CommandIssuer trait/mixin type. If I decide to move the storage of command maps to a different trait during some future refactor, this code will break.

My next thought, then was to send a message to the soul owner (the player) and I would then expect a message back containing the information I need. This is far more Scala-looking than anything I’ve done so far:

	def handleCommandSoul(verb: String, extParams: List[String]) : Boolean = {
		//val cmdIssuer = soulOwner.asInstanceOf[CommandIssuer]
		var string = "\nCurrently Attached Command Souls:\n"
		soulOwner ! QueryCommandSouls
		self.receiveWithin(500) {
			case rep: CommandSoulReply => {
				rep.souls.foreach( mapitem => string += mapitem._1 + " - " + mapitem._2.describe()._2 + "\n")
				soulOwner ! TextMessage(string)
			}
			case TIMEOUT => {
				soulOwner ! TextMessage("Woah, your command issuer is roasted")
			}
			case somethingElse =>
			{
				println(somethingElse)
				soulOwner ! TextMessage("received a bizarro message!")
			}
		}
		true
	}

I’ve got a couple extra guards in there because I’ve never done this before and have no idea what to expect. What I assume is going to happen here is that the looping react pattern matcher I have in the player will eventually get to the partial function in CommandIssuer and handle the request to query the list of command souls. At that point, it will reply to the sender with the information I’m looking for, using this code:

	case QueryCommandSouls => {
		println(sender + " just asked me for the list of command souls!")
                val souls = commandSouls.toMap // Create an immutable copy!! encapsulation FTW
		sender ! CommandSoulReply(souls)
		}

When I compile and run the MUD this time and I type cmdsoul into my telnet client,  I get something entirely unexpected. The message that my receiveWithin(500) pattern match received was QueryCommandSouls! As it turns out, the wizard command soul is attached to the same player (Actor) that has the CommandIssuer trait. So, basically I’m sending myself the QueryCommandSouls message and immediately after that, I start a receive block. In short, I’m catching my own message before the rest of my reactors can see it.

Remember that Actors in Scala are really nothing more than objects backed by a queue (message box) and every message you send to an Actor is really just dumped into the queue and then pulled out of that queue synchronously or asynchronously using pattern matching syntax. So, when I called receive after sending myself the QueryCommandSouls message, I just received the message I sent a nanosecond ago. I need to refactor this some more to make this more asynchronous to allow the player’s reactors to handle things in the right order.

Here’s my new handleCommandSoul function:

def handleCommandSoul(verb: String, extParams: List[String]) : Boolean = {
		soulOwner ! QueryCommandSouls(this)
	}

Note that I had to change the query message into a case class instead of a case object. This is because if I send the message without any parameters, the sender object on the other end will be the player and not my command soul. To get the reply to come back exactly where I want it, I have to pass the object with the message (unless I actually want the player to handle the reply). This is looking much better – it looks much more idiomatic than my previous attempts.

Now I need to handle the reply in a react loop in my act method in the command soul:

def act() : Unit = {
	loop {
		react {
			case rep:CommandSoulReply => {
				var string = "\nCurrently Attached Command Souls:\n"
				rep.souls.foreach( mapitem => string += mapitem._1 + " - " + mapitem._2.describe()._2 + "\n")
				soulOwner ! TextMessage(string)
			}
		}
	}
}

At this point I can compile and run my MUD again and the cmdsoul command works just as it did before (at least from the player’s point of view) but the internal plumbing has been changed so that it now operates in a thread-safe, asynchronous fashion that looks far more like it belongs in Scala than it does in Java.

The whole point of this blog post is, first and foremost, strive for simplicity. My code looked convoluted, complex, and difficult to read. In addition, I knew it wasn’t thread-safe and violated encapsulation rules. I refactored a couple times and still wasn’t happy. With my final solution of asynchronous messaging between two traits attached to a single parent Actor, I am actually pleased with the result.

Building a MUD in Scala, Part 4: Command Processing

In many traditional MUDs, the list of things a player or an administrator can do is fixed at compile-time. In a standard Zork-style adventure you might be able to do the typical things like enter ‘north’, ‘south’, ‘get’, ‘attack’, ‘kill’, ‘drop’, ‘quit’, etc. In a MUD you get some additional commands that might be relevant in a multi-player environment like ‘who’ or ‘say’ or ‘tell’ and even some fancy muds let you emote with commands like ‘bow’, ‘praise’, ‘introduce’, ‘wave’, etc.

While I’m perfectly OK with that list of commands, I’ve never liked how the player is given those commands. In almost all MUDs that I’ve encountered, the game engine knows about the fixed list of available commands and the execution of said commands takes place somewhere at the low engine level. This totally violates my feelings toward the single responsibility principle (SRP), encapsulation, and domain-bleeding.

The following sample scenarios should make it clear why I hate the idea of the engine having built-in commands:

Scenario 1: A player is in a MUD and they enter a disco. While inside this disco, the player can type ‘disco’ to get their 70s funk on. The ‘disco’ command is only available to the player while they are in this one room out of the thousands of rooms that make up the MUD. Do we really want to go modify the command parser at the engine level in order to grant the player the ‘disco’ command in a single room? What happens if that room gets deleted … now we have orphaned, scar tissue code sitting in our engine that serves no purpose. This might not seem like a big deal for a game, but it illustrates a very good point about designing large applications with large domain models.

Scenario 2: A player in that same MUD stumbles across a sword. The sword has an inscription on it and when the player types the words from that inscription into the console, the sword bursts into flames and does an extra bajillion points of damage. In this case, the command is even more situational than the disco room. Only when the player is wielding this sword are they granted the ability to type the secret word ‘clambake’ into the console that will activate the sword’s secret powers.

So, what I’m envisioning here is I want to be able to send the Player actor a message whenever I grant them the ability to type a command and likewise, send them another message when they no longer have the ability to type that command. Consider the following functions that we might find in the Holy Clambake Sword:


def onWielded(player: Player) : Unit = {
    player ! AddCommand(List("clambake"), handleClambake)
}

def handleClambake(verb: String, extParams: List[String]): Boolean = {
    player ! TextMessage("You have activated the mighty abilities of the Holy Clambake Sword!")
    player ! Emote("has activated the mighty abilities of the Holy Clambake Sword!")
    isFlaming = true
    true
}

To be able to send Player’s the AddCommand message, I’m going to create a trait called CommandIssuer. This trait can be mixed into any Actor that is capable of issuing commands to the system. This includes NPCs and other interactive entities within the game. For now, since I haven’t coded NPCs, we can just start with players. Here’s the code for the CommandIssuer trait:

package com.kotancode.mud.engine

import scala.actors._
import scala.actors.Actor._

sealed abstract class CommandRequest
case class AddCommand(verbs: List[String], executor: Function2[String, List[String], Boolean],
	cmdSoul: CommandSoul = null) extends CommandRequest
case class RemoveCommand(verbs: List[String], cmdSoul: CommandSoul = null) extends CommandRequest
case class ExecuteCommand(verb: String, extParams: List[String]) extends CommandRequest

trait CommandIssuer extends Actor
{	                             // CMD verbs , Func to call
	private var commandMap: Map[List[String], Function2[String, List[String], Boolean]] =
		Map.empty[List[String], Function2[String, List[String], Boolean]]

	var commandSouls: Map[String, CommandSoul] = Map.empty[String, CommandSoul]

	protected val handleCommandMapping : PartialFunction[Any, Unit] = {
		case req: AddCommand => {
			commandMap += req.verbs -> req.executor
			if (req.cmdSoul != null) {
				commandSouls += req.cmdSoul.describe()._1 -> req.cmdSoul
			}
		}
		case req: RemoveCommand => {
			commandMap -= req.verbs
			if (req.cmdSoul != null)
				cmdSouls -= req.cmdSoul.describe()._1
		}
		case exec: ExecuteCommand => {
			val toExecute = commandMap.filter(m => m._1.contains(exec.verb))
			if (toExecute.size == 0) {
				self ! TextMessage("What?\n")
			}
			else {
				toExecute.foreach( m => m._2(exec.verb, exec.extParams))
			}
		}
	}
}

If we add the CommandIssuer trait to our Player class (or any other class we want to be able to issue commands, either from a terminal or at the behest of other Actors) then we can send Players the AddCommand, RemoveCommand, and ExecuteCommand messages. The code that reads in lines of text from the player’s attached socket can now invoke ExecuteCommand after splitting the input line into a head and tail (how LISPy is that??):

val tokens = line.split(' ').toList
this ! ExecuteCommand(tokens.head, tokens.tail)

Finally, I want to mention Command Souls. Command souls are logically bundled groups of command handlers that are also bundled with the code that attaches and removes the commands from targets. This provides a neat and tidy way of packaging logically related commands like the stock commands that belong to all mortals (who, quit, say, get, look, etc), stock commands that belong to wizards (broadcast, cmdsoul to inspect commands, destroy, teleport, etc). Command souls are part of what I consider a MUD’s library code, logically and physically separated from the MUD’s engine code. This concept neither original nor mine – I first encountered it when I was an Archwizard of Code on the LPmud Genesis.

Take a look at the code for the Wizard command soul, a classic example of what Scala should look like when done in clean, tidy, small modules:

/*
 * Wizard Command Soul
 * Commands granted to all wizards
 */
package com.kotancode.mud.lib.wizard

import com.kotancode.mud.engine._
import scala.actors._
import scala.actors.Actor._

class WizardCommandSoul extends CommandSoul
{
	private var soulOwner : Actor = null

	def attachTo(target:Actor) : Unit = {
		soulOwner = target
		target ! AddCommand( List("cmdsoul"), handleCommandSoul, this )
		target ! AddCommand( List("broadcast", "bcast"), handleBroadcast, this)
	}

	def detachFrom(target:Actor) : Unit = {
		soulOwner = null
		target ! RemoveCommand( List("cmdsoul"), this)
		target ! RemoveCommand( List("broadcast", "bcast"), this)
	}

	def describe() : (String, String) = {
		("Wizard", "Standard commands available to all Wizards")
	}

	def handleCommandSoul(verb: String, extParams: List[String]) : Boolean = {
		val cmdIssuer = soulOwner.asInstanceOf[CommandIssuer]
		var string = "\nCurrently Attached Command Souls:\n"
		cmdIssuer.commandSouls.foreach( mapitem => string += mapitem._1 + " - " + mapitem._2.describe()._2 + "\n")
		soulOwner ! TextMessage(string)
		true
	}

	def handleBroadcast(verb:String, extParams: List[String]) : Boolean = {
		var text = "[Broadcast from " + soulOwner.asInstanceOf[Player].name + "]: "
		text += extParams.reduceLeft(_ + " " + _)
		PlayerRegistry.allPlayers.foreach(p => p ! TextMessage(text))
		true
	}
}

And finally, to prove that I’m not just blowing hot air, here’s a screenshot of a session I had while logged into the MUD. My prototype MUD auto-grants every user both Mortal and Wizard command souls and doesn’t care what you type for a name. In the future, it will have to ask for a username and a password, look that person up from storage, and load their profile, yadda yadda … For now, this is what I’ve got:

Sample MUD Session, Illustrating Command Processing

Sample MUD Session, Illustrating Command Processing

Overall I’m still fairly pleased with Scala. A few times I’ve been slapped in the face by the strong-typing because I’m not used to that when everything else feels so functional and lightweight – side-effects of Scala’s Frankenstein/hybrid nature. Still, even with a few syntactic bits of ugliness, I continue to keep forging ahead with this to get a real feel for what it’s like to work with Scala to solve practical problems.

Building a MUD in Scala, Step 3: Refactoring and Pub/Sub

As I mentioned in the previous blog post, I left some ugliness lying around in the code last time. The biggest problem in the last version of the code was that every time a player logged in, the Player actor iterated through the connected player list, accessed a variable specific to networking (the socket writer), and then sent text directly to that player. Not only did that violate encapsulation, but it violated the laws of good taste. It wasn’t elegant, simple, or clean enough for me. I had to fix this and I had to fix it now!

First, before I did the coupling fix, I extracted my code into multiple files. I now have an engine directory which contains the Player.scala and GameServer.scala files. I put them both in the com.kotancode.mud.engine package. This made me feel a little better – at least I was getting some proper organization out of this and I was no longer cramming everything into a single file.

Next, to address the encapsulation problem. After thinking about the problem for a little while I realized that the issue was one of pub/sub (publish/subscribe). I wanted the Player actors to simply publish the fact that they have logged in and then any interested party could then respond to that. Great, I’ll make the PlayerRegistry subscribe to a player login event and then publish that same event. The reason why I can’t have players subscribing to that event on other player objects is that players don’t know about other players (at least until after they’ve logged in) – it’s a chicken and the egg problem that only the singleton PlayerRegistry object can fix.

To give my Actors the ability to publish and subscribe, I used a Trait as a mixin called ActorPublisher (which you can find at this great blog post here by Jim McBeath). So now my engine directory has the following class files:

  • Player.scala
  • ActorPublisher.scala
  • GameServer.scala

GameServer has now become ridiculously small and the only change I’ve made is that instead of calling the message sent to the Player actor echo, I now call it StartTextProcessing. I love the fact that the act of reading commands from the player over a socket in a multi-threaded fashion is just taken care of me by the very nature of actors in Scala.

Let’s take a look at Player.scala, which now contains a revised Player actor that publishes notification of logins and subscribes to notifications of other players logging in from the PlayerRegistry object, which is acting as a multiplexer for this type of notification.

/*
 * com.kotancode.mud.engine
 *
 * Player class and related goodies
 */
package com.kotancode.mud.engine

import java.net._
import java.io._

import scala.actors._
import scala.actors.Actor._

case class StartTextProcessing(socket: Socket)

class Player extends Actor with Subscriber[PlayerMessage] with ActorPublisher[PlayerMessage] {
 var name = "";
 var inReader: BufferedReader = null
 var outWriter: PrintWriter = null

 implicit def inputStreamWrapper(in: InputStream) =
  new BufferedReader(new InputStreamReader(in))

 implicit def outputStreamWrapper(out: OutputStream) =
  new PrintWriter(new OutputStreamWriter(out))

 def processText(in: BufferedReader, out: PrintWriter) {
   inReader = in
   outWriter = out
   PlayerRegistry ! Subscribe(this.asInstanceOf[Subscriber[PlayerMessage]])
   out.println("\nWho be ye?")
   out.flush()
   name = in.readLine();
   out.println("\nWelcome to the KotanMUD, " + name)
   publish(PlayerLoggedInMessage(this.asInstanceOf[Player]))
   out.println("Other people currently playing:")

   PlayerRegistry.allPlayers.foreach( p => out.println(p.name) )
   out.flush()
   while (true) {
       val line = in.readLine()
       out.println(name + ": " + line)
       out.flush()
  }
 }

private val handleOther : PartialFunction[Any,Unit] = {
	case StartTextProcessing(socket) => actor { processText(socket.getInputStream(), socket.getOutputStream()) }
	case PlayerLoggedInMessage(player) => {
		if (this != player) {
			outWriter.println(player.name + " logged in.")
			outWriter.flush()
		}
	}
}

def act() {
	loop {
		react (handleSubscribe orElse handleOther)
	}
}
}

sealed abstract class PlayerMessage
case class PlayerLoggedInMessage(source:Player) extends PlayerMessage

object PlayerRegistry extends Actor with Subscriber[PlayerMessage] with ActorPublisher[PlayerMessage]
{
	start
	var allPlayers = List[Player]()
	def getPlayer() : Player = {
		val newPlayer = new Player()
		allPlayers ::= newPlayer
		newPlayer ! Subscribe(this.asInstanceOf[Subscriber[PlayerMessage]])
		newPlayer
	}

	private val handleMessage : PartialFunction[Any, Unit] = {
		case m:PlayerLoggedInMessage => {
			println(m.source.name + " logged in.") // output to console
   			publish(PlayerLoggedInMessage(m.source)) // republish the message
			}
	}

	def act() {
		loop {
			react (handleSubscribe orElse handleMessage)
		}
	}
}

So now I will compile my new MUD with the following command (as I add files it adds a bit more complexity to my ability to rapidly run my MUD… at some point I’m going to have to upgrade to a build tool to automate this… but that’s a topic for another post):

scalac engine/ActorPublisher.scala engine/Player.scala engine/GameServer.scala

And then I run my MUD with:

scala com.kotancode.mud.engine.GameServer

I can now verify that I am able to handle incoming connections the same way I used to, the multi-threading and thread-local storage is all working properly and most importantly, I am now able to let other players know that a player has logged in using a more elegant publish/subscribe approach.

Building a MUD in Scala Part 2 – Shared State

In the previous post, I explained a little bit about my reasoning behind experimenting with a MUD as a way of learning a new language. As a result, I’ve been poking around a little with Scala. Whenever you’re learning a new language it helps to have a goal in mind rather than building a bunch of disparate “hello world” samples. My goal is a MUD.

Last time I build a telnet server that prompts the user for their name and then acts as an echo server thereafter. In this post, I’m going to experiment with how I can add some global state. I want to be able to keep track of who is currently logged into the MUD. In addition, I want to be able to send messages to all connected players and let them know that another player has connected.

To do this, I’m going to modify my original Scala script from the previous post to make it look like the following:

/*
 * Pathetically simple Scala echo server
 * Step 2 on the road to making a MUD - maintaining player list
 */
import java.net._
import java.io._

import scala.actors._
import scala.actors.Actor._

case class Echo(socket: Socket)

class Player extends Actor {
 var name = "";
 var inReader: BufferedReader = null
 var outWriter: PrintWriter = null

 implicit def inputStreamWrapper(in: InputStream) =
  new BufferedReader(new InputStreamReader(in))

 implicit def outputStreamWrapper(out: OutputStream) =
  new PrintWriter(new OutputStreamWriter(out))

 def echo(in: BufferedReader, out: PrintWriter) {
   inReader = in
   outWriter = out
   out.println("Who be ye?")
   out.flush()
   name = in.readLine();
   out.println("Welcome to the Echo Server, " + name)
   out.println("Other people currently playing:")
   PlayerRegistry.allPlayers.foreach( p=>
	{
		out.println(p.name)
		if (p.name != name)
			p.outWriter.println(name + " just logged in.")
		p.outWriter.flush()
	})
   out.flush()
   while (true) {
       val line = in.readLine()
       out.println(name + ": " + line)
       out.flush()
  }
 }

 def act() {
  loop {
   receive {
    case Echo(socket) =>
     actor {
      echo(socket.getInputStream(), socket.getOutputStream())
     }
   }
  }
 }

}

object PlayerRegistry
{
	var allPlayers = List[Player]()
	def getPlayer() : Player = {
		val newPlayer = new Player()
		allPlayers ::= newPlayer
		newPlayer
	}
}
// Singleton object for the echo server.
object EchoServer {
 val serverSocket = new ServerSocket(8888)

 def start() {
  while(true) {
   println("Awaiting connection...")
   val clientSocket = serverSocket.accept()
//   val player = new Player()
   val player = PlayerRegistry.getPlayer()
   player.start
   player ! Echo(clientSocket)
   println("Spun off echo handler for player")
  }
 }
}

EchoServer.start

The new code here is the PlayerRegistry object. Object’s in Scala are a first-class implementation of the singleton pattern. Simply by declaring something an ‘object’ rather than a ‘class’ Scala automatically takes care of the plumbing involved in setting that up as a singleton. The PlayerRegistry singleton contains a method called getPlayer, which is responsible for instantiating a new player as well as adding that new player object to a list. Note that as we change properties on the player object, that will be reflected in the global player list because we’re making changes to the same object (aren’t pointers awesome?).

The logic behind what I’ve done is pretty simple. The PlayerRegistry singleton object keeps track of all players currently in the game. When someone logs in, I iterate through the list of players. If the player object in the current iteration is not the player doing the logging in, I send the “(player) logged in.” message.

Veteran programmers and programmers with some measure of good taste will realize that I’m violating some patterns here. When a player logs in, I shouldn’t be looping through the player list and manually doing the notifications. What I should be doing is sending messages and letting the player object handle the message accordingly. I’ll take care of refactoring this in the next blog post. For now, take a look at this screenshot from a terminal session logged into my ‘game’ server:

Using My Scala MUD

Using My Scala MUD

Building a MUD in Scala, Step 1: The Echo Server

If you’re reading this then you’re probably familiar with the fundamental, driving force behind this blog: elegant simplicity. This concept is what I strive for in my code, in my architectures, and generally in my life. Lately I’ve been doing a little experimenting with Scala and the more I play with it, the more I see potential for elegant simplicity in that language that is just not achievable with standard Java. My goal is to find out if Scala can really meet my need for 枯淡 (kotan).

You might be thinking: MUD? WTF? Didn’t those go extinct with the dinosaurs?? No. People are often surprised by this but, MUDs (Multi-User Dungeon/Dimension – old-school online text adventure games) require a lot of their developers. MUDs require developers to think about a lot of things that they don’t normally have to worry about with simple “Hello World” samples, such as:

  • Concurrency – performing multiple tasks on multiple threads in a way that doesn’t destroy data
  • Concurrency and Load – supporting multiple connected users to the same central process without slowing the process down.
  • Multi-threading – MUDs make extensive use of thread-local data, especially those MUDs whose text is exposed via Telnet.
  • Push Notifications – Good MUDs sent blurbs of text letting players know when other players enter and exit rooms, when someone draws a weapon, when another player does a dance. Developers can learn all kinds of useful techniques when they try and create domain models and networking code that supports this kind of behavior.
  • OOD and DDD – Designing the class hierarchy for a MUD is actually a great mental exercise and I highly recommend that every developer do it every time they feel that their experience has grown or changed.
  • Near-Real-Time Data – some of the better MUDs I used to work on “back in the day” had weather systems that would make thunder crackle (text-based thunder, but still…) at different times and the “noise” would radiate out, notifying only those players that are within earshot of the storm. This kind of design has applications in real-world business scenarios as well.
  • Testability – Writing code for a MUD should require a developer to write tests for their code since they can’t count on the fact that players will be able to walk around their areas, trodding on all that can be trod and poking all that can be poked, etc. This is also a very real-world scenario : we can’t expect our end users to find all the edge cases.
  • API Design – MUD developers typically build a game engine and then a core library. The core library is essentially an API that allows “wizards” (players who have gotten powerful enough to decide to add to the game) to build their own content. The API created by the original MUD developers needs to be simple enough that even the most junior of developers can utilize it to create fun areas. In real-world business scenarios, knowing how to create and test high-quality APIs is an essential skill for architects and senior developers.

Still think MUDs are worthless toy relics left over from the 80s and 90s? Hopefully not. One of my litmus tests for good, expressive, elegant languages is their ability to allow me to create a MUD that adheres to my “code as data” policy. Rather than reading rigid crap from weapons.xml, weapons should be first-class language objects and the use of the game library is what creates instances of swords, daggers, or laser cannons.

To get myself started, I wanted to see how hard it would be to write the networking server. This is a smoke test. If any part of this is difficult or I feel like I’m spending all my time writing ceremony (like I would if I was writing a telnet server in POSIX C) then I will stop right away.

The requirements for my networking server are as follows:

  • Accept connections from a seemingly (limited by infrastructure and memory) unlimited number of clients
  • Each connection should have connection-private data, such as the player’s name. This proves that I can maintain private player state even while multiple players are connected
  • Everything the player types, after supplying their name, will be echo’d back to them. This proves that I can respond to commands with text that only the command issuer can see.
  • I fully intend to throw away much or all of this code in future refactors, as such – I don’t want to write a lot of code.

Thankfully, I was able to write some Scala that achieved all of these goals. Here is my simple echo server that also supports the prompting for and thread-local storing of player names (some of this is cobbled together from various echo server implementations I found via Google):

/*
 * Pathetically simple Scala echo server
 * Step 1 on the road to making a MUD
 */
import java.net._
import java.io._

import scala.actors._
import scala.actors.Actor._

case class Echo(socket: Socket)

class Player extends Actor {
 var name = "";

 implicit def inputStreamWrapper(in: InputStream) =
  new BufferedReader(new InputStreamReader(in))

 implicit def outputStreamWrapper(out: OutputStream) =
  new PrintWriter(new OutputStreamWriter(out))

 def echo(in: BufferedReader, out: PrintWriter) {
   out.println("Who be ye?")
   out.flush()
   name = in.readLine();
   out.println("Welcome to the Echo Server, " + name)
   out.flush()
   while (true) {
       val line = in.readLine()
       out.println(name + ": " + line)
       out.flush()
  }
 }

 def act() {
  loop {
   receive {
    case Echo(socket) =>
     actor {
      echo(socket.getInputStream(), socket.getOutputStream())
     }
   }
  }
 }

}

// Singleton object for the echo server.
object EchoServer {
 val serverSocket = new ServerSocket(8888)

 def start() {
  while(true) {
   println("Awaiting connection...")
   val clientSocket = serverSocket.accept()
   val player = new Player()
   player.start
   player ! Echo(clientSocket)
   println("Spun off echo handler for player")
  }
 }
}

EchoServer.start

When I run this application by just typing scala EchoServer.scala, it starts up a listener on port 8888. Then I telnet to localhost, port 8888. I am prompted with the text, “Who Be Ye?” to which I reply with my name. From there after, everything is echoed back to me, prefixed by the name I entered at the start of my session. I can fire up as many terminal windows as I like and log in with as many different names as I like. All of these connections have separate instances of the Player actor and that instance has a variable called name. This meets all of my requirements. It didn’t take me that much code, it looks clean, I’m not so attached to this code that I can’t throw it away, and I can support a (virtually) unlimited number of connections and each of those connections gets their own echo server loop.

Looks like I’m well on my way. The next thing I’ll want to do is add some kind of rudimentary command processing so that I can move beyond a simple Echo Server. At this point, I’m pretty pleased with the elegant simplicity of Scala and I think it’ll really start looking amazing once I start writing in-game objects like weapons, rooms, items, and building combat systems – where I get to (hopefully) start making extensive use of Traits and Actors, two of the most appealing aspects of Scala to me.