Dusting off CuteMaze

Sometimes I look at old code and say, “What in the world was I thinking?”. I had such an incident today. For an unrelated reason I found myself looking at the source code of CuteMaze. One piece of code in particular stood out: the placement of targets on the maze. This is the code in the current version:

// Add player
m_player.setX(rand() % (columns - 1));
m_player.setY(rand() % (rows - 1));
m_start = m_player;

// Add targets
QList locations;
if (columns * rows > m_total_targets * 2) {
    locations.append(m_start);
    QPoint target;
    for (int i = 0; i < m_total_targets; ++i) {
        do {
            target.setX(rand() % (columns - 1));
            target.setY(rand() % (rows - 1));
        } while (locations.contains(target));
        locations.append(target);
        m_targets.append(target);
    }
// Handle if targets cover half or more of the maze
} else {
    for (int c = 0; c < columns; ++c) {
        for (int r = 0; r < rows; ++r) {
            locations.append(QPoint(c, r));
        }
    }
    locations.removeAll(m_player);
    int pos;
    for (int i = 0; i < m_total_targets; ++i) {
        pos = rand() % locations.size();
        m_targets.append(locations.takeAt(pos));
        for (int y = 0; y < size; ++y) {
            for (int x = 0; x < size; ++x) {
                locations.append(QPoint(x,y));
        }
    }
}

Now that is some pretty strange code. And its major flaw is that as the number of targets increases it gets a lot slower, which apparently I tried to paper over. I randomly selected a location and tried to place a target, unless the number of targets was over half of the maze, in which case I selected random locations from a list. Riiight. Instead, here’s the code that will be in the next version:

QList locations;
for (int y = 0; y < size; ++y) {
    for (int x = 0; x < size; ++x) {
        locations.append(QPoint(x,y));
    }
}
std::random_shuffle(locations.begin(), locations.end());
m_player = m_start = locations.first();
m_targets = locations.mid(1, m_total_targets);

Now I make a list of all locations in the maze, shuffle it, and use the first location for the player and the next group of locations for the targets. Simple, fast, and scales all of the way up to having targets in every single cell of a 10×10 maze (Whee! It’s Pac-Man! :-P).

Of course, changing the target placement code means that old save games won’t work. I seem to be on a roll of breaking compatibility lately. If I’m going to do that, I might as well see if any of the rest of the code makes me say, “What in the world?”.

Advertisements

Comments are closed.