Keeping it Small and Simple

2007.06.22

..Can I sleep now?

Filed under: Uncategorized — Lorenzo E. Danielsson @ 07:05

The last two weeks have been too hectic. I’ve been programming pretty much around the clock. But finally I was able to hg commit. Now I’m going to take a day or two to rest before I get back to my normal routines. I definitely need to spend some time with my kids. They’ve been complaining of late they hardly ever see me. Maybe I should take them to Accra Zoo. Last time they were there they had stories to tell me for about three weeks.

It’s odd, how can programming be so much fun when you work on your own stuff, and so boring when you are developing for a client? I guess because clients only need boring applications. I never had a customer come up and tell me “yeah, you know, in order to increase our productivity we’d really need an RPG developed. We’d like the world to be loosely based on Tolkien’s Middle Earth. Or, think Bard’s Tale. Think Dungeon Master. Think your very own world with its own rules..” No, instead I get stuck working on “business applications”. Bah, humbug!

Well, now I can hopefully get back to writing my pygame tutorial. Expect something in a few days time (after I’ve slept away those funny things hanging down under my eyes that make me look like I’m 75).

Advertisements

2007.06.12

Battle for Wesnoth: The Valley of Death

Filed under: Battle for Wesnoth, Computer Games — Lorenzo E. Danielsson @ 02:19

It took me a long time to be able to survive The Valley of Death in the Heir to the Throne campaign (I am talking about Battle for Wesnoth in case you didn’t read the title). Because of that I’ve always had a lot of respect for this particular episode and consequently anytime I get to The Valley of Death I just send all my units south, defeat the lich and stay put until the rounds are up. Occasionally I send a few units to gain some extra experience by knocking off a few walking corpses coming from the east.

The other day I decided to try to defeat all three liches. It turns out to be quite simple. This is what I did.

I sent my three white mages up north. They are efficient against the annoying wraths. With them I sent Delfador to act as a backup in case my mages run into trouble. After a few battles with wraths, one of the mages becomes a Mage of Light. I get my second Mage of Light by defeating the northern lich.

To the east I sent my three horsemen and Kalenz. One of my horsemen was a Grand Knight, the other two level two knights. These two quickly become level three characters as they get attacked a lot. The three horsemen take care of all the walking corpses easily. Although there are many of them they do little damage and the horsemen are strong. When I horseman needs to heal he runs to a village and Kalenz temporarily steps in. Kalenz is of course mostly useful, but can buy some time while a knight heals.

In order to separate the walking corpses I spread the horsemen out so that one attacks from the North, one from the West and one from the South. Kalenz stays behind to the West, but ready to move where he needs to. When I’m ready to kill the lich I entice him to attack my Grand Knight who has full hit points. Then the other two horsemen ride in and destroy him.

To the South I sent my three red mages. One quickly becomes an Arch Mage and one other gets is just 4 points from promotion at the end of the scenario. Because the units can take quite a bit of damage from the enemy units in the South, I also had brought two elvish shamans along. In addition, I recruited one scout to cause distractions and prevent all enemy units from attacking my mages all at once.

I used my new Arch Mage to soften up the southern lich, and one of the red mages to deal him the final death blow.

What about Konrad? Well, I sort of forgot about him, and left him in the middle. My Konrad is a level three character, so I would probably have sent him South to act as an additional backup, had I remembered him.

Now that I’ve lost my respect for the Valley of Death, I’m going to try again with a few changes. First of all, I won’t use my Grand Knight. It’s better to my level one horsemen so they can gain some experience. Second, I’ll let Konrad go South instead of recruiting the scout. He will be responsible for creating a diversion.

I also think I’ll send two white mages and a red mage up north, and let the third white mage join in to the south. That way I have one unit that can heal there and won’t need the shaman anymore.

A few tips

First of all don’t get close to the liches with units that are injured. It’s a quick way of losing them, as the lich will attack a weak unit. As a matter of fact avoid confrontation with a lich during the night (they are hard to defeat then). When you do attack, it’s a good idea to have a powerful unit (Defaldor, a Mage of Light or an Arch Mage) standing by, just in case they need to step in. Once you begin your attack on a lich you should finish him off before he gets a chance to counter-attack.

Keeping the white mages together in the north is a good idea, since they heal each other.

