No-frills SDL2: Basic graphics

This is part of a series of basic SDL examples, introduced here.

  1. Initialize SDL:


  2. Create window, and bind a renderer to it:

    SDL_Window *window = SDL_CreateWindow("Title", 0, 0, 800, 600, SDL_WINDOW_SHOWN);
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

  3. Load bitmap image, with its magenta background transparent:

    SDL_Surface *imageRaw = SDL_LoadBMP("image.bmp");
    SDL_SetColorKey(imageRaw, SDL_TRUE, 0xff00ff);
    SDL_Texture *image = SDL_CreateTextureFromSurface(renderer, imageRaw);

  4. Draw stuff to the screen:

    // Clear renderer with a blue color
    SDL_SetRenderDrawColor(renderer, 24, 82, 161, 255);

    // Draw yellow rectangle
    SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255);
    SDL_Rect rectangle = {200, 100, 50, 150};
    SDL_RenderFillRect(renderer, &rectangle);

    // Draw image
    SDL_Rect imageRect = {500, 150, 50, 50};
    SDL_RenderCopy(renderer, image, 0, &imageRect);

    // Copy renderer to window

  5. Clean up:


No-frills SDL2 examples

There is quite a bit of information out there about how to use SDL, a C library for basic graphics, sound, user input, timing and OpenGL support. What I couldn’t easily find, however, was a simple demonstration of the various functions and types, and how they fit together. I will be posting a series of examples to fill this void, consisting of bare-bones code examples with brief annotations, to demonstrate how the different elements are used.

Importantly, the code samples will not constitute complete programs, and will exclude error checking and handling.

For details about setting up SDL, and more compete code examples, I recommend the excellent tutorials by Lazyfoo. The best reference available for SDL is probably the SDL Wiki.

Posts in this series:

A barebones MMO

My econ-sim project has been dormant now for about three years, but I’ve had a sudden urge to continue development. I had originally considered using third-party MMO middleware to allow a multiplayer version, where human agents did most of the work and AI took a backseat. The few I looked at didn’t offer all features I wanted, though (such as persistent destruction and construction), and so I abandoned that path. This weekend I started again, from scratch. I learned socket programming, which I had never used before. I learned SDL 2.0, which was easy enough given my familiarity with SDL 1.2. I made some sacrifices—modularity, hardcoding, prettiness, user-friendliness—at the altar of prototyping time, and I am now cleaning them all up. The result was a mininmally functional MMO:

  • The server can connect to and maintain information about multiple clients
  • Client information is identified by raw Winsock SOCKET handles
  • Clients can send ‘move’ requests which are handled by the server, and the new location is sent to all clients
  • Each client can send a message to the server
  • The server can send a message to a single client, or broadcast one to all clients

Server and clients To use:

Available actions

As part of the rationality engine discussed earlier, I’ve put together a list of 12 types of economic actions for my agents to consider as options. For now it seems to cover all of the strange ideas I have for this project, but I’ll be careful to allow room for adding new actions or changing the existing ones. The actions are as follows:

  1. Use an object, for example using a plow to till soil, or mounting a horse.
  2. Attack a person or object, which includes chopping trees for wood.
  3. Use an object with another object, like using a millstone with wheat.
  4. Take an object, picking it up and adding it to inventory.
  5. Place an object, for example dropping excess goods, or paving ground.
  6. Manufacture object(s) from other object(s)
  7. Place a buy order
  8. Buy from a seller
  9. Place a sell order
  10. Sell to a buyer
  11. Place a job order
  12. Take a job order

Recipes and crafting
It is likely that there will be prescribed “recipes” for manufacturing objects, in a similar vein to Minecraft‘s crafting system. This is something which will have to be fiddled with later, but until my focus moves to manufacturing I’ll keep it simple. Ultimately, recipes may require broad categories of items (“metal”, where many metals will work, etc.), and may be discoverable in the world.

Buy/sell orders
It seems that the best way to have agents buy and sell from each other is through a system of buy and sell orders, like one finds in a stock exchange. When one has a good to sell, they can either meet an existing buy order if they’re happy with the price, or list their own sell order and wait for a buyer. When choosing the best order to fill, an agent will have to consider both the order’s price and the distance to the trading agent.

Job orders
“Jobs” will be matched in a similar way to buying and selling: potential employers will “list” a job order (like a buy order for labor), which specifies a goal, a timeframe, and a reward. Agents can look over this list and determine whether one of the jobs listed is worth their time. Working for an employer means that the agent will have access to the employer’s property, which may increase his productivity.

For example, agent A, who owns a millstone, may list a job for somebody to create as much flour as possible within five minutes. Agent B, who takes the job, will be more productive because he has access to a millstone, and meanwhile, agent A has determined that they would rather have those five minutes available to do something else than have whatever reward was promised to the agent B.

Ultimately it might be worth including a system of “employee orders”, like sell orders for labor, which would give employers a choice of desperate candidates.

Making a man chop down a tree: modeling economic rationality

I’ve recently been getting more heavily into my economy sim, creating the foundations for resource gathering and interactive objects. I then came to the next logical functional step: making a man chop down a tree.

In my current, simple testbed, the only resource is wood, and the only objects trees and branches on the ground. However, in order to get an AI-controlled agent to “want” to cut down one of the trees (which we can all agree is a worthwhile use of his time), short of hard-coding this behavior, I’ll need to model something more fundamental, possibly the most fundamental element of a human economy: rationality, for the agents to employ and apply to the world in which they find themselves (Certain human-like irrationalities will of course be useful additions later, but even they will require this foundation).

A preliminary sketch gave me this framework for the parts necessary for rationality to exist, each of which would need to be implemented before rational behavior begins emerging:

  1. A finite goal for the agent, be it finite through a time limit or a goal threshold
  2. Performable actions, with predictable outcomes
  3. Consideration of sequences of actions, including changes in wealth and availability of actions
  4. Response to changes in environment, prices, and possibly other agents, while executing an action sequence
  5. A search of potential action sequences, for the one which will allow the agent to reach his goal earliest (in the case of a goal threshold) or with the best outcome (if a time limit applies)

So, with a goal of “acquire 35g” a possible action sequence might be:

  1. Walk to tree #2
  2. Cut down tree to obtain 4 wood
  3. Walk to person #35
  4. Sell wood for ~40g (based on the current price at that area)

Agents’ goals (1) will be straightforward to add, though room for flexibility must be made, such that new goals can be added later (like having children, or attaining some specific item, or earning a title).

The actions performable (2) will likely be limited to moving, interacting with objects, buying and selling, and later some form of property maintenance. If this is everything, then these actions can be explicitly addressed in code.

Sequences of actions (3) will be somewhat more challenging. The time to complete each action must be estimated. Additionally, a subset of the world state must be maintained for each sequence, changing with each constituent action. For example, if I cut down tree #2, it will no longer be there, and thus if I need yet more wood I won’t be able to cut it down a second time in the sequence.

Responding to real-time changes in the world (4) is important. If the price of wood in an area suddenly drops to virtually zero, then wood may no longer be the optimal path to prosperity, or at least selling wood there would not be. If somebody else cuts down a tree in my action sequence, I’ll have to adjust accordingly. This will likely come down to checking the active sequence regularly, ensuring that it is still applicable, and recalculating if it is found not to be.

Lastly, a search for the optimal sequence (5) could be done as the sequences are constructed and considered; there is a defined “best”, and so the process comes down to a more detailed version of finding the highest value in a tree. If a tree is used, of course, and the entire state space searched, then infinitely-long sequences won’t work; this may mean time limits will be a necessary part of goals, or perhaps the search will simply end after a certain number or total time of actions.

There are simpler ways to make a man chop down a tree, of course; a job-assignment system like in Stronghold or Pharaoh, specialized, single-job units like in Knights and Merchants, centrally assigning roles like some communist dictator… but I feel that independent, rational actors in a model economy will provide the most interesting possibilities, as well as a (hopefully) simple way to expand the scope of a game without reworking unit AI.

The Baker: Status Report

The broken-window game I conceived last month turned out to be a rather literal interpretation of Bastiat’s parable, in which the player controls a bakery in a small village economy, balancing raw materials, production, and the purchase of luxury goods to push back the time limit.

The game, The Baker, contains two lessons:

  1. that one must break windows in order to keep the glazier in-business, and
  2. that the economy survives, and more productively, without certain businesses.

I brought it along to IGDA Sydney’s “Bits & Pieces”, a bi-monthly show-and-tell event. A good number of people played the game that night, most of whom had fun. A few got very competitive about their scores, but for most players it seemed fairly successful as an educational tool. As they played, people had sudden moments of inspiration where they each of the two lessons in-turn. This generally happened when one game had ended and the player began another, considering new strategies to reach a higher score.

The feedback from the Experimental Gameplay Project was also quite good, though from fewer players:

I really felt like there was an economy at work and that each business depended on the others even if not directly. I particularly liked that smashing the window at first appeared to be a waste of money but it has to be done to keep the glazier in business. I really feel like I learned something about the fragility and counter-intuitiveness of economies.

This player learned the first lesson perfectly, but hadn’t yet managed to learn the second. The players who did learn the second lesson did so after multiple plays-through (more so than are necessary to learn the first), and so encouraging replay is crucial to the educational value of this game. I believe that the best way to motivate replay is to embrace the competitiveness that emerged at Bits & Pieces, by adding a high-score list. This was part of the original design, but I didn’t have time to implement it. It seems that it’s a necessity now.

I hope to exhibit The Baker at this year’s iFest. If I offer secret prizes for the highest scores of the day, it should keep people playing to defend their title, and hopefully lead to robust discussion about strategy and the consequences of actions. Ideally, the day will end with a moderately sized group of people newly converted to the idea that destruction is never good for the economy in the long-term.

The Broken-Window Fallacy, in a game?

This month’s Experimental Gameplay Project theme is Economy, and it got me thinking about whether I could apply some of the techniques used in my thesis, to make players aware of Frédéric Bastiat’s Broken-Window Fallacy.

This would probably involve players participating in a simple economy, and then having the option to waste wealth, be it through broken windows, or digging and filling holes, or war. The player must be tempted by the activity, though, under the guise of helping the economy, and subsequently be educated.

Essentially, such a game would require the following:

  1. An initial illusion that spending on X is good for the economy
  2. An illustration that X is, in fact, wasteful
  3. The player to understand this, and its wider application in the real world

Real-time strategy games present rich worlds of choices to the player, and have them choosing how to distribute resources, be it towards production or research or military exploits. The Civilization series of games is particularly effective at this, as production is generally more long-term, and the player becomes personally invested in what is produced. When the time is taken to produce a soldier who is then quickly lost, the player feels that the effort was wasted, whereas it could have been spent on something more productive and permanent.

Most RTS games fail to address the principle as it pertains to domestic economics: while it’s obvious when a worker unit’s efforts are wasted on rebuilding and repairing, the player doesn’t see this as “good for the economy” solely because it gives workers more work to do, keeping them employed. The game thus does an incomplete job (as an educator of this principle), as workers working isn’t seen as an inherently “good” thing. Consequently, it misses point 1 from the list above.

Will Wright suggested that while some things are well-conveyed with a game, others are better-conveyed with a story. Bastiat himself teaches the principle with a parable, stating that while personal experience is the most perfect educator, the development of foresight is a gentler alternative. While a game would put players in the position of experiencing the effects of their decisions in a virtual way, personally, I believe that a story is sufficient to make a person understand this particular idea clearly. It’s hard to say whether a game would be any more effective in this pursuit than Bastiat’s original story, except that it would be a more approachable and interesting medium for a person than a short story in a thick economics textbook, and one more likely to facilitate the idea’s spread… assuming, of course, that such a game could be made.

Games as political weapons

For my thesis, I studied the effects of exposure to model systems on players’ reactions to similar real-world systems, and there appear to be possible links. The strongest links, though, seem to be educational.

