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.