I started writing a discrete event simulator tonight with a friend of mine. It's going to simulate random D&D encounters. We've both used Python before, but not that much; since we wanted to learn it more, we decided to implement the simulator using Python.
And damn, it's awesome! It can do some really interesting stuff. Having mostly used C, C++, and Java in the past, Python has been a liberating experience!
Here's an example of its coolness. One of the objects in the simulator is a BattleGrid, which is a simple rectangular grid made up of Square objects, which contain info about the squares. When creating a BattleGrid class, I initialize it with default squares. Here's how the code would look in Java:
CODE
this.grid = new Square[this.height()][this.width()];
for (int row = 0; row < this.height(); row++) {
for (int col = 0; col < this.width(); col++) {
this.grid[row][col] = new Square();
}
}
for (int row = 0; row < this.height(); row++) {
for (int col = 0; col < this.width(); col++) {
this.grid[row][col] = new Square();
}
}
But in Python, it's only a single line of code!
CODE
self.grid = [[Square() for w in xrange(self.width)] for h in xrange(self.height)]
At one point, I also print out a textual representation of the grid. In Java, the code would be kind of annoying to write:
CODE
StringBuilder buf = new StringBuilder("Battle Grid " + this.width() + "x" + this.height() + "\n");
for (int row = 0; row < this.height(); row++) {
buf.append("|");
for (int col = 0; col < this.width(); col++) {
buf.append(this.grid[row][col].moveCost());
}
buf.append("|\n");
}
String str = new String(buf);
str = str.substring(0, str.length()-1); // Trim off the trailing newline character
return str;
for (int row = 0; row < this.height(); row++) {
buf.append("|");
for (int col = 0; col < this.width(); col++) {
buf.append(this.grid[row][col].moveCost());
}
buf.append("|\n");
}
String str = new String(buf);
str = str.substring(0, str.length()-1); // Trim off the trailing newline character
return str;
But in Python, it's way easier!
CODE
desc = ["Battle Grid (%dx%d)" % self.size]
for row in self.rows:
costs = [str(col.move_cost) for col in row]
costs = " ".join(costs)
dstr = "|%s|" % costs
desc.append(dstr)
return "\n".join(desc)
for row in self.rows:
costs = [str(col.move_cost) for col in row]
costs = " ".join(costs)
dstr = "|%s|" % costs
desc.append(dstr)
return "\n".join(desc)
I think I'm in love.