Readers of stories by George Orwell or Charles Dickens or Ayn Rand can be powerfully influenced, but not to the same extent as those actually experiencing and interacting with such a world in a close-to-realistic setting. Skyrim drops the player in the middle of a war between nationalists and an occupying force, and forcing the player to consider his views by making him choose a side. Minecraft exposes players to a free reign over resources, and complete self-determination. A similar approach could be used to, say, expose citizens of oppressed countries to the ideas of liberty and democracy, in subtle and potent ways.

Strategy games present simplified models of government and economies, allowing players to explore their systems and draw from them their own conclusions about politics and economics. They teach players about the relationships between economy, military and state. Civilization and Rise of Nations put the player in charge of balancing resources and deciding when to sacrifice for the war effort. I personally plan to extend this idea, and design a game which teaches players about the Broken Window Fallacy with regards to war.

First-person shooter games like Battlefield and Call of Duty, where politics provide only a narrative backdrop to the action, may teach and re-create political scenarios, but probably won’t do much to enlighten players and coax them to a particular ideology. Those games’ players are enthralled by the shooting and violence, appreciating the flavor given by political narrative, but probably not critically analyzing policy and philosophy. The mechanics simply don’t lend themselves to thinking outside the action.

More than anything, games seem to have the power to teach, rather than to directly influence. I personally believe in a marketplace of ideas, and to that end, the spreading and teaching of a variety of ideas is a pretty substantial power that games possess.

Koster and Crying

Something I often hear is of a loose goal of games as a medium: to make the player cry. I’m confident that this has already occurred in many story-heavy, cinematic games. But does this count?

In cinema, directors call upon lighting, music, story and actors to construct a massive wall of sensation. If they want you to cry, or laugh, they can generally do it. This power is also given to game developers when cutscenes and scripted in-game events take place. However, as expressed in an earlier post, this is a form of “cheating”.

In my opinion, for a game to fairly consider itself to achieve any kind of emotion as a game, it ought to do so through the mechanics and natural dynamics of gameplay. If it achieves this through a cutscene, then I believe that it’s more the medium of cinema that is achieving the emotion.

Can the game itself invoke strong emotions in the player? I believe so. Raiding in World of Warcraft manages to create high levels of stress for players, followed by a great spectrum of emotions based on the outcomes of battles: from immense disappointment at coming close but dying at the last second, to slight disappointment at losing a fight which you never expected to win, to minor success at killing something for the twentieth time and receiving loot as a reward, to incredible accomplishment and glory at defeating a powerful enemy for the first time, with a large group of friends who have stood together, training exhaustedly for days or weeks to reach that point. I would be shocked if those extremes had never drawn tears from anybody.

When I killed Ragnaros for the first time, it was emotional, but not because a great evil had been purged from the world of Azeroth; it was because it was a reward for the hard work put in by my friends over the weeks, to get that far. Likewise, when a football team wins a game, they manage to feel emotional without having a demon appear at the end to slay their captain.

While I have no objection to the use of cinematic techniques in video games (they contribute greatly to the player’s experience, and the overall experience is the entire point of all this), I do take issue with games claiming to take a victory for the medium, with an achievement earned outside of gameplay. I want to hear of games making people cry because of anxiety or drama or unfairness or victory, from the dynamics of the game itself.

The Enchanted Forest

Last month my brother and I attended a “Show ‘n’ Build”, the first event of Sydney Uni’s new EGADS group. Feeling bored and adventurous, we decided to collaborate (for the first time in eleven years) on a project in QBASIC (for the first time in eleven years). Within the four hours of the event we managed to relearn the intricacies of subroutines, text placement and drawing, and end up with something more advanced than anything we had managed to make as kids, in our months and years of messing around with the language.

I suspect what it comes down to is a shift in focus from top-down design, to a more “extreme programming” approach emphasizing functionality, which occurred around the end of high school; from starting with menu screens and opening animations, to making sure the guts of the thing are done first.

Note: a camera is necessary to take screenshots from a running QBASIC program

Note that this isn’t a game; it isn’t fun at all. It’s merely a tech demo, and in that capacity demonstrates that QBASIC shouldn’t be used for games, unless such a game is designed specifically to work well in the interpreter.

The code is available at Pastebin.