Recent article of mine published on Best Image Editors for OS X at raywenderlich.com.
March 30, 2016
March 21, 2016
Roguelike Development with C# – Part 4: Windows and Turns
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.
[code language=”csharp”]
_rootConsole.Print(1, 1, $"Current tick: {tick}", RLColor.White);
[/code]
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 tostring.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:
[code language=”csharp”]
RLKeyPress key;
do
{
key = _rootConsole.Keyboard.GetKeyPress();
} while (key == null);
[/code]
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).
[code language=”csharp”]
private static void RootConsole_Update(object sender, UpdateEventArgs e)
{
bool userAction = false;
// Handle keyboard input
RLKeyPress key = _rootConsole.Keyboard.GetKeyPress();
if (key != null)
{
userAction = true;
switch (key.Key)
{
case RLKey.I:
playerY -= 1;
break;
case RLKey.J:
playerX -= 1;
break;
case RLKey.M:
playerY += 1;
break;
case RLKey.K:
playerX += 1;
break;
case RLKey.Q:
_rootConsole.Close();
break;
}
}
// Turn based events only if userAction is true
if (userAction)
{
// Ensure player stays on the screen
if (playerX < 0)
playerX = 0;
if (playerX > screenWidth – 1)
playerX = screenWidth – 1;
if (playerY < 0)
playerY = 0;
if (playerY > screenHeight – 1)
playerY = screenHeight – 1;
turn++;
}
// Real time actions
tick += 1;
}
[/code]
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.
Change the section managing keyboard input to:
[code language=”csharp”]
if (key != null)
{
userAction = true;
switch (key.Key)
{
case RLKey.Up:
playerY -= 1;
break;
case RLKey.Left:
playerX -= 1;
break;
case RLKey.Down:
playerY += 1;
break;
case RLKey.Right:
playerX += 1;
break;
case RLKey.Q:
case RLKey.Escape:
_rootConsole.Close();
break;
}
}
[/code]
That concludes this tutorial. You can download a zip file with the code to this point. Next we’ll start giving our player something to do other than wander in empty space.
March 15, 2016
Roguelike Development with C# – Part 3: Game Loop with RLNET
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.
[code language=”csharp”]
namespace RogueLearnng
{
class Program
{
static void Main(string[] args)
{
}
}
}
[/code]
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.
[code language=”csharp”]
private static RLRootConsole _rootConsole;
private const int screenWidth = 80;
private const int screenHeight = 24;
private static int playerX;
private static int playerY;
[/code]
Two changes here. We’ve removed the quit flag that’s no longer needed with RLNET. We’ve added a RLRootConsole
object that we’ll use to set and render our screen. Now let’s look at the new Main
method.
[code language=”csharp”]
static void Main(string[] args)
{
_rootConsole = new RLRootConsole("ascii_8x8.png", screenWidth, screenHeight, 8, 8, 2f, "Rogue Learning");
_rootConsole.OnLoad += RootConsole_OnLoad;
_rootConsole.Render += RootConsole_Render;
_rootConsole.Update += RootConsole_Update;
_rootConsole.Run();
}
[/code]
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.
Next we’ll implement these handlers starting with OnLoad
:
[code language=”csharp”]
private static void RootConsole_OnLoad(object sender, EventArgs e)
{
playerX = screenWidth / 2;
playerY = screenHeight / 2;
}
[/code]
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.
Our Render
handler also looks familiar:
[code language=”csharp”]
private static void RootConsole_Render(object sender, UpdateEventArgs e)
{
_rootConsole.Clear();
_rootConsole.SetChar(playerX, playerY, ‘@’);
_rootConsole.Draw();
}
[/code]
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.
Last we have the Update
handler.
[code language=”csharp”]
private static void RootConsole_Update(object sender, UpdateEventArgs e)
{
// Handle keyboard input
RLKeyPress key = _rootConsole.Keyboard.GetKeyPress();
if(key != null)
{
switch(key.Key)
{
case RLKey.I:
playerY -= 1;
break;
case RLKey.J:
playerX -= 1;
break;
case RLKey.M:
playerY += 1;
break;
case RLKey.K:
playerX += 1;
break;
case RLKey.Q:
_rootConsole.Close();
break;
}
}
// Ensure player stays on the screen
if (playerX < 0)
playerX = 0;
if (playerX > screenWidth – 1)
playerX = screenWidth – 1;
if (playerY < 0)
playerY = 0;
if (playerY > screenHeight – 1)
playerY = screenHeight – 1;
}
[/code]
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
Roguelike Development with C# – Part 2: A Basic Game Loop
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).
[code language=”csharp”]
private static bool quit = false;
private const int screenWidth = 80;
private const int screenHeight = 24;
private static int playerX;
private static int playerY;
static void Main(string[] args)
{
// Register Ctrl+C handler and hide the cursor
Console.CancelKeyPress += ConsoleOnCancelKeyPress;
Console.CursorVisible = false;
// Initialize Game variables
InitializeGame();
// Enter Game Loop
GameLoop();
}
[/code]
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.
private static void InitializeGame()
{
// Set window size
Console.SetWindowSize(screenWidth, screenHeight);
Console.SetBufferSize(screenWidth, screenHeight);
// Set initial player position to center of screen
playerX = screenWidth/2;
playerY = screenHeight/2;
}
[/code]
The first two lines set the window and buffer size of the Console to match our specified values. We then set the initial player position to the center of the screen.
That handler code by the way just sets the quit
variable to true.
private static void ConsoleOnCancelKeyPress(object sender, ConsoleCancelEventArgs consoleCancelEventArgs)
{
// Set flag that we’ll use to cancel on our own terms
quit = true;
consoleCancelEventArgs.Cancel = true;
}
[/code]
Next comes the heart of the game, our game loop code.
private static void GameLoop()
{
while (!quit)
{
// Sleep a short period at the end of each iteration of the loop
Thread.Sleep(100);
// The Render section
// Clear the console before we draw
Console.Clear();
// Draw the player at the current position in white
Console.SetCursorPosition(playerX, playerY);
Console.ForegroundColor = ConsoleColor.White;
Console.Write(‘@’);
// The Update section
// Wait for a key press and do not display key on the console
ConsoleKeyInfo character = Console.ReadKey(true);
// Handle the player input
switch (character.KeyChar)
{
case ‘i’:
playerY -= 1;
break;
case ‘j’:
playerX -= 1;
break;
case ‘k’:
playerX += 1;
break;
case ‘m’:
playerY += 1;
break;
case ‘q’:
quit = true;
break;
}
// Ensure player is still on the screen
if (playerX < 0)
playerX = 0;
if (playerX > screenWidth – 1)
playerX = screenWidth – 1;
if (playerY < 0)
playerY = 0;
if (playerY > screenHeight – 1)
playerY = screenHeight – 1;
}
}
[/code]
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
Roguelike Development with C# – Part 1: Introduction
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 a number of definitions 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#.
That’s all for this article. Next time we code.