Log In · Register

 
 
Reply to this topicStart new topic
I'm in love, with Python!
mipadi
post Jul 27 2008, 02:17 AM
Post #1


Senior Member
******

Group: Administrator
Posts: 2,648
Joined: Apr 2008
Member No: 639,265





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();
    }
}


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;


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)


I think I'm in love. wub.gif
 
heyo-captain-jac...
post Jul 27 2008, 04:08 AM
Post #2


/人◕‿‿◕人\
*******

Group: Official Member
Posts: 8,283
Joined: Dec 2007
Member No: 602,927



I know for a fact you're in love. And I don't blame you. Python is the best.
 
mipadi
post Aug 1 2008, 02:31 PM
Post #3


Senior Member
******

Group: Administrator
Posts: 2,648
Joined: Apr 2008
Member No: 639,265



I discovered a bunch of other cool stuff, but I still can't get modules to dynamically load functions. Grr...
 
KryMeARiver
post Aug 1 2008, 05:43 PM
Post #4


Banned
*****

Group: Banned
Posts: 700
Joined: Jun 2008
Member No: 658,432



I still haven't made good on my goal to learn Ruby...
 

Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members: