31 Things, Day 15: Programming

31 things I'd rather be doing right now

There is something very satisfying for me about programming. I’m specifically referring to coding here; it’s part problem-solving, part art. The problem to solve can be small (make this mess of text into a nice table), or big (make a game).  The art part is the design of the code “building blocks” that will work together to make a computer program. The term used among programmers is “elegant code,” and I think it is an apt word. If you can create some code that can be reused for many things, both now and in the future, you just saved a lot of time. You never have to touch it again, because you know it works. I love that.

Take this example from my own game code, which I find to be very elegant, (if I do say so myself). A tile-based game is a grid where objects can move in any direction to a tile next to it. Sometimes an object can’t move for various reasons, maybe it’s blocked by a wall. In any case, a game needs to be able to handle an object moving from one tile to another.

2dgame

 

When I first made my Heroquest game, the code handled moving objects very specific to the game. I would never be able to use the code again, because it was very closely tied to only that game. Later, I discovered I could refactor that code and make it reusable. In order to do that, I had to completely generalize what was happening when an object moved from one tile to another. It doesn’t matter if the game is Heroquest or Monopoly or Sorry!

This is what I came up with:

When a pawn wants to move in a certain direction, follow these steps

  1. Does the pawn meet the prerequisites to be able to move in the first place? If no, do something else because they are not met. Otherwise, continue
  2. Are Diagonal moves allowed? If no, does the pawn want to move diagonally? If yes, do something else because diagonal moves are not allowed. Otherwise, continue
  3. Does the tile the pawn wants to move to exist? If no, do something else because the tile can not be found. Otherwise, continue
  4. Is the tile the pawn wants to move to accessible based on where the pawn is now? If no, do something else because the move is blocked. Otherwise, continue
  5. If you got this far, the move will now happen:
  6. Process/do the physical move itself
  7. Evaluate the ramifications of the move to the pawn, the surrounding area, and/or the whole game itself
  8. Do any post-move processing (clean up, things that always happen at the end of a move, etc)

Now I had a skeleton framework to make some reusable code, and I could use it any game I wanted. Here is the actual code:

public void move(TileOccupier pawn, Compass dir) {
  if (movePrerequisitesMet(pawn))
  {
    if (!(!diagonalMovesAllowed() && dir.ordinal() > 3))
    {
      AbstractTile targetTile = 
        tileMap.getAdjacentTile(pawn.getLocation(), dir);    
      if (targetTile != null)
      {
        movePreProcessing(pawn, pawn.getLocation(), targetTile, dir);
        if (tileMap.isEnterableFromOppositeDirection(targetTile, dir) ||
          ignoreTileBoundaries(pawn, dir))
        {
          processMove(pawn, pawn.getLocation(), targetTile, dir);
          evaluateMove(pawn, pawn.getLocation(), targetTile, dir);
          movePostProcessing(pawn, pawn.getLocation(), targetTile, dir);
        }
        else { processMoveBlocked(); }
      }
      else { processTargetTileNotFound(); }
    }
    else { processNotAllowedDiagonalDirection(); }
  }
  else { processMovePrerequisitesNotMet(); }
}

Not that long at all. And the way it works is that any game I make in the future will be able to use it because it is abstract. I simply have to make some concrete decisions about what happens in the particular game at the various stages of the move. (For example, one game may yell at you when try to move diagonally; another game may do nothing at all.)

For the non-programmer types reading this blog, this post may have been boring. But whenever I look at that code above – something I made all on my own – I think, “wow, that was a really elegant design.”

And then it makes me want to go code something!

So that’s another thing I’d rather be doing now, programming.

Advertisements

Ransackediron Restored, Part 7: A Dwarf Fortress Story

← Continued from Part 6

10th day of Malachite, 551 years since the Record began,

Stakud “Closebolt” Urolalath, Manager, Head Mason and Bookkeeper for the Expedition Group Anuzlolor, “The Fair Letter”

Tonight I sensed a level of contentment in my kin that I have not felt in quite a while. I think it has to do with the number of improvements we have made to the outpost, as well as the state of affairs in the area.

Our biggest improvement is Stodir’s latest excavation project: bedrooms. It seems like such a simple thing – and they are very small rooms – but I can’t count the number of dwarves that have personally thanked me for giving the order for their construction. Previously with just two dormitories, our increasing numbers were making privacy a new concern – and with children now all about, sleep was becoming near impossible. Almost three dozen alcoves have been dug out, which allows for most of us to have a private room; the couples and families can also share a room to themselves as well. We will likely turn the two dormitories into another storage room and a barracks.

bedrooms

Another improvement that has been a long time coming: the thaw arrived, and our cistern is full!

full_cisternThe design of the pump and channel system worked flawlessly and quickly; clean, fresh water is now deep underground, protected from the harsh cold winters, easily gathered from a marble block well I designed myself. The well has already become a frequent place of socialization and relaxation, lifting everyone’s spirits.

well_hangout

Still, that area can not hold us all, so I think the time has come to carve out a dining hall from the marble vein near the underground farms. I have not engraved anything since our first month here, and there is so much history we need to record on the walls!

There are still no signs of goblins, which is another reason we are at ease. I think we have enough defensive measures in place to begin crafting items that are of some worth. It may draw unwanted visitors, but it will certainly draw traveling merchants which so far have been unimpressed with us. Just this week a human caravan from Uhosgil arrived and we almost turned them away, for we thought we had nothing to offer. They happened to see our kitten skull totems and were eager to have them; since we had no use for them, we agreed, and gave us fresh fish in return. A strange trade, but we never say no to food. We hope that next time merchants arrive, be they human, elf, or dwarf, we will dazzle them with all manner of works that only we can create.

Yes, life is good here in Roofloves. Yet our leader, Lokum, does not seem to agree. She has not been herself of late. I have always found her hard to read since our arrival, but a few weeks ago she acted quite strange, even for her. She was making crossbow bolts from bone fragments, when suddenly she stopped and began running around the outpost looking for something.

lokums_mood

We watched in confusion as she gathered strange materials and then returned to her work area. She muttered under her breath for several hours. We left her alone as she worked, and then in the night she called out in a loud voice: “Salirlised!” We ran to her, and she was holding a beautiful scepter high above her head. It looked like she carved it from the leg bone of a wombat.

artifactartifact2

A scepter? What use is that to us here? Does she seek to become a baroness – or worse, our queen? I can’t fathom what is going through her mind. I wonder if she even knows. As always, I will be watching her…

Gameplay breakdown

Not really much I can say here that Stakud hasn’t already said. I noticed a lot of the dwarves had negative thoughts about not sleeping in their own room, so I figured it was time to make private bedrooms. I went with a new design called the Savokis Leaf that I found in the “blueprints” folder of Quickfort; but I didn’t actually use the Quickfort utility to make it, because I didn’t have time to learn how to use it yet. The design is much better than what I was going to do (basic rows), so I’m glad for that.

designate_rooms

The Hall of Death grows more deadly with an assortment of traps being added as I make more devices.

weapons_trap_ordersThis will be interesting when I get attacked. It should happen soon, I would imagine – I struck platinum ore when digging out the bedrooms, so that should have spiked my wealth a bit.

hall_of_death_deadlier

I LOVE that it was Lokum that had the strange mood and created the artifact scepter. Couldn’t have asked for better story fodder.

Finally, I loved using that pump for the first time. Filled up so fast!

pumping

The story continues next week…

If you’re enjoying this story, perhaps you might enjoy my original fantasy novel, By the Light of the Moons, available for download on Amazon Kindle.

Ransackediron Restored, Part 6: A Dwarf Fortress Story

← Continued from Part 5

28th day of Obsidian, 550 years since the Record began,

Stakud “Closebolt” Urolalath, Manager, Head Mason and Bookkeeper for the Expedition Group Anuzlolor, “The Fair Letter”

The winter is nearly over. I sit here at my desk, a fine wine in one hand, quill in the other, as I warm my sore muscles by the heat of boiled stones Stodir prepared for me. On this final day of the year, I cannot help but look back and wonder how we have lasted so long here with so little. A few weeks ago, I thought it was the end for us; thankfully, I was wrong.

It happened due to my own mismanagement of the outpost. My thoughts and efforts were ever on the defenses, mostly overseeing the trap for Siga our great enemy, and I would not listen to those closest me. I would become annoyed at the slightest interruption of my work, and I just bellowed out orders without planning, without thinking. I focused everyone’s efforts on the Hall of Death, to the detriment of all. Then the alcohol ran dry.

I’m sure someone noticed the dwindling supply; it’s possible they even told me about it. But when I reached for a mug of ale myself and found an empty barrel, only then did I see my folly: no brew; all the water outside frozen, and our barren cistern incomplete. A dozen thirsty dwarves looked at me blankly, some with contempt. I deserved it.

I immediately sent the brewers to work at the still, and the carpenters to create more barrels. As I oversaw the operation, Stodir returned with news that the next stage of the hall was ready for planning. Still angry at myself, but childishly taking it out on her, I ordered Stodir to begin a trench. She started to explain why it wouldn’t work. I didn’t listen.

Days later, I saw why Stodir had warned me – a trench in the Hall of Death led right down into the level we had dug out months ago, into the patch of silty clay the farmers were using. Stodir dug it to prove a point. No one was hurt (she saw to that) but the damage to my pride was her intention, and she succeeded. It was the best thing she could have done for me.

I summoned all that night, and begged their forgiveness for my missteps. We have been here almost a year; it is no longer an outpost, it is our home. It is time we started making this place feel that way. This week we corrected the trench, and come spring, we will move on to bettering our stay here.


17th day of Granite, 551 years since the Record began,

Stakud “Closebolt” Urolalath, Manager, Head Mason and Bookkeeper for the Expedition Group Anuzlolor, “The Fair Letter”

Such activity this week as we have never seen! Elves from Senawimimale came with their wares, and we hastily crafted a place of trade for us all to deal. We had very little to offer, but they seemed delighted with our gemstones, even the rough ones Ezum had not cut yet. In return they traded delectable fruits which we took gratefully, and some well-crafted hardwood armor and shields for our defenses.

Not a day later, the outpost was overrun by thieves; not by goblins or kobolds, thank Rimtar, but Kea. These giant birds must have traveled in the Elves’ wake, for we had never seen them before. They swooped in between our ranks, stealing not our food nor seeking to hurt us, but simply to take away our new purchases before we even had time to bring them inside. I can laugh now at the absurdity of it all, but at the time, the outpost was furious. What would a bird want with a wooden shield? we all wondered. The Elves merely smiled and shrugged, and reminded us that all trades were final. Perhaps the tree worshipers trained these pests? The Kea are gone, but the Elves remain nearby, so perhaps not. Still, we will be more vigilant the next time.

As if this was not enough, two days ago, as we celebrated our first year here with a rousing party, who should arrive but more migrants from the west. None of them were from the besieged cities, nor had they seen any signs of goblin ranks in the area. Have we dodged an arrow, and the goblins will not attack? We hope so.

The migrants have brought children. Kel and Lor, newlywed, cradle their baby girl Cilob, just months old; Olon the brewer brought his three children with him, yet his wife Vabok, whom he talks of often, is not among them. And just today Sarvesh and Shorast from our first newcomers welcomed their baby girl Nil into the world.

The addition of children changes everything here, for now we truly are a home, a place that must be safe but also a place to grow, to thrive. Even in my old age, I look to Stodir and wonder if we should attempt to bring a young one here. But first, the outpost must know we are betrothed. I can’t wait to see the looks on their faces.

Gameplay breakdown

I love this game, even though it’s so hard! So much to keep an eye on once the population starts increasing, and boy did I make a huge mistake! While micromanaging the trap hall, I noticed this message, my first indication of trouble:

noWaterSource

No water source? That usually means someone is injured, someone else is trying to give the injured party water (injured can’t be given alcohol), and since I have no well or cistern, they are out of luck. But just as I was looking for the injured dwarf in a bed, that’s when I saw this:

thirsty

Those blue down arrows are my thirsty dwarves. That many thirsty dwarves can only mean one thing: the alcohol’s gone. Nothing strikes fear into the heart of dwarf fortress player like seeing a dozen unhappy dwarves that could turn destructively berserk with rage. Luckilly, I must have caught things early, for once I made a batch of brew, the thirsties went away. Phew.

It was at this same time I made a stupid mistake in the trap hall, telling the miner to dig a trench, forgetting that I already had dug out the level below for farms. The last thing I want is for enemies to use the trench to get in the fortress through a back door I never intended. I was able to patch it up, thankfully:

trench_below

Below

trench_above

Above

Then those Keas! What the heck is a kea? I had to look them up. Apparently they really do exist, and they really do steal things they can’t use. Awesome.

kea

Pretty vicious though. Banged up my worthless war dog that’s supposed to guard against intruders. I feel safe now.

kea_dog_fight

When the next batch of migrants arrived, I realized I hadn’t looked at the relationships screen at all since starting the game. Imagine my surprise to find out that my main character and the buff and burly female miner were an item. How cool is that? Fits right in with the story (all those long nights together… digging.) :/

lovers

And then the first birth. Aw…

its_a_girl

So a lot happened in a short amount of time, as always in this game. And now that I am over 30 people, it’s time to ditch the dormitories and start making individual rooms, so the couples can have some peace and quiet. I need a bigger dining hall too.

Let’s hope the goblins continue to stay away. And the keas.

The story continues in part 7.

If you’re enjoying this story, perhaps you might enjoy my original fantasy novel, By the Light of the Moons, available for download on Amazon Kindle.

Ransackediron Restored, Part 5: A Dwarf Fortress Story

← Continued from Part 4

25th day of Limestone, 550 years since the Record began,

Stakud “Closebolt” Urolalath, Manager, Head Mason and Bookkeeper for the Expedition Group Anuzlolor, “The Fair Letter”

So it is true: goblins are on the move. Our Mountainhome liason Endok Kuletkoman arrived yesterday and met with Lokum and I to discuss the disturbing news. Submergedmirror, a fortress just to our southwest, was conquered by the goblins of the Witch of Steam. The fortress Shielddike is being sieged right now, by a group of goblins calling themselves The Untoward Curses, led by Sasmar Screamworried. Eleven small groups of dwarves are known to have escaped, but their current fates and the fate of the fortress are uncertain. We all fear the worst.

liason_news

Every dwarf in our outpost decided, unanimously, that to venture off and search for survivors is foolhardy. A small band of goblins might be thwarted, but a siege army? They would flatten us to the very stones we sprung from. We stay here, then, and make a stand even to our deaths. If Sasmar and the Untoward Curses come this way, we intend to fight on our terms, where we can control the battle. Ideas are being sketched out now, but time may be short. We must work quickly, for our enemy could arrive at any moment.

Endok arrived accompanied with some traveling merchants, but we have nothing to trade with them. I wish we did, for we could use some arms, food stores, anything that could aid us if we were besieged. But there’s nothing to be done about it now.

no depot


1st day of Moonstone, 550 years since the Record began,

Stakud “Closebolt” Urolalath, Manager, Head Mason and Bookkeeper for the Expedition Group Anuzlolor, “The Fair Letter”

