I moved to a new URL! Check it out!

posts tagged with: programming

Easy CSV Parsing in .Net

Easy CSV Parsing in .Net
Working on getting a public build of my latest game jam game up, and one thing I'm experimenting with is using CSVs for certain types of data. There's a bunch of enemies in the game that all have different stats, and usually I just store this information in the class for each enemy. Storing this data on a CSV has the benefit of being able to see all the data next to each other.

While I could achieve the same thing by having a dictionary set up in the code itself, storing the data in a csv file makes it a little bit easier to view and edit. Tweaks can be made more easily, and storing a bunch of data in dictionaries in code can get a little crazy looking depending on how much data there is to store.

Image


At first I was using OpenOffice Calc for my CSV editing, but there's a huge down side with that: file locking! OpenOffice thinks it's an awesome idea to put any file its editing into a crazy lock down mode, so I can't even read from the file while OpenOffice has it open. So I had to ditch it, and instead I'm using Ron's Editor. So far this is the best free csv editor I can find, even though it's a quite bit more strict about editing than a big spread sheet.

Now for loading the CSV data I'm using CsvHelper which makes parsing a csv as painless as possible. My enemies.csv looks like this:
EnemyType,Supply,Mass,MaxHealth
BasicTest,1,1,10
BigSkeleton,10,0,-1
TestPart,0,0,5

And the code to parse that looks like this:
var csv = new CsvReader(File.OpenText(Assets.Data.Enemies));
while (csv.Read()) {
var record = new Record();

record.EnemyType = Util.GetTypeFromAllAssemblies(csv.GetField<string>("EnemyType"));
record.Supply = csv.GetField<int>("Supply");
record.Mass = csv.GetField<float>("Mass");
record.MaxHealth = csv.GetField<int>("MaxHealth");

Records.Add(record.EnemyType, record);
}

I'm using a tiny class called Record to store the data. Record looks like this:
public class Record {
public Type EnemyType;
public int Supply;
public float Mass;
public int MaxHealth;
}

I end up loading the csv data into a dictionary with the enemy Types as the key, and the Records as the values. When an enemy is created it can look into that dictionary by using its own type and get out a Record object that contains all the data it needs to initialize.
var r = Records[this.GetType()];

AddComponents(
new Team(TeamType.Enemy),
new Heart(r.MaxHealth),
new SpriteEffects()
);
Group = O.GroupGameplay;

if (r.Mass > 0) {
AddComponent(new PushAway(r.Mass, Tag.Enemy));
}

var h = GetComponent<Heart>();

h.OnDeath += () => {
Death();
};
h.OnDamage += (d) => {
};

Pretty straight forward! I think I'm going to extend this to expose more fine tunings of things. It might also be fun to leave the files totally exposed for players to mess around with as well.

Dev Log: Jam Game Stuff

Dev Log: Jam Game Stuff
I've been doing pretty bad on blog posts this month so far, but I've been getting a lot of cool stuff done lately. I've been mostly focusing on my game jam game from a few weeks ago. I want to get that into a good playable state and do some testing at a local indie gathering and hopefully push it out to the public after that. This is another game that I'm making using my 2d .net framework Otter.

During the game jam I started to use the idea of components a lot more. The entity component system is the new hotness in video game programming as it seems many developers are starting to favor it over the old school hierarchy tree of classes. Here's a pretty good write up explaining how it works.

Image


So far all of my games depend very heavily on the whole class hierarchy tree. Like I would have a base Entity, and then maybe a game specific Actor which extends Entity. Then I would have a MovingObject which extends Actor, and then a PlatformerObject which extends MovingObject. Finally the player would be a class (like the momma from Offspring Fling) that extends PlatformerObject. It seemed like a good idea at the time!

Now with this jam game I'm working on I'm trying to use components as much as possible. It may be a little overkill, but I'm using this as a learning opportunity.

Image

For example here's what the Heart component looks like. I use the Heart for everything that can be involved in combat in some way, like anything that can take damage and all that stuff.

There's also something as simple as the RenderAllColliders component, which is handy for just slapping into an Entity if I want to see all of it's colliders during runtime. It will only render colliders on its parent Entity if the game is running in debug mode which is pretty neat.

So what does an Entity look like with all this component stuff? Here's a quick snippet from my main player class:
AddComponent(new CameraTarget());

// Add the movement and pass the axis from the controller.
var movement = new MovementTopdown(7, 0.3f);
movement.AxisMovement = c.Movement;

// Add the weapon, and pass it the shoot button from the controller.
var weapon = AddComponent(new AngelWeapon());
weapon.Button = c.Shoot;

var special = AddComponent(new Components.SpecialAttacks.Shotgun());
special.Button = c.Special;

AddComponent(movement);
AddComponent(new ClampInsideScene());
AddComponent(new SpriteEffects());
AddComponent(new RenderAllColliders());
AddComponent(new PushAway(2, Tag.Angel, Tag.Orb));

Later if I need to I can use GetComponent to retrieve any of those components if I need to change anything on them.

So far I'm really liking this approach, and it seems like it's the way things are heading in the video game programming world as far as I can see. I'm a little concerned with the performance of using a lot of components with GetComponent() running all the time, but it's probably not going to have that much of an effect.

Visual Studio Asset Class Generator

Visual Studio Asset Class Generator
One of the key things I learn from every game jam is what the major knots are in my work flow. The past two jams I did with Otter had a common issue: getting assets from my assets folder to the game was annoying!

I don't like to rely on strings in my code to reference things. A typo can cause a major headache, especially when referencing a path to a file that needs to be loaded. Usually I like to just keep an Assets.cs class that has a bunch of static references to various file paths. Something like this:
class Assets {

static string Asset(string str) {
string assets;
#if DEBUG
assets = "../../Assets/";
#else
assets = "Assets/";
#endif
Console.WriteLine("[ASSET] Register asset {0}.", assets + str);
return assets + str;
}

public static string ImageIcon = Asset("img/icon.png");

public static string ImagePalette = Asset("img/palette.png");
public static string ImageTile = Asset("img/tile.png");
public static string ImageTiles = Asset("img/tiles.png");

// and so on...

This makes it so I can just do something like this later:
public Image Image = new Image(Assets.ImageIcon);

Instead of having to remember that the path to the icon whenever I want to use it, I just keep a reference to it in once spot. This drastically reduces the amount of typos I could possibly hit, and it also makes it easy to bring up with auto complete and intellisense stuff.

However the process of saving out a png, then remembering the exact path to the png, and then opening up Assets.cs and adding lines to it for every new asset every single time becomes a giant pain. The more assets I have, the more complicated this becomes, and the more I'm modifying the assets folder the more annoying it gets! Back when I was using Flash I created an asset generator script to overcome this, so why not just do the same for C#? Wouldn't it be awesome to just be able to click a button in Visual Studio and have an Assets.cs generated from the files in my Assets folder?!

Download AssetClassGenerator.exe (v1.0 Windows 11kb)

This program will execute in the console and build an Assets.cs file based off of the Assets folder in your project directory. This was built with my specific use case in mind so this may not be an exact fit for your needs currently.

Super Sky Sisters Timelapse

Super Sky Sisters Timelapse


Make sure to watch it in full 1080p at 60 frames per second, yeah!

The game isn't out yet, but you can watch me make it at hyper speed over the course of 48 hours. The game ended up getting a bunch of awards at the game jam, including second place overall which is pretty cool!

Index Palette Shader

Index Palette Shader
A few months ago I made and released a game jam game that featured a cool shader based off of Dan Fessler's HD Index Painting tutorial. The idea is to take a normal image and render it with an extremely limited palette. Essentially it's like a game boy shader, and with the help of a dither map texture it actually creates the illusion that there are more colors than there actually are.

Image


The game jam version of the shader was rather clunky, and required the game to manually render a dither texture over the entire screen. Yesterday I spent some time figuring out how to apply the dither directly in the shader itself to make it more general purposed. Here's the entire shader:
#version 130
uniform sampler2D texture; // The main input texture (the screen.)
uniform sampler2D palette; // The palette texture.
uniform float shift; // The shift amount on the palette texture.
uniform float offset; // The offset for the random noise generation.
uniform float screenScale; // The current scale of the screen. (1x, 2x, etc)
uniform vec2 screenSize; // The size of the core game screen (320 x 240)
uniform float noiseAlpha; // The amount of alpha the noise should have.

// A weird way to generate a random number with a vec2 seed.
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

void main() {
// The size of the game window.
vec2 screenSizeScaled = screenScale * screenSize;
// The pixel coordinate being operated on.
vec2 pixpos = gl_TexCoord[0].xy;

// Get dither pixel
vec2 overlayCoord = floor(gl_FragCoord.xy / screenScale);
// Get 1 or 0 based on the pixel location.
float overlayPixelColor = mod(overlayCoord.x + overlayCoord.y, 2);
// Dither is black and white every other pixel.
vec4 overlayPixel = vec4(overlayPixelColor, overlayPixelColor, overlayPixelColor, 1);

// Scale the frag position to match the screen scale
vec2 scaledpos = floor(pixpos * screenSizeScaled);
// Adjust the position based on the scale of the screen.
scaledpos -= mod(scaledpos, screenScale);
// Convert back to 0 - 1 coordinate space.
scaledpos /= screenSizeScaled;

// Get base color.
vec4 pixcol = texture2D(texture, pixpos);

// Mix dither texture.
pixcol = mix(pixcol, overlayPixel, 0.1);

// Determine the brightness of the pixel in a dumb way.
float gray = (pixcol.r + pixcol.g + pixcol.b) / 3;

// Round it to the nearest 0.25.
gray = round(gray / 0.25) * 0.25;

// Add some noise.
gray += (rand(scaledpos + offset) * 2 - 1) * noiseAlpha;

// Map the palette to the pixel based on the brightness and shift.
pixcol = texture2D(palette, vec2(gray, shift));

// Multiply through the gl_Color for final output.
gl_FragColor = pixcol * gl_Color;
}

The shader does require a 2d texture for the palette itself. For this game the palette I used was this:

Image


The "shift" uniform in the shader determines the Y coordinate to sample the palette on. A shift of 0 will sample the top most Y, and a shift of 1 will sample the bottom most. You can use this to dynamically change the palette during the game.

The shader needs to have the "screenScale" uniform set to the current scale of the screen. This will make sure that the pixel size is corrected for the dither and the noise. The shader also needs to know the "screenSize" in order for the noise pixels to be the correct size. You can also just set the "noiseAlpha" to 0 if you don't want any of that stuff to show up.

To make the noise change every update the "offset" value should be set to a random float 0 - 1 every update.

Here's what the game looks like without the shader:

Image


And turning on the shader:

Image


Neat!

Dev Log: Snakes and Skeletons

Dev Log: Snakes and Skeletons
The struggle of building creatures out of skeletons and bones continues this week as I try to finish up a Snake class for Otter! One of my other goals with enemies is to be able to construct enemies out of "snakes" of entities. Basically have a series of pieces all following the next piece like a slithering snake.

Image


I already had the ground work for this laid out last week, but today I dug into it some more so that I could actually have each piece of the snake be an entity with a skeleton. Now I can build crazy enemies and objects out of snakes composed of skeletons all animating! The next step is going to be going back to the game project itself and plugging some of this stuff in, as well as cleaning up the code as much as I can in order to have it be useful for people other than me.