April 1, 2016

First a note that I didn’t get the code for the last couple of articles posted before so that’s been done now. Today’s article will work on setting up some debugging and counter logic that we’ll use going forward. We’re also going to fix a small bug in our handling of turns left in last time.

Last time we created a pair of counters to track how long we’ve been running. The tick variable holds how many times our game has run through the update handler while the turn variable tells us how many times the player has performed an action. We’re going to add three more counters and move these values into a separate class. Create a new file in the program named GameCounters.cs and define it as follows

This creates a class that holds our current Tick and Turn counters. It also adds three new values that hold the date and time we start our game, the date and time of each frame, and the difference in time since the last frame for each frame.

Now we’ll add a few three more calculated properties to this class. Before the constructor add the following three properties.

If this looks unfamiliar, I’m using a new syntax introduced in C# 6. This uses the lamba arrow (=>) to define the body for the expression. The effect is exactly the same as if the methods had had a block body with a single return statement. In other words

Now we need to update our game to use the new class. Replace the two existing counter variables with a single variable of the new GameCounter class.

[code language=”csharp”]private static GameCounters _counters;[/code]

We could initialize the counter class in our OnLoad handler, but I want to keep that to setting the initial game state. Instead we create the instance of the class immediately before starting the loop at the end of the Main method before the _rootConsole.Run(); line.

We also now need to use the new methods whenever a turn or tick passes instead of directly changing the variables. Replace the turn++ call at the end of the loop handling key strokes with _counters.NewTurn();. Replace the increase of the tick counter at the end of the Update handler with a call to the new method so tick += 1; becomes _counters.NewFrame();.

In additon let’s add a new print statement to show the new counters. In the Render handler after the existing print statement add a new one.

If you run the application as it is now, you’ll see that the statements are hidden at first, but will show after you press the D key. Pressing the D key again hides the information.

I also mentioned a bug in our handling of turns. Restart the game and press D. You’ll notice it shows one turn has passed. In fact if you press any key, including unrecognized ones such as F and the turn counter increases. That’s because we’re setting the userAction flag to true any time that we get a keypress.

We only want turns to pass when the player actually performs an action. Interface type activity (such as showing the menu here with the D key) shouldn’t count nor should keys we don’t recognize or act upon. Let’s fix this by only seting the userAction flag to true for keys resulting in the player peforming an action. Change the swtich statement handling keypresses within the Update handler to the following.

Now we only set the flag when the user moves. Quitting or toggling the display of debugging information does not count as an action.

Today we’ll do one more change to move the code that should only execute after a turn and the code that executes every time through the Update handler into separate functions. This will leave the Update handler focused on code to process player input.

[code language=”csharp”]// Turn based events only if userAction is true
if (userAction)
{
ProcessTurn();
}

// Update frame timers and counters
ProcessFrame();[/code]

We’ve done a number of changes in this article. download a zip file with the code to this point. Next time we’ll actually start implementing a real game by adding someone else besides our player to the game.

March 21, 2016

The last article recreated our game loop using RLNET. We’re now going to talk a bit more about some of the design choices of RLNET so we can understand how they’ll affect our design moving forward.

First if you ran the last demo (do so now if you didn’t) you likely noticed there were two windows. Our console containing our player and a second console in the background. As our project is set as a Console Application, this console was created even though we don’t want it and don’t use it. We could get rid of the window by hiding it, but a better option in our case is to never create it. Since we’re not a console app anymore, we change our project to work as a Windows application.

Right click the project in Visual Studio’s Solution Explorer and choose Properties. Under the Application tab change the Output type to Windows Application. Save and run and you’ll see no more unwanted console window.

You’ll also notice the window looks quite a bit different now. Our Console based program had a window that was roughly in the 4×3 ratio common to Console apps. The RLNET window though is very elongated.

This is exaggerated by the use of the 2.0 scaling factor, but most comes from our change to square tiles. Most console fonts have characters that taller than they are wide. Moving to characters that are the same height as their width means that the same size window will now look shorter. For now we’ll leave it, but will come back to the window size later.

Moving to RLNET also made another change to our code that isn’t currently obvious. In our Console verion the program waited for keyboard input and then processed that input. It still appears that’s the case, but a quick test will show this is not how RLNET works. Let’s add a simple counter after our other variables.

[code language=”csharp”]
private static int tick = 0;
[/code]

We’ll add a line to print this counter to our RootConsole_Render method.

Note that I’m using a recent feature of C# known as interpolated strings. If you’re not familiar with this syntax $"Current tick: {tick}" is equivalent to string.Format("Current tick: {0}", tick).

If you run the app you’ll see the tick counter increases even when we don’t press a key. That’s because the keyboard check _rootConsole.Keyboard.GetKeyPress() doesn’t wait until a key is pressed. If checks for a key press, but if no keys was pressed it continues and returns a null.

Our game loop therefore now runs in realtime. This is a change from our original game loop using the Console as the Console.ReadKey(true) command does wait until a key is pressed before continuing. It doesn’t matter here since our game does nothing at the moment, but will become more important when we add other objects to the game, especially those hostile to the player. It would be quite a surprise if the player expects a monster to move only as they do, only for it to charge across the map and attack without the player doing a thing.

That doesn’t mean that this real time aspect is a bad thing. In fact we can make a real-time loop like this operate as a turn based loop. It adds a little work on us as a programmer, but gives us flexibility for the future we can use for animations or other things we might want to occur even when there’s no action by the user.

The simplest way to move toward real time would be to loop until a key is pressed. This way the actions of the game only continue after a player action. The code would look like:

This won’t work. If you make this change and run the game you’ll find your game won’t respond to any keypress. What we will do instead is a more flexible approach that divides our update handler into real time and turn based components. Let’s add a second counter to track this. After the tick counter we added, add another counter.

[code language=”csharp”]
private static int turn = 0;
[/code]

and change the print statement we added earlier to also show this new counter.
[code language=”csharp”]
_rootConsole.Print(1, 1, $"Current tick: {tick} Current turn: {turn}", RLColor.White);
[/code]

Next we’ll change our Update handler to deal with the mix of events that occur every time we go through the loop (ticks) and events that we’ll process only after the player makes an action (turns).

Now running the app you’ll see the tick counter increases in real time. Our turn counter only increases when we move our character. As I originally noted, my design for this game will be turn based, that’s a purely a game design choice. Having a creature charging at the player doing nothing can be normal and expected in many games.

One last change to make today. We chose the i,j,k, and m keys out of tradition, but I think most players would be expecting the arrow keys to move the player. So let’s make a change that uses those keys for movement instead, and we’ll also let the escape key end our game.

The i, j, k, and m key arrangement dates back to the popular Unix vi editor. It therefore became rather common in software written for Unix to use these keys for cursor movement. This included Rogue and Nethack.

March 15, 2016

At the end of the previous part we’d implemented a basic game loop using the Console for input and display. It works pretty well now, but the C# interface to the console is lacking at best. Pretty soon we’ll run into those limitations so we’re going to move to something else before going any further. We’re going to stick with a text based game, we can do that while leaving ourselves flexibility going forward that will make a graphical also possible.

C# libraries related to Roguelikes are a bit scarce compared to some other languages, but there are a several that will work for our needs. In place of using the Windows console I’m going to use RLNET. RLNET provides an API for creating tile based games under .NET that will handle our console output. I also handles our keyboard and mouse input.

Using an external library does add a dependency to our project. That’s a risk worth taking for a learning process like this as this library will save time we can devote to the other aspects of a game. Given that RLNET is open source, meaning we have access to the source code in case of bugs or needed changes, it feels like a safe risk.

Let’s walk through building the same functionality that we had at the end of the last article using RLNET. Begin in Visual Studio by selecting File -> New Project... from the menu. Under Templates choose Visual C# and expand Windows Desktop and choose Classic Desktop -> Empty Project and give it the name RogueLearning.

Since we have an empty project, we need to add in the Program.cs class that we’d have created for us using the Console Application. Right click on the project and select Add -> Class. Name the class Program.cs and change it to match the following code. This will create a main method that will be called when our application begins.

We next will add RLNET to our project using the NuGet Package Manager. Right click on the project and select Manage Nuget Packages.... Choose the Browse tab and search for RLNET and click Install. This will add RLNET and its dependency OpenTK to your project. At this time the current version of RLNET is 1.0.6.

While we’re keeping our game text based for simplicity, RLNET actually is tile based. It uses a special image called a Font File to define these tiles. The Font File is a rectangular image containing all the tiles in this one image. These tiles must all be the same size, but there is no requirement that they contain text. They could as easily be made of images that we’d use instead. The format is that used by the popular C language Roguelike library libtcod and you can read more about these files on the libtcod documentation site.

The RLNET download comes with a simple text font file ascii_8x8.png, but the NuGet package does not install it so I’m providing a copy here. Download the file and drag it onto your project in Solution Explorer to add it to your program. In the properties for this file, change the Copy to Output Directory option to Copy if newer. Skip this step, and you’ll get an error when you try to run the app that the bitmap cannot be found.

Viewing the file you can see that it is a 128 x 128 pixel image that contains 256 8 x 8 pixels tiles arranged in 16 rows and 16 columns. These tiles correspond pretty closely to the original IBM CGA character set and is popular for text based games like this.

With the library loaded and a font file added to our project, we can being implementing our game loop. First at the top of the Program.cs file we’ll add a reference to the RLNET namespace so we don’t need to prefix it to every method.

[code language=”csharp”]
using RLNET;
[/code]

As in the previous entry, we’ll begin by adding the global variables that will contain our game state to the top of the class before the Main method definition.

The first line creates our console object that we’ll be using for display and to read player input. There seven parameters here, and each is important so let’s go through them in detail.

The first parameter “ascii_8x8.png” chooses the font file described earlier. The next two parameters, screenWidth and screenHeight, define the width and height of the console for our game. We’re using the constants declared a moment ago.

The next two parameters relate back to the font file and tell RLNET the size of each tile in pixels. For the ascii_8x8.png file each tile is 8 pixels wide by 8 pixels tall. We next provide a scale factor. This is a float value that zooms the screen by that factor. We’re using 2 here. This will make the display appear more pixelated, but shows up a bit better using these small tiles for screenshots. The last parameter lets us specify the name to appear on the window.

The next three lines set the handlers for the three events that we’ll deal with as our game loop. The first OnLoad event runs when we begin the game loop. The Render handler takes care of the display of the game state to the player. The Update handler allows us to read user input and update the state of the game.

This performs the step of setting the player’s initial position as we did in the InitializeGame method of the last article. Note that since we defined the size of the console on creation, we do not need to do that here.

We first clear the console so we have an empty display to begin. We then set the @ character at the player’s current position. Last we draw the current console to the window.

What we’re doing when setting the @ character is a little more complicated than it sounds. We aren’t displaying text directly as we were in the Console based version. We’re telling RLNET to display a tile at the player’s position. That tile is the integer value of the @ character, which is 64. Tile 64 of the loaded font file is a graphic that looks like the @ character. If you didn’t follow that, don’t worry about it for now. With our current font file the distinction isn’t important as characters and tiles match. We’ll go in more depth when needed.

Again the code should look familiar. We now use the RLNET library to get our keyboard press, but otherwise we check for the i,j,k, or m keys as before and update the position as we did before. We also handle the quit method here by using the Close method on the console to end the game. After dealing with player input, we ensure the player isn’t trying to wander off the screen and correct if needed.

At this point we have recreated the previous demo using RLNET. This tutorial has already run a bit long, so we’ll stop there for this article and you can download the code to this point. Next time we’ll delve a bit more into the Update handler and discuss some subtle changes the move to RLNET brought.

March 9, 2016

To begin the game, we’ll start with a game loop. Every game works through the same basic three steps.

Initialize

Update

Draw

In step one, the program sets up the inital state of the game. The game then repeats steps two and three until the game ends. To start with I’m going to build a simple Command Line project using the built in Console class in C#.

For the initial pass we’ll keep things simple. Our goal is to create a player character that can be moved around the screen with the keyboard. We’ll use the i, j, k, and m keys as in the classic Nethack to move. We’ll also use the @ character for our player, again as in Nethack (and most other text Roguelikes).

We begin by defining five variables. The first stores a flag we can set to quit the game. We also store the size of the game screen along with the player’s current position.

A C# console app begins executing our Main method here. First I add a handler function that will be called when Ctrl+C is pressed. Next we hides the cursor and then call InitializeGame() to set up he initial state of our game by setting the variables above.

The method begins with a while loop hat loops until the quit variable we defined earlier is true. Each pass through the loop begins with a short pause of 100ms. Given how little we’re doing at this stage of the loop, this pause keeps the pacing of our movement more controllable.

In this first pass I swapped the order of the render and update sections of the loop from above. They should occur be in the opposite order, but we’ll go with the code as written for now. These two sections repeat until we quit the game (or close the app).

The render section displays the current state of the game world and displays it to the player. Our loop begins by clearing the console giving a blank screen to draw on. Next the code prints the ‘@’ character, the player, in white at the player’s current position as specified by those variables we defined earlier.

The render section completed, the code continues to the update portion. Update handles user input and updates the game state to reflect that input.

We’re using a turn based approach and not real time. The Console.ReadKey method waits on a keypress before continuing. After the keypress, we interpret pressing the i,j,k, or m key as a request to move up, left, right, and down respectively and update the player’s position to match. We also respond to the q key by setting that quit flag to true which will end end the while loop the next time through, and thus end the game. Other keys are ignored.

After movement is processed, we check the player’s position and if the player has moved off the screen, then we shift the player back to the edge of the screen. If we didn’t do this then our game would crash with an exception when we attempted to print our character outside the defined screen. In a “real” game this check would better be done before responding to the move request.

You can download a full sample project for this simple game. Running the code as is gives us what we’d set out to accomplish. The player can move around the screen until pressing q or Ctrl-c to quit. It’s not much of a game, it’s barely even a demo, but it does give you a framework and start to build on. This basic process of update and render lies at the heart of any game.

March 6, 2016

Welcome to the first in an indefinite series of article covering my experiments creating Roguelike games using C#. I developed a renewed interest in the genre a couple years ago when I rediscovered Nethack, one of the many descendants of Rogue which gives its name to the genre of Roguelikes.

Defining a Roguelike is a bit difficult, especially as the term has come to be popular in the independent and small studio game space. There are anumberofdefinitions proposed for Roguelikes, but .

To start I’m looking at exploring the traditional roguelike structure. The basic game here will be a single player RPG where the player controls a single character. We’ll stick with the traditional dungeon crawl setting using procedural world generation along with random distribution of creatures, items, etc. The game will be turn based, allowing the player time to consider each decision. We’ll also set the game with permadeath.

This last feature means that the player’s character dies, then the game is over. No checkpoint to start back from, no loading last save and trying again. Spend hours playing and then do something stupid and die? Too bad. It’s a harsh feature compared to many games where you can quickly save before doing almost anything.

The goal here isn’t to recreate Nethack or even necessarily produce a high quality game. I plan to write a playable and hopefully enjoyable game, but my primary goal is to learn. It’s been a while since I’ve done any type of game programming and I think this could be a fun project. I though it would be an intersting experience to document the process here and in the process also create a tutorial on build a Roguelike game in C#.

So a few decisions on what I’ll be creating. The game and tutorial will be written for Windows using C#. Most of the original Roguelike games used console graphics and I’ll do the same in this tutorial to keep things a little simpler. I’m also intentionally being a bit vague on when the program and tutorial are complete. I want to explore and try things by starting small and simple and building the program from there. I may restart any time and begin with the knowledge I’ve learned so far.

I’ll be writing this using a somewhat “warts and all” approach. I plan to document each step, misstep, and mistake. Each article will come with source code of the program implemented to that point and possibly the occasional side experiment. The code along with all displayed in the articles can be used for educational and research purposes. Feel free to use the overall code as a starting point for your own work. Please don’t simply take the code, change some words, and publish it as your own.

I’ll be using Visual Studio 2015 for development to take advantage of the newest features in C#. A few years ago I did some initial work against the console directly, but found C# support for the console too limited for what I’ll need going forward. Instead we’ll use a Console library for C#.

December 14, 2014

I’m writing this entry late in the evening of my fortieth birthday. Tonight I sit here taking a few quiet moments to let myself recharge after a number of very social days. The importance of a single birthday because it’s a round number like forty can be debated, but I’ve been asked a few times my thoughts on this birthday the last few weeks so I thought a moment to reflect wouldn’t be out of line.

Having a birthday less than two weeks before Christmas means that I’m used to it being a busy time. There is the normal activity as the days count down to the holiday season and the end of the year. Having worked in higher education for the last thirteen years it’s also a time that marks the end of a semester, student exams, and graduation ceremonies at work.

Even with those factors, I’ve been busy lately. Earlier this year had challenging times, but as summer turned to autumn I’ve found myself both fairly busy an mostly happy. I don’t think those are unrelated. I’ve opened myself back up more socially after closing off for a while. Meeting people without expectations has left me busy, at time even hectic, but enjoying life as it comes by.

As I reach forty I find myself happy. Not all of my life is perfect, but is life ever? It is pretty good. I’m in the best health I’ve been since I was a teenager and the best shape of my life. When I look forward it’s with optimism and the feeling that my best years are coming more than they have passed me by. And that is truly I think all I could ask for any day.

March 31, 2014

I always enjoy finding something new that meets a need. As you might guess from the title, I found myself recently needing to forward a port on a Windows server. The scenario is that I had a server I need to allow access to from an network that hadn’t been originally planned to do so. I could have just opened a firewall port, but I prefer to set up a more secured method.

For web connections this can be done using a reverse proxy pretty easily and Windows 2012 server even includes a wizard to make this easier to set up. In this case I needed to forward an arbitrary port to the same port on another server.

It turns out this functionality is built into Windows and has been since at least 2008 and the command to do so is pretty simple.

This binds port 80 on address 10.0.0.1 on the local server and forwards any traffic received on this port to port 8088 at address 192.168.1.75. The response is also returned back through the proxy to the source server. It works quite nicely in early testing and fills a need I’ve always had trouble finding a good, reliable solution for on Windows. There are only a few limitations I’ve found so far. From my reading it seems to require IPv6 to be installed to work even if you’re not doing an IPv6 connection. It also cannot bind the localhost addresses which limits use in development scenarios. Documentation on the command is at http://technet.microsoft.com/en-us/library/cc731068%28v=ws.10%29.aspx.

As implied by the v4tov4 portion of the command, you can use this to set up proxies between IPv4 and IPv6 servers. That should come in handy when migration to the new IP version comes over the next few years.