In the South you really need to position the units carefully to avoid a single unit being attacked by multiple enemy units at once. This is also true to lesser degree to the North. To the East however, you will want to place your horsemen where they can act like “corpse magnets”. The more the merrier.

When you are recruiting/recalling, make sure you position the units so that they can move as far as possible in the direction they are going. The key to success here is a swift attack, at least to the North and to the East. You shouldn’t let the wraths get a chance to get away as they are way to quick for a mage to keep up with. I held back a little more to the South, where I used the scout to try to as far as possible single out enemy units and take them out one by one.

Obviously how you play will depend on what type of units you have. I tend to use mostly mages on Isle of Anduin, Muff Malal’s Peninsula and Seige of Elensefar. At the Bay of Pearls my horsemen get a lot of battle experience. On the Princess of Wesnoth episode, I use a combination of mages, elvish rangers and horsemen to attack from different directions. That way, by the time I get to Valley of Death I already have some experienced mages as well as horsemen.

Building an object model in PHP #1: A database combo

Filed under: Object-oriented programming, PHP Programming — Lorenzo E. Danielsson @ 00:29

These days it seems to be increasingly common to hate PHP. If you look at some of the PHP code that has been written, perhaps one can understand why. But PHP code doesn’t have to look like a mess. In this series I will show you how to evolve an object model in PHP.

It may very well be that PHP sucks, but that is of no concern to me. PHP exists and I am interested in programming. I aim to teach you how it can be used. I assume you can figure out for yourself whether or not PHP is a good tool for whatever task you have.

What we are going to do is develop a fragment of an object model representing HTML elements. I know, it has been done already, and a number of times. Some of the implementations are much better than I could ever hope to accomplish. But we are learning, so we don’t really care about that. We will place ourselves in a possible world where no such model has been developed.

Experts in object-oriented programming know that the best worlds are the ones that are created by intelligent design. Normally this design is done using UML (the Useless Modeling Language), a tool created by a group commonly referred to as “the 666 Amigos”. UML is a part of a plot to take the fun out of programming.

Jokes aside, UML is a useful tool, especially when projects become large. But I am looking through the eyes of a programmer so I will not go into UML. If you are serious about object-oriented programming, then learning UML is not going to hurt you one bit. Go out and buy yourself a book on the subject.

As I am going to try to show off some OO techniques in PHP, I will occasionally take the OO concept too far. I will implement objects for just about everything. When you are back in the real world, you will have to judge how far it makes sense to use objects. It is very possible that in some cases it doesn’t.

A final note: I will be using some features that are only available in PHP5. You can do object-oriented programming in PHP4 as well, but it will look slightly different.

The problem

At this current point in time I’m not really interested in developing any object model at all. My problem is simple: I have been working on a web application for a while and I’m beginning to realize that I am doing a lot of CRYing (Constantly Repeating Yourself). Looking into the code a bit, I have noticed that I have quite a few database lookup tables. In my web application, I usually represent this as combo boxes (if you don’t like the word combo box then you may s/combo box/whatever you like/g).

These combo boxes have a few things in common. They are populated by simple SELECT queries that return two columns: an column that uniquely identifies the row (an ID column) and one that contains some form of textual representation of the row. For example, to populate a combo box showing departments within an organization I might use the following SQL statement:


select id, department from departments;

For people I might use:


select id, concat(firstname, ' ', lastname) as name from friends;

Furthermore I only have MySQL installed on my system. Any time I sell my application I install MySQL for the client. I have heard that there are other database servers out there but I am (at this stage) satisfied with supporting only MySQL. Not a single one of my clients has complained about it so far.

This gives us a starting point for developing a first class.

The combo box

Below is a first implementation of a combo box class.

<?php

class ComboBox {
    private $db;
    private $sql;

    public function __construct($sql) {
        $this->sql = $sql;
        $this->db = mysql_connect("localhost", "dbuser", "n0tap455w0rd");
        mysql_select_db("storage");
    }

    public function __toString() {
        $result = mysql_query($this->sql);
        $html = '<select>';
        while ($row = mysql_fetch_array($result)) {
            $html .= '<option value="' . $row[0] . '">'
                . $row[1] . '</option>';
        }
        $html .= '</select>';
        return $html;
    }
}

?>