Winter is upon us, and we have heard no more news of the siege in the south, nor have we seen any inklings of goblin activity near our site. Despite this seemingly good news, no one here is at rest. Realizing our numbers are simply too small for open combat, and since our battle experience is limited as it is, we have instead decided to fight with what we do have: the very rock we stand on. The plan is simple: lure the simple-minded goblins into a trap–or should I say, traps.

We have created an alternate entrance to our home which opens on level with the vast field. We will make it appear to be our official entryway so as to call the goblins’ attention. If a wide open doorway isn’t enough incentive, the hens have hatched over thirty chicks, so we will have plenty of bait for the bloodthirsty abominations to come after.

chicks2chicks

Once they are inside, we will seal the gate shut, and the enemy will have to navigate what the men have nicknamed “The Hall of Death.” We will have traps of all kinds waiting for the creatures, ready to crush, saw, maim, dismember and impale their twisted bodies until every last one of them lies dead. If by some miracle they are able to escape these traps alive, a narrow corridor awaits them where we can fire our arrows at them from behind safe fortifications. If any of the enemy should survive all this, then the god Rimtar is against us. May it never be!

Our grandest trap I have designed myself, and although its true target is Siga Gravefatal himself, I will use the goblins to test it. It is a tall platform of towering rubble that will fall upon any creature which triggers a pressure plate on the floor beneath it. I dare Siga or any creature to escape it alive.

Gameplay breakdown

One of the things I’ve always been bad at in this game is defense. The sheet amount of other things to keep track of is daunting, and I always – ALWAYS – seem to forget to make some kind of deterrent into my fortresses. The game makes it relatively easy to have basic defenses: walls, moats, traps, retractable bridges, things like that. This time I want to be ready, not just for the sake of the story, but because now I have warning that the goblins are likely coming soon.

How do I know? Prior to July’s update, ambushes and sieges happened at regular intervals, and the strength of the attacking force was proportional to your fortress’ total wealth. I thought that to keep the wealth down was to keep safe. From what I gather now, because of the “world activation” enhancement to the game, attacking forces are pre-existing bands of enemies that are traveling the map. So when I saw the news of attacks from my liason, and I used Legends Viewer to see where these locations were (close to me!), I immediately changed tactics to a defensive posture. I would love some kind of elaborate obstacle course-like system, but what I am planning will have to do.

trap_hall

While I’m at it, I figured I would construct the weapon which should hopefully defeat the forgotten beast Siga Gravefatal, if I am successful in luring him out of hiding. (It’s the whole purpose of my story, after all.) A few years ago I had created a similar pressure-plate-triggered cave-in trap, and it killed a forgotten beast. I’d love for it to work again this time.

The story continues in part 6.

If you’re enjoying this story, perhaps you might enjoy my original fantasy novel, By the Light of the Moons, available for download on Amazon Kindle.

Ransackediron Restored, Part 4: A Dwarf Fortress Story

← Continued from Part 3

1st day of Limestone, 550 years since the Record began,

Praise Rimtar for many hands! Our modest outpost has expanded greatly, with everyone working harder than ever. Lokum has, as I feared, become overwhelmed with the duties of leader, and the rest can see it. There is so much to be done, and Lokum is simply slowing us down. While she will retain the now ceremonial title of Expedition Leader, the group has unanimously elected me Manager of Roofloves, and I have taken up my position with great pride. I am not a harsh task master, but I am respected, and because of that we are making incredible progress.

I assigned apprenticeship tasks to the new dwarves and everyone is learning at a quick pace. My junior masons have made the kitchen and still and some doors, and our woodworkers have made beds, barrels, and a retaining wall around our pump.

pump_area_before

Pump is ready

