Bill Morefield My thoughts, discoveries, and occasional rambiings.

March 9, 2016

Roguelike Development with C# – Part 2: A Basic Game Loop

Filed under: c#,gamedev,roguelike — Tags: , , — Bill Morefield @ 10:53 am

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

  1. Initialize
  2. Update
  3. 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.

[code language=”csharp”]
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.

[code language=”csharp”]
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.

[code language=”csharp”]
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

Filed under: c#,gamedev,roguelike — Tags: , , — Bill Morefield @ 11:00 am

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.

December 14, 2014

This is My Forty

Filed under: Uncategorized — Bill Morefield @ 10:25 pm

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.

July 29, 2014

My Article on Preventing XSS in ASP.NET Published

Filed under: article,aspnet,web — Tags: , , , — Bill Morefield @ 9:16 pm

My article on Preventing XSS in ASP.NET is up at NetTuts this week. Follows earlier articles on SQL Injection and Preventing CSRF.

March 31, 2014

Port Forwarding in Windows

Filed under: web — Tags: , , — Bill Morefield @ 8:33 am

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.

netsh interface portproxy add v4tov4 listenport=80 listenaddress 10.0.0.1 connectport=8088 connectaddress=192.168.1.75

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.

March 25, 2014

Article Published on Tuts+ Code

Filed under: Uncategorized — Bill Morefield @ 10:39 pm

My article on Securely Handling User’s Login Credentials is up on Tuts+ Code.

For most websites, you have different areas within it (home page, user profile, admin page, etc.), some of which will be public and others will need to be restricted to only certain users. You often want to uniquely identify users so you can provide customized content or to capture specific information from a user. Many sites also need to protect part of the site, such as an administrative area to maintain and update the content of the site. In a CMS site, some users may be able to create content, but others must approve that content before it is shown to the public.

Read the Rest.

March 21, 2014

Better Weigh in the App Store

Filed under: iPhone,Programming — Tags: , — Bill Morefield @ 8:56 am

So earlier this year I decided to write an app for the iPhone. In my case I wanted to loose a little weight before working to add on some muscle for a planned summer trip. I’d not been particularly happy with anything I found to track my weight before, so I decided to write my own. Thus was born Better Weigh.

 better-weigh-screenshot

The app focuses on helping you track your weight and spot trends such as subtle weight gain before weeks of dieting is required to lose unwanted weight. It works if you’re looking to lose weight, gain weight, or just maintain your weight

Just normal changes from diet, exercise, and other activities can cause your weight to vary by several pounds per day. These daily swings make the real changes over time of your weight hard to track. Better Weigh smoothes out these variations showing you how your weight is really changing and helping you reach your goal.

You can enter your weight manually or sync with FitBit. More syncing options are planned. You can find it on the App Store or see more info at http://betterweigh.me.

January 6, 2014

Goodbye AppStorm

Filed under: article — Tags: — Bill Morefield @ 12:02 pm

Saw today that AppStorm is shutting down. I hate to see that. I admittedly am biased as  I wrote for the Mac and Windows sides of the sites  through late last year. I always felt the site had good reviews and found a number of useful tools and apps through the last few years. More worrying is another quality site goes down as losing money while the “Ten Surprising Ways Your PC Can Hurt Your Cat” sites keep going.

November 29, 2013

Encoding CSR on Exchange 2010

Filed under: web — Tags: , , — Bill Morefield @ 11:46 am

Mostly writing this for my own benefit as I have to do this a couple times a year and always have to look it up. By default if you request a new or renewed certificate signing request on Exchange 2010, it comes out as a binary file that almost no certificate authority accepts. They want a base 64 encoded file instead.

It’s easy to convert the binary file to base 64 though using the certutil utility using the encode option.

certutil -encode C:\renewal.req C:\renewal.csr

This command encodes the binary file renewal.req into a base 64 encoded file renewal.csr that will work with any certificate authority.

October 22, 2013

Fixing a Lightroom Catalog

Filed under: photos — Tags: , — Bill Morefield @ 9:30 am

The biggest risk of any type of database file is corruption. Sometimes you can fix it, but too often the only way to recover from a corrupted file is to restore a backup from before the problem showed up and rebuild or recreate anything lost. For full database servers there are ways to minimize these problems, but for personal catalogs not so much. Major corruption let’s you know, often with a corrupt file message when starting the program. When the corruption is subtle you may not know it until it’s too late to easily recover.

I do a lot of photography and organize my work using Adobe Lightroom. At heart the Lightroom catalog is a specialized database storing information about the photos and the data you’ve attached to them. I found myself seeing an odd error whenever I would take an image into Photoshop for editing, the edited photo would not show in Lightroom as it should. After searching the Internet and talking with Adobe support, I confirmed the catalog was the problem.

I now faced the prospect of either creating a new catalog, importing my photos, and then rebuilding lost data or rolling back to a several month old backup and redoing every import and edit since then. The later might not have been a bad option except I’d done quite a few of both the previous few weeks. Either way I’d have to hope I didn’t miss anything. Neither felt like a particularly good option.

I began to look for ways to possibly pull the data I couldn’t normally save, such as pick/reject flags, from one catalog to another. I knew there was an SDK to create plugins and tools to work with Lightroom and I began to think of something to export everything I cared about into something like an XML or CSV file and then import it again.

I had no luck finding an existing app or plugin to do this, but during my search I learned that the catalog file in fact is a database. It’s a fairly common database format known as SQLite. This led me to the hope that I could extract the data I wanted using database queries. All those years writing web apps looked to be about to pay off in getting my data from the corrupted catalog.

I found two articles on the web at http://gerhardstrasse.wordpress.com/2010/08/19/recover-from-a-corrupt-adobe-lightroom-catalog-file/ and http://www.simplyness.com/more-photography-tips/recover-corrupted-unrepairable-lightroom-3-catalog-with-sqlite.html. Neither of these articles worked perfectly for me, but did get me in the right direction.

Without diving too deep into the technical details, SQL databases are a fairly common database structure and SQL is the language used natively to create and manipulate those databases. The process described involved converting the database into a text file that contains a series of SQL commands that could then be used to create the database.

First I downloaded the command line tool to deal with SQLite databases from https://www.sqlite.org/download.html.  I downloaded and unzipped the shell binary for Mac OS resulting in a program that could be run from the command line to manage a SQLite database. I move the sqlite3 binary to my home folder along with a copy of my catalog file leaving the original safely put away in case this didn’t work. I then used the following to dump out the contents of the database into a text file containing the SQL commands needed to create that database:

echo .dump | ./sqlite3 ~/Lightroom-3-Catalog.lrcat > ~/Lightroom-catalog.sql

The vertical bar (|) breaks this command into two parts. The first part takes the characters .dump and sends it as the input to the second part. The effect is the same as typing those commands after the second part of the line runs. The rest of the command executes the sqlite3 binary I downloaded giving it my catalog file as the database (and yes I’ve been using this catalog since Lightroom 3). The .dump command tells SQLite to display the text commands it would take to create the database. At the end the greater than sign then tells my computer to send that text to a file named Lightroom-catalog.sql instead of displaying them on the screen.

So I now had a huge text file instead of a unreadable catalog file. Some articles I read noted common errors seen in the SQL commands, but my scan of the data found nothing out of order. So now that I had a text file I wanted to create a new database using this command:

cat Lightroom-catalog.sql | ./sqlite3 ~/Lightroom-Catalog-Repaired.lrcat

This command is again split into two parts. The cat command takes the contents of the Lightroom-catalog.sql file we just created and normally sends them to the screen. As before though the vertical bar instead sends them as input to the command that follows the pipe. This command creates a new database with the name. In effect the entire contents of the 600+ MB text file is automatically typed in.

I moved the new catalog file back to my Lightroom folder and opened it. Behold everything was there and all looked good. Only problem I ran into was that when I next imported photos into Lightroom it saw the parent of the folder holding these new files as different than the original folder in spite of being the same. It made no sense to me, but was easily fixed by clicking on each subfolder and using the locate folder to get everything synced up.

It’s been a bit over a month now and all is still working well. Hope that helps anyone else running into this problem.

« Newer PostsOlder Posts »

Powered by WordPress