As you can see, the ComboBox class currently has two methods: __construct and __toString. Both of these are special (PHP tends to use double underscore for special methods). The first one, __construct is the class constructor, that is the method that is run when a new instance of this class is first created. The __toString is used to convert an instance of this class into a string.

In the constructor we set up a connection to the database as well as store the SQL statement that will be used to populate the combo box. The __toString method simply returns the HTML to generate the combo box. Note that it only returns the HTML as a string. To actually make the combo box appear on a page you would have to echo the string.

There are a number of shortcomings with the ComboBox class as it currently stands. The database connection is hard-coded inside the class. There is absolutely no error-handling done. But at this stage I don’t care. Remember that the current requirement was just to create a re-usable combo box that gets its list items from the result of a database query. And it does just that, as long as we stick to one particular database.

We can test the combo box class with something like the following:

<?php
require_once("./combo.php");
$cb1 = new ComboBox("select id, department from departments");
$cb2 = new ComboBox("select id, concat(firstname, ' ', lastname) as name "
    . "from friends");
?>

<html>
<head>
<title>Testing: Combo box</title>
</head>
<body>
<p>Let's see if we can't generate a combo box or two.</p>
<?= $cb1 ?><br />
<?= $cb2 ?><br />
</body>
</html>

In order to get things working you will have to modify the connection statements in the ComboBox class as well as the SQL statements in the test page. The connection should be to a database that you have on your system and the SQL statements should select from tables in that actual database.

Conclusion

So far we have developed a single class, so we can’t really talk about an object model at all. In the next tutorial things will begin to change as I get a troublesome client who does not want to use MySQL. Also, I find myself wanting to be able to use the combo box in another web application, so there are more reasons to make the class more generic.


Update 2007.06.12: Fixed typo in title.

2007.06.08

That would be Sir Lorenzo, if you don’t mind

Filed under: Computer Games, Web Sites — Lorenzo E. Danielsson @ 19:52

Today this blog was mentioned on Free Gamer! If you don’t understand what the fuss is about, all I can say that for somebody that is into open source gaming, that is pretty much the equivalent of being given a knighthood or a sainthood or something like that. So from now on that is Sir Lorenzo 😉

Let me just state once more what a great resource Free Gamer is. Within the free software gaming community it really is second to none. I know Charlie puts in a lot of good work to keep providing us gamers with news. Maintaining a quality blog (as opposed to blogs dedicated to mindless rabbling about Paris Hilton) takes quite a bit of time. If you like the site, head over there and give some support.

If you read the article I linked to above, you will notice that he’s actually asking for some community feedback. Let Charlie know what direction you would like Free Gamer to take.

2007.06.06

Translating source code into a different language as practice

Filed under: Computer Programming, Java Programming — Lorenzo E. Danielsson @ 13:05

One of the things I encourage my programming students to do is to take open source programs and rewriting them in a different programming language, or using a different GUI toolkit. There are a number of benefits to this:

  1. The student learns to read somebody else’s code
  2. The student learns to analyze code in a language that is different from the one they are learning
  3. The student (hopefully) learns a few new programming techniques along the way
  4. It is yet another way to keep the student writing code
  5. It provides a bit of variation from the old “write a program that..”-type exercises.

It’s easy to say that this is a “passive” process, meaning the student simply just translates the code to “their own” programming language without reflecting much about what they are doing. That may be true for some people, but then again, some people go through an entire programming class without reflecting much on what they are doing.

Another thing is that a friend of mine raised the concern that programming languages sometimes differ in techniques and that if I am translating a C program into Java I might be learning “C-isms”. First of all, I don’t quite understand what is so wrong with “C-isms”. Secondly, it is your responsibility as a teacher/mentor to review their code and point out areas where they could improve the program.

Remember that at first the student’s primary concern is with getting the program running at all. It is only once they have been able to do succeed in that that they will start worrying about “making it look like a conventional Java program”. The following might be a rough sketch of this process.

  1. Translate the program straight off (leaving variable names exactly the same etc). At this stage, the students only concern is to get the program to compile (in the case of a compiled language) and run, with all the functionality of the original program intact.
  2. Next they begin to do things like renaming variables to suit the language. For example, if translating a C program to Java, you might want to rename a variable from x_axis to xAxis simply because that is a convention that most Java programmers follow.
  3. Then the student refines the code. In the case of translating from a non-object orient language to an object oriented one, this might involve moving parts of the application functionality out into classes, where that makes sense.