Stodir is unstoppable in her excavation! I am now forever in her debt, for she prevented me from making a horrible mistake. I was about to give the order to begin pumping into the cistern when she stopped me – we had not yet dug the well shaft above the cistern! In truth, I had not forgotten it, but she being the experienced miner explained the safety of digging now, before the water is in there. She sketched out her plans for a well, completely underground, accessible only via a long corridor from under our current home. Though I deemed it very sensible and thus conceded, I do fear this has set us back a week or two. Autumn is here; I feel a chill in the air, and I know frost is just around the corner. We must pump before the pond freezes. Perhaps one last touch-up to the cistern is in order: a grate, to prevent small fish that made it through the pump from getting into the cistern.

well_area

Black hole = well shaft above cistern (well itself still to be built)

Some mixed news came this morning: the hunting dog gave birth to puppies, which is welcome, but the cats have also had a litter. The last thing this place needs is to be overrun with felines. I wonder what anyone else thinks of grilled kitten.


22nd day of Limestone, 500 years since the Record began,

Stakud “Closebolt” Urolalath, Manager, Head Mason and Bookkeeper for the Expedition Group Anuzlolor, “The Fair Letter”

Two nights ago, despite the pounding hail outside and the raucous laughter indoors, we heard a knock at our entrance doors. Stodir raised her pick and Edem grabbed the tree axe, but Lokum waived them off and went to the door herself. There stood a soaking husband and wife, Lokum (called Paddelglow) and Tirist. They had traveled from the northwest, from a place called Portaltone. They saw our constructions outside, and thought to find a shelter for the night. We welcomed them in, gave them dry clothes, and then they told us what they had seen: a long line of dwarf refugees is pouring from the south. They could not say exactly from where, only that they bore the colors of the The Ferocious Galley. It can only mean that our brothers and sisters have been attacked, and that the enemy is close. Adil immediately leashed the war dog to guard the entrance, and bolted the door.

Thus began the next few days of much talking and disagreement. Most of our newest members want to leave and rescue the refugees, fearing for their friends and families they left behind; some of us wish to prepare for war; still others wish to wall off the entrance and burrow deep below where we won’t be found. We have not yet decided what to do.

All this concern and debate has left us completely distracted from the urgent tasks at hand. This morning, we awoke to a flash frost. I feared the worst, ran to the pump to start it myself, but it was too late. The murky pool had frozen overnight. We will have no water for the next 6 months.

frozen_pool

Ice delays plans

Gameplay breakdown

Note: I won’t be creating a separate post for the gameplay breakdown anymore, I’ll just be tacking it onto the bottom of each story part.

Just some more infrastructure building for this round, and nothing too exciting. Stakud was made Manager, but I have not actually used his abilities in that role yet. Got some new areas laid out upstairs and downstairs of the main entrance, and increased the food and drink stores. I do plan to slaughter the kittens, as horrible and as gross as it sounds. Cats will reproduce like crazy if you’re not careful, and can actually slow the game down if there’s too many of them running around. If cats adopt dwarves as pets (you read that correctly), you can’t exterminate them without making the dwarves very sad; so yes, it’s best to kill them young. (OH STOP IT, IT’S JUST A GAME.)

I mainly focused on the cistern and well area, which look very nice, but despite working as fast as I could, I missed my chance to pump the water from the murky pool. I gave the order, but the dwarves were all over the place, and seemed to be ignoring the order. The water turned to ice before my pump operator reached it. Makes for a good story for Rob the author, but it will make things a bit difficult for Rob the gamer. Without access to water, I have to have a large alcohol store or the dwarves will either die of dehydration or will go stark raving mad from thirst. Mad dwarves make other dwarves mad, resulting in the dreaded tantrum spiral (cue ominous music).

The 2 migrants “seeing” the refugees is a bit of creative license because of what I know happened just a little while later when my dwarven liason brought news of world events. (You’ll have to read part 5 to see that, though.) Thanks again to Legends Viewer for providing some context to the situation.

The story continues in part 5.

If you’re enjoying this story, perhaps you might enjoy my original fantasy novel, By the Light of the Moons, available for download on Amazon Kindle.