~/home/blogs/generating-cards-with-csharp.md

Generating cards with CSharp!

I'm working on a card game with a co-worker. I made a tool to generate our card images 😎

- Raul G.
2021-01-22

I am working on a card game with a co-worker, we started on this together last year.

Once the game loop was designed we made a list of the cards that would need to exist, as well as their text, names, etc.

We had practically made a spreadsheet. From that, we agreed on a prototype card layout.

I started by opening up GIMP to begin editing a ton of card images together. I got through 2 cards and realized I'd much rather automate this.

Manually updating the cards and creating the printout was too much work for me.. It would also allow human error to introduce inconsistencies and...

it would require Quality Checking.

So, my excuses are: 

  • Inconsistant. If I don't use a style guide or some other pre-defined ruleset, our cards will be inconsistent.
  • Tedious. A lot of the clicking is going to be repetitive and will need to be done every time that we change a card.
  • The Print-Out

My Solution

I wrote a program in C# that takes a path to a CSV file as input.

This is the master spreadsheet and it references other spreadsheets relative to it.

  - images/*.png

  - spreadsheets/*.csv

  - card_data.csv

spreadsheets? ## generating cards

So, using the text, color codes and names in the spreadsheets, I can generate the cards.

I do this for every card of every type and generate a bunch of images.

If you're wondering how what the code looks like, we're using the Graphics class in C#.


Bitmap canvas = new Bitmap(CARD\_WIDTH\_PIXELS, CARD\_HEIGHT\_PIXELS);
Graphics marker = Graphics.FromImage(canvas);

Then, when we need to draw to the canvas, we use the marker object. When you want to save the image, you save the canvas.

So, the Header panel and icon is drawn like this:


Brush panelBrush = new SolidBrush(BACKGROUND\_COLOR);

Rectangle headerPanel = new Rectangle(0, 0, CARD\_WIDTH\_PIXELS, PANEL\_HEIGHT);
marker.FillRectangle(panelBrush, headerPanel);

// Add the Card Type Icon
string iconPath = "<icon path>";
Image cardTypeIcon = Bitmap.FromFile(iconPath);

Rectangle iconPos = new Rectangle(PANEL\_MARGIN\_PIXELS, PANEL\_MARGIN\_PIXELS, PANEL\_MARGIN\_PIXELS*3, PANEL\_MARGIN\_PIXELS*3);
marker.DrawImage(cardTypeIcon, iconPos);

You can find more info on the Graphics and Bitmap classes online.

Put it all together and what do you get? ## The results

Finally, once the code runs and all the cards have been generated, we can add them to the printout as many times as necessary. The code will automatically position the cards so that they are printed and ready to play!

If you guys want me to elaborate any any of it, leave a comment or contact me!

Thanks for reading!

Share this post