Translating a program from for example C to Java, or from using Qt to using Gtk is not some form of miracle solution that will turn everybody into a master programmer. But it is a way to let the people who are genuinely interested in programming to get some extra practice. That’s all. I find the exercise useful. I would love to hear what others think. Please leave your comments/experiences in the comments section.

Finally I will give a small example. Recently, I had a Java student who said he wanted to learn how to do graphics programming. So I helped him get a hold of some programs (mostly in C) and told him to start translating them into Java. To demonstrate it I took this program by CorTeX/Optimum and wrote it as a Java applet. You can see the result below (you will obviously need to create an HTML document to load the applet in order to see it in action).

  1 /*
  2  * "Flashouillis" for Java.
  3  *
  4  * Original C program written by corTeX/Optimum.
  5  *
  6  * Author: Lorenzo E. Danielsson <danielsson.lorenzo (AT) gmail DOT com>
  7  * Date created: 2007.04.21
  8  */
  9 
 10 import java.awt.Color;
 11 import java.awt.Graphics;
 12 import java.awt.Image;
 13 import javax.swing.JApplet;
 14 
 15 import static java.lang.Math.cos;
 16 import static java.lang.Math.sin;
 17 import static java.lang.Math.random;
 18 
 19 public class JFlash extends JApplet implements Runnable {
 20     private final int WIDTH = 500;
 21     private final int HEIGHT = 500;
 22     private final int DELAY = 10;
 23     private final int FLASH_MAX = 5000;         // Number of points.
 24     private final int G_ACC = 330;              // Acceleration (g).
 25 
 26     private Thread animation = null;            // Animation thread.
 27     private Graphics buffer = null;             // Back buffer for drawing.
 28     private Image image = null;
 29     private Flash[] flash = new Flash[FLASH_MAX];
 30     private int current;
 31     private float ax = 0.0F, ay = 0.0F, az = 0.0F;
 32 
 33     public void init() {
 34         image = createImage(WIDTH, HEIGHT);
 35         buffer = image.getGraphics();
 36 
 37         for (int i = 0; i < FLASH_MAX; ++i) {
 38             flash[i] = new Flash();
 39             flash[i].state = 0.0F;
 40         }
 41 
 42         current = 0;
 43     }
 44 
 45     public void paint(Graphics g) {
 46         buffer.setColor(Color.BLACK);
 47         buffer.fillRect(0, 0, WIDTH, HEIGHT);
 48 
 49         for (int i = 0; i < FLASH_MAX; ++i) {
 50             if (flash[i].state == 0 || flash[i].state >= 1)
 51                 continue;
 52 
 53             int x = (int)(flash[i].x + flash[i].vx * flash[i].state);
 54             int y = (int)(flash[i].y + flash[i].vy * flash[i].state
 55                     + (flash[i].state * flash[i].state) * G_ACC);
 56 
 57             if (x < 0 || x > WIDTH || y < 0 || y > HEIGHT)
 58                 continue;
 59 
 60             int red = (int)(flash[i].r * (1 - flash[i].state)) << 3;
 61             int green = (int)(flash[i].g * (1 - flash[i].state)) << 2;
 62             int blue = (int)(flash[i].b * (1 - flash[i].state)) << 3;
 63 
 64             if (red > 255) flash[i].r = 255;
 65             if (green > 255) flash[i].g = 255;
 66             if (blue > 255) flash[i].b = 255;
 67 
 68             buffer.setColor(new Color(red, green, blue));
 69             buffer.drawLine(x, y, x, y);
 70 
 71             flash[i].state += 0.007F;
 72         }
 73 
 74         g.drawImage(image, 0, 0, null);
 75     }
 76 
 77     public void run() {
 78         Thread thread = Thread.currentThread();
 79         while (animation == thread) {
 80             repaint();
 81 
 82             int x = (int)(WIDTH/2 + WIDTH/4 * (cos(ax+ay) + sin(ay-az)));
 83             int y = (int)(HEIGHT/2 + HEIGHT/4 * (sin(ax-ay+2*az)
 84                         + sin(ax+ax/2)));
 85 
 86             for (int j = 0; j < 40; ++j) {
 87                 float rd = (float)(2.0 * random() * Math.PI);
 88                 float vx = (float)(cos(rd));
 89                 float vy = (float)(sin(rd));
 90                 rd = (float)(50.0 + random() * 30.0);
 91                 vx *= rd;
 92                 vy *= rd;
 93 
 94                 flash[current].x = x + ((int)(random() * Integer.MAX_VALUE)
 95                         & 3);
 96                 flash[current].y = y + ((int)(random() * Integer.MAX_VALUE)
 97                         & 3);
 98 
 99                 flash[current].vx = vx;
100                 flash[current].vy = vy;
101                 flash[current].state = 0.01F;
102 
103                 flash[current].r = (int)(10 * cos(ax*6) + 20);
104                 flash[current].g = (int)(20 * cos(ay*5) + 40);
105                 flash[current].b = (int)(10 * cos(az*7) + 20);
106 
107                 ++current;
108                 if (current == FLASH_MAX)
109                     current = 0;
110             }
111 
112             ax += 0.05F;
113             ay += 0.03F;
114             az += 0.0441F;
115 
116             try {
117                 thread.sleep(DELAY);
118             } catch (Exception e) {}
119         }
120     }
121 
122     public void start() {
123         animation = new Thread(this);
124         if (animation != null)
125             animation.start();
126     }
127 
128     public void stop() {
129         if (animation != null)
130             animation = null;
131     }
132 
133     public void update(Graphics g) {
134         g.clipRect(0, 0, WIDTH, HEIGHT);
135         paint(g);
136     }
137 }
138 
139 class Flash {
140     public int x = 0, y = 0;
141     public int r = 0, g = 0, b = 0;
142     public float state = 0.0F;
143     public float vx = 0.0F, vy = 0.0F;
144 }
145 

So this obviously does quite a few things that look familiar to a C programmer but maybe less so to a person from a Java background. But the point is that Java does support the shift operators. I’m not sure if you gain anything performance-wise in Java by using the shift operators for multiplying and dividing, but it is not illegal to do so.

Now this is just a first iteration of the program. It works, and looks like the original when run. You could easily modify it to look “better” from a Java point of view.

2007.06.02

Alternating row color in HTML/CSS (with PHP)

Filed under: CSS, HTML, PHP Programming — Lorenzo E. Danielsson @ 00:28

I frequently get asked how to create an HTML in which the rows have alternating background color. Most of the people who ask me this are PHP programmers or at least striving to be, so I’m going to use PHP for the example, but the principle is of course valid regardless of implementation language.

First of all, create two CSS classes, row0 and row1. Set the background-color of each to be a different value. Here is an example:

.row0 {
    background-color: #ffffff;
}

.row1 {
    background-color: #f0f0f0;
}

You will probably be creating your table rows inside a loop of some form. You will need to have flag that will hold either 0 or 1, depending on the CSS class to use for the current table row. How do we make sure that the value is always 0 or 1? Simple. Assuming the name of our flag variable is $rowclass then we just do:


$rowclass = 1 - $rowclass;

Since this will evaluate to 0 if $rowclass is 1, or 1 if $rowclass is 0 it does exactly what we want. I think it is easier to understand how it works if you see it used. So take a look at the following:

<html>
<head>
<title>Table example</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
<table>
<tr>
<th>Toon</th>
</tr>

<?php
$toons = array("Bugs Bunny", "Daffy Duck", "Tom Cat", "Jerry Mouse");
$rowclass = 0;
foreach ($toons as $toon) {
?>
    <tr class="row<?= $rowclass ?>">
    <td><?= $toon ?></td>
    </tr>
<?php
    $rowclass = 1 - $rowclass;
} ?>

This assumes that you called your stylesheet file style.css and placed it in the same directory as the php file. If you did that you should see a table with four rows, where rows one and three have a white background and rows two and four have a light gray background.

This simple example iterates through the array $toons, but you could do the same thing if your data is the result of a database query.

While we’re at it, I also get asked how to make the rows change background color when the mouse moves over them. That isn’t difficult either. Just add the following to your stylesheet:

.row0 {
    background-color: #ffffff;
}

tr.row0:hover {
    background-color: #ffff00;
}

.row1 {
    background-color: #f0f0f0;
}

tr.row1:hover {
    background-color: #ffff00;
}

Adding the :hover part specifies the style to apply when the mouse is over a table row. This is frequently used to style hyper-links, but it can be used for table rows as well.

Blog at WordPress.com.