Progress on StarSuckers

May 13th, 2012

 

starsuckerstitle_new_small600

As you can see above: the splash screen for Starsuckers has been updated using Flavio Takemoto’s “Shine Energy 5” image from SXC – thanks Flavio! Smile

We’re currently in the process of going through the Microsoft “Evil List”, and making sure our game lives up to the checklist before we send it for approval. If any of you are going to create a game for XBOX, there’s also a best practices list you should adhere to, and these two may be of interest as well:

http://forums.create.msdn.com/forums/t/17830.aspx
http://create.msdn.com/en-US/resources/help/peer_review_language_faq

GameThumbnail The Game Thumbnail is currently this logo here (left) – we may change it so the splashscreen and game thumbnail are more in sync graphically – but we’re not graphics artists, so we’ll see about that Winking smile

We’re defining what will be left out of the trial version. We’re considering, the single player mode (with AI), the multishots and the ability to aim yourself instead of the Starsucker firing for you, to be extra for the full version.

More updates as we progress!

StarSuckers – our IndieJam 2012 entry

April 26th, 2012

 

In the beginning of April we participated in the cozy IndieJam in Aalborg, Denmark.
The theme was “Out of this world”, and our little two-man-team got a split-screen two-person-spaceshooter up and running before the time of judgement, sunday morning Smile.

StarSuckers_screen-1024x574

We were ONE measly vote from winning the indie Smile. So we have decided to publish the game on the XBOX 360 Indie channel. We’re devoting one day a week to the project, so before the summer is over, you will probably be able to play it.

If you’ve got XBOX 360 controllers with a USB adapter – you can download the playable version (XNA 4.0) and beat a friend (or enemy) of yours at home Winking smile … or maybe get the code.

Created by yours truly and Jesper Niedermann.

Manipulating doublearrays – an extension method

March 22nd, 2012

arraymanipulations

I’ve been fiddling around with returning JSON from an Asp.net MVC solution and getting it in Jquery using the $.getJSON method. Unfortunately – when the default JSON serializer in .net serializes my doublearrays it takes the values of the first column first, then the next column, etc. I would like it to serialize it as one row, then the next, etc.

I am aware that this is default behavior and that I could just populate the doublearray with rows as columns and vice versa, but I find it more intuitive to be able to refer to the first indexer in an array as x and the second as y, like this:

byte[,] data = new byte[3,3];
int x = 2;
int y = 1;
data[x,y] = 1;

Therefore I created a little extension method for manipulating doublearrays. You may find it helpful if you need to rotate an array, or swap values vertically or horizontally.

You can perform multiple operations by chaining the manipulations.

This is how you use it:

byte[,] data = new byte[3,3];
byte[,] manipulatedData =data.GetManipulatedCopy(ArrayManipulation.RotateClockwise);

Download Vs2010 project

Download Class file

Here is the complete class:

using System;

// Class with extensionmethods to manipulate doublearrays with
// Jakob Krarup (www.xnafan.net)
// Use, alter and redistribute this code freely,
// but please leave this comment

namespace ArrayManipulation
{

    /// <summary>
    /// Defines how to manipulate an array
    /// </summary>
    public enum ArrayManipulation
    {
        /// <summary>
        /// Moves all values around the array clockwise
        /// </summary>
        RotateClockwise,

        /// <summary>
        /// Moves all values around the array counterclockwise
        /// </summary>
        RotateCounterClockwise,

        /// <summary>
        /// Swaps all values from the top to bottom and vice-versa
        /// </summary>
        FlipTopToBottom,

        /// <summary>
        /// Swaps all values from left to right and vice-versa
        /// </summary>
        FlipRightToLeft
    }

    public static class ArrayExtensions
    {

        /// <summary>
        /// Implements easy doublearray manipulations
        /// </summary>
        /// <typeparam name="T">The type of the values in the array</typeparam>
        /// <param name="matrix">The doublearray</param>
        /// <param name="manipulation">How to manipulate the array</param>
        /// <returns>A copy of the array with the values as ordered</returns>
        public static T[,] GetManipulatedCopy<T>(this T[,] matrix, ArrayManipulation manipulation)
        {
            int width = matrix.GetLength(0);
            int height = matrix.GetLength(1);
            T[,] ret = null;
            switch (manipulation)
            {
                //if we are rotating the matrix,
                //we need to swap width and height sizes
                case ArrayManipulation.RotateClockwise:
                case ArrayManipulation.RotateCounterClockwise:
                    ret = new T[height, width];
                    break;

                //otherwise we create an array with the same size
                case ArrayManipulation.FlipTopToBottom:
                case ArrayManipulation.FlipRightToLeft:
                    ret = new T[width, height];
                    break;
                default:
                    throw new ArgumentOutOfRangeException("Invalid manipulation : " + manipulation);
            }

            //for all values in the source matrix...
            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    //copy the values to the new array
                    //choosing position depending on the wanted manipulation
                    switch (manipulation)
                    {
                        case ArrayManipulation.RotateCounterClockwise:
                            ret[y, width - x - 1] = matrix[x, y];
                            break;
                        case ArrayManipulation.RotateClockwise:
                            ret[height - y - 1, x] = matrix[x, y];
                            break;
                        case ArrayManipulation.FlipTopToBottom:
                            ret[x, height - 1 - y] = matrix[x, y];
                            break;
                        case ArrayManipulation.FlipRightToLeft:
                            ret[width - 1 - x, y] = matrix[x, y];
                            break;
                    }
                }
            }

            //return the new array
            return ret;
        }
    }
}

Searchwords for Google: extensionmethod, rotate double arrays, manipulate two-dimensional, twodimensional arrays, non-jagged

Maze creation in C#

March 17th, 2012

maze_19x19

A small maze generator for use in .net.

I am currently in the process of learning how to code 3D graphics in XNA 4.0.  It’s a lot of fun – and I’ve gotten pretty far with just boxes covered by different textures. However I thought that it would be fun to have a small mazegame – where you’re running around as a bewildered labrat inside the maze. For that I would need to have a random maze generated each time.
So I Googled around, found some tips, and coded a mazegenerator.

After that I took the time to comment the code  and wrap it up. So if you don’t care about the inner workings, you can just add a reference to my DLL and get mazes like this:

//get a MazeCreator ready to make 9x9 mazes that start at 1,1
MazeCreator creator = new MazeCreator(9, 9, new Point(1, 1));
byte[,] maze1 = creator.CreateMaze();
byte[,] maze2 = creator.CreateMaze();
byte[,] maze3 = creator.CreateMaze();

Basics of maze creation

The basic algorithm of creating a maze is as follows (pseudocode)

Start at a valid starting point in the maze - then:
as long as there are still tiles to try
{
  excavate the square we are on
  get all valid neighbors for the curent tile
  if there are any interesting looking neighbors to branch off to(*)
  {
    remember the current tile, by putting it in a list of potential branch-offs (stack)
    move on to a random of the neighboring tiles
  }
  else
  {
    we are at a dead-end
    toss this tile out, thereby returning to the previous tile in the stack
  }
}
(*) and they are valid for whatever rules you have for your maze

(Longer writeup here: http://en.wikipedia.org/wiki/Maze_generation_algorithm)

Take a look at the animated gifs on this page, and try to follow along with the steps. I have chosen to use complete tiles for walls, but you could as well have neighboring tiles with a thin wall between in your own implementation.

The MazeCreator also has a MazeChanged event that signals every time a new tile has been excavated. This makes it easy to monitor the progress, either by inspecting the Maze property (byte[,]) or by calling the maze’s ToString representation:

The ToString() representation of the maze

 

The animated gif above was created by using gOODiDEA’s NGif component – here you can see that I subscribe to the event MazeChanged and add a new Bitmap to the AnimatedGifEncoder for every new tile excavated in the maze:

//create mazes
for (int size = 11; size < 22; size+=2)
{
//make a new mazecreator
MazeCreator creator = new MazeCreator(size, size, new Point(1,1));

//figure out a savepath with a logical name
string gifPath = string.Format("c:\\maze_{0:00}x{0:00}.gif", size);

//output status to console
Console.WriteLine("Creating " + gifPath);

//subscribe to the mazechanged event
//to get a fresh bitmap on every new tile excavated
creator.MazeChanged += new EventHandler<PointEventArgs>(CreatorMazeChanged);

//create the animated GIF
//make a new encoder
AnimatedGifEncoder enc = new AnimatedGifEncoder();
enc.SetDelay(100);  //in milliseconds
enc.SetRepeat(0);   //yes - repeat (-1 is NO)
enc.SetQuality(25); //for generating palette - this is pretty good ;-)
enc.Start(gifPath); //where to save the maze
var maze = creator.CreateMaze();    //create a maze
enc.Finish();       //save the GIF
}

Class diagram and code

Here you can download the project which displays how to use the MazeGenerator, and see the public members of the MazeCreator. If you only want random mazes and don’t care for anything else, just grab the zipped DLL.

 Code with sample project
 Just the DLL
 Just the MazeCreator.cs (right-click and choose “Save as…” to save)

image

More sample mazes  Smiley

11 x 11 maze_11x11           13 x 13 maze_13x13          15 x 15 maze_15x15

image

musicForProgramming()

February 7th, 2012

Came across this website which has an interesting idea:

“What if we made music designed to occupy the part of your mind that distracts you from real work, thereby leaving you free to work more focused?”

That’s the simple concept behind musicForProgramming()

image

In their own words:

“Through years of trial and error - skipping around internet radio stations, playing our entire music collections on shuffle, or just hammering single albums on repeat, we have found that the most effective music to aid prolonged periods of intense concentration tends to have a mixture of the following qualities:

Drones
Noise
Fuzz
Field recordings
Vague memories (Hypnagogia)
Textures without rhythm
Minor complex chords
Early music (Baroque, lute, harpsichord)
Very few drums or vocals
Synth arpeggios
Awesome
Walls of reverb

Music possessing these qualities can often provide just the right amount of interest to occupy the parts of your brain that would otherwise be left free to wander and lead to distraction during your work.”

It’s dreamy, newagey-, easy listening and free Smile.

Note: of course, if you’re not a programmer – it can be used for a lot of other pastimes as well Winking smile.

Moving a WordPress blog – some tips…

January 31st, 2012

Moving dayI just moved the blog to a new webhost today. From Servage.net to UnoEuro.dk.
It took me quite a while to figure out the steps, as I haven’t worked with PHP/WordPress configuration files before. In case you want the bulletpoints, for moving your own blog, here they are:

You’ll need two things from the webhost you’re leaving:

- The complete contents of the FTP site (or minimum the wp-content folder)
- An export of the database (*.SQL)

Files
I took a copy of everything in the web-root of the host I was leaving, cleared the contents of the host I was moving to (after backing it up, just in case ;-) ), and then uploaded everything to the new host.
Database
Servage had a webinterface where I could export the existing blog’s database as a *.SQL file, which I did.

After that I logged on to the phpMyAdmin website of UnoEuro and chose the SQL file for upload.

After that I figured that everything would be well – but alas I got the following message:

“Error establishing a database connection”

After Googling a bit I found out that the database settings are stored in the wp-config.php file. I figured out that since I had overwritten this with the Servage settings, the blog had a hard time connecting :) .
So I deleted everything in the root folder of the FTP site again, and restored the backup I had, so the empty blog was in place. Then I deleted the wp-content folder, and uploaded mine. Among other things this folder has the plugins folder (where the syntax highlighter resides among others) and the themes folder where my custom theme is. So this folder is important for both the presentation and the functionality of the blog ;-) .

Finding the right tables

After a bit of checking around in the config file, I noticed a variable called $table_prefix with the value drupalwp_.

/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'aiwp_';

I had noticed in the phpMyAdmin that there were quite a few tables beginning with this name. Why the 'Drupal' I shall never know, but it got me worried that I had chosen some wrong settings when setting up the blog using the 1-click interface at UnoEuro ;-) . Then I noticed that there were two sets of identical tables: one set prefixed with aiwp_ and one set prefixed with drupalwp_. Then it dawned on me: The old webhost had a prefix of aiwp_. And after configuring the $table_prefix value I suddenly had a site which worked !  … almost :) .

Where’s the last half of each post?

To my great horror I noticed that a lot of my posts only contained the first sentence. The rest was missing. And also – the layout was skewed … a lot. After digging throught the aiwp_posts, where the blogposts are, and looking at the backup.sql file I could see that right where the sentences had been snipped – were some linebreak tags:  \r\n. After thinking for a while I figured out that the encoding of the SQL file may have had something to do with it. So after editing the SQL file in UltraEdit, and saving as UTF-8, deleting all tables in the database and importing the SQL file again – voilá. The blog was functional :) .
Here is the SQL of my first blogpost, with the \r\n as you can see:

 INSERT INTO `aiwp_posts` VALUES (7,1,'2009-10-23 07:30:52','2009-10-23 06:30:52','Hi everybody. Well I finally took the dive into the binary fray of the Blog-O-sphere and here it is. A blog about my passion \"Gamedevelopment\".\r\n\r\nIn the times to come I will be creating a site with tutorials meant for beginners to get up-and-running, while posting API ideas,tools, etc. of my own creation.\r\n\r\nLooking very much forward to getting started, sharing and reading your feedback.\r\n\r\n- Jakob \"XnaFan\" Lund Krarup','Off to a running start... :) ',0,' A blog about my passion \"Gamedevelopment\".','publish','open','open','','off-to-a-running-start','','','2009-10-23 07:30:52','2009-10-23 06:30:52','',0,'http://xnafan.net/?p=7',0,'post','',2);</p> 

Cleanup

I had a bit of cleanup, with some folders containing downloads. Since I am a unix newbie, I didn’t know that there is a difference in casing on *nix systems. So when I started using WordPress I had inadvertently  created a Downloads and a downloads folder which made it easy for me to make a mistake in uploading and linking to files. This was easy to fix, since all my blogposts were in the aiwp_posts table so I could use the REPLACE command in the phpMyAdmin to streamline.

UPDATE aiwp_posts
SET post_content = (REPLACE(post_content, ‘Downloads/’, ‘downloads/’));

After copying the files from Download into download,  I only have one download folder which is less frustrating ;-) .

Hope some of you other WordPressers can use the info.

Android and Arduino combination kit – yay!

May 11th, 2011

Google has released news of the Android Open Accessory Kit which will enable users to interact with external sensors and outputs from an Android phone using a development board based on the Arduino Mega2560.  The kit will be priced around $400 but it will be possible to work with a much cheaper Arduino Host Shield and a standard Arduino.

It would be neat if a phone came out which had a row of programmable ports ready like the Arduino :) . You could get instant texting support for turning on light/heat/etc. at home. Or the other way around - you would be able to have the phone monitor and report from any kind of sensor.

More at the Arduino website and the MakeZine website.

TönnenKlapps – not entirely unlike a virtual piñata beating game for XBOX controllers

March 17th, 2011

TonnenKlapps_Title_500

A couple of weeks ago some friends and I competed in the very cozy Indie9000 game jam in Aalborg, Denmark. The theme was Fastelavn, a celebration where danish kids beat innocent barrels to pieces with sticks.

We figured it would be fun to make a virtual edition of this custom – so we did! :)

In this version up to four players use an Xbox controller and try to beat the colored staves in the barrel using the button on the controller in the corresponding color. The timing must be right too, as the bat can only hit a single position.

ingame_2

Highlights of the code are:

- dynamic detection of new controllers added and existing ones removed
- simple emulation of a spinning 3D barrel by drawing single staves back to front using individual colors

Here you can see the 36 different transparent PNGs used to simulate rotation:

rotating_barrel_160 

Here you see Lars trying to get a feel for where the bat would hit the barrel while learning 3D modelling:

Lars

Here you see the team (myself excluded) and a group of playtesters:

playtesting

It was fun to make, and we were nominated in Best game, Best graphics and Best sound – yay!

The game is published to Codeplex on http://tonnenklapps.codeplex.com/, so head there for sourcecode and a game of barrelwhooppin’ TönnenKlapps! :)

Empty folder deleter – cleanup tool

December 28th, 2010

Since I often download pdfs, sourcecode and other files from the web, I often end up with my downloads folder being cluttered with full and empty folders between each other.

emptyfolderdeleter_screenshot

For that reason I made a little commandline tool to delete empty folders. I have it in my downloads folder, so I can doubleclick it whenever I’ve been sorting stuff, and want the empty folders deleted. To be sure that you meant to run the program it asks you to press D(elete) on the keyboard to continue. You can run it from a batch file with the parameter "-quiet" to make it run without confirmation.
You can download the application CommandPrompt (zip), or the source code floppy .

An interesting code snippet is the Options class. Earlier I've been using Plossum, but I didn't want to include referenced DLLs in my app, so I made the Options class as an alternative. It is a class which parses the command line and stores the options in public properties, so the logic in the command line version could easily be changed to accept input from for example an xml file. The main logic is in the constructor which receives the string[] sent from the Main() method of the program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace EmptyFolderDeleter
{

// ****************************************************************
// Jakob Krarup - December 2010
// http://www.xnafan.net
// Distributed under Creative Commons Attribution license:
// http://creativecommons.org/licenses/by/3.0/
// Short version: use it how you wish, just leave my name on it :)
// ****************************************************************

/// <summary>
/// Class to parse commandline options for the EmptyFolderDeleter program
/// </summary>
public class Options
{

#region Properties

/// <summary>
/// The folder to delete files in
/// </summary>
public string Folder { get; set; }

/// <summary>
/// Whether to refrain from writing status to the console
/// </summary>
public bool Quiet { get; set; }

/// <summary>
/// Whether to display the program help for the user
/// </summary>
public bool Help { get; set; }

/// <summary>
/// Whether there was an error parsing the arguments in the constructor
/// </summary>
public bool ParseError { get; set; }

/// <summary>
/// What the error was, when parsing the arguments in the constructor
/// </summary>
public string ParseErrorMessage { get; set; }

#endregion

/// <summary>
/// Parses the commandline arguments and saves them in an Options object
/// </summary>
/// <param name="args">A string[] containing the arguments</param>
/// <returns>An Options object containing the parsed values</returns>
public Options(string[] args)
{
if (args.Length == 0)
{
return;
}
else
{
//convert the argument array to list to be able to use LINQ and to remove items
List<string> argList = args.ToList();

//create a stringbuilder for the errormessages
StringBuilder error = new StringBuilder();

try
{
//if "help" is one of the arguments, set the help property of options to true
if (argList.Any(arg => arg.ToLower() == "-help"))
{
this.Help = true;
argList.Remove("-help");
}

//if "help" is one of the arguments, set the help property of options to true
if (argList.Any(arg => arg.ToLower() == "/?"))
{
this.Help = true;
argList.Remove("/?");
}

//if "quiet" is one of the arguments, set the verbose property to false
this.Quiet = argList.Any(arg => arg.ToLower() == "-quiet");
argList.Remove("-quiet");

if (argList.Any(arg => arg.StartsWith("-path")))
{
//find the first argument that begins with "-path"
string folderArgument = argList.First(arg => arg.StartsWith("-path"));

string folderPath = folderArgument.Split('=')[1].Trim();
//remove quotationmarks
this.Folder = folderPath.Replace("\"", "");
if (!Directory.Exists(this.Folder))
{
this.ParseError = true;
error.Append("The path '" + this.Folder + "' is not a valid folder.\r\n");
}
argList.Remove(folderArgument);
}

//if there are still arguments left, the user has entered an invalid argument
if (argList.Count > 0)
{
this.ParseError = true;
argList.ForEach(arg => error.Append("Unknown argument: '" + arg + "'.\r\n"));

}

}
catch (Exception ex)
{
this.ParseError = true;
error.Append("Error while trying to parse arguments.\r\n The error message is '" + ex.Message + "'.");
}
//save the collected errormessages
this.ParseErrorMessage = error.ToString();

}
}

/// <summary>
/// The folder the user wants to delete, as a DirectoryInfo
/// </summary>
/// <returns>The folder the user wants to delete, as a DirectoryInfo</returns>
public DirectoryInfo GetFolder()
{
DirectoryInfo folderDir = null;

//if no parameter was given or ".", then we use the current folder
if (string.IsNullOrEmpty(Folder) || Folder == ".")
{
folderDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
}

else if (!Directory.Exists(Folder))
{
//if a folder parameter was given, but it doesn't exist, we throw an exception
throw new ArgumentException("The path '" + folderDir + "'is not a valid folder");
}
else
{
folderDir = new DirectoryInfo(this.Folder);
}

return folderDir;
}
}
}

MineCraft Timer app for Netduino

December 27th, 2010

MinecraftSince my previous post two things have happened...
First I’ve taken a liking to MineCraft, the builder/explorer indiegame that sold over half a million copies.   Secondly – I’ve taken up learning electronics, using Electronics for Dummies, and YouTube ;-) .

When I try to learn something new, I always start out with a little project I really want to do. It gives a lot of motivation to get through the ordeal of learning something by yourself.
For a long time, I’ve wanted to be able to program something on the PC which interacts with homemade netduinohardware outside the PC. I had heard about the Arduino (an open source programmable micro computer which interfaces with homemade periferals), but hadn’t gotten so far as to invest in one, when I heard about the netduino. The netduino is an Arduino for .Net coders. It runs the .Net Micro Framework, so you can write code in C# in Visual Studio.Net and then deploy it directly to the USB connected netduino.

minecraft_canary Ever since I downloaded the MineCraft Canary for my Android, which lets me know what time of day it is on the surface, I wanted to make an electronic version using LEDs. I am not yet skilled enough to make a version using just electronic components from scratch (you know – the oldfashioned way with soldering and stuff), so I thought “Why not use the netduino?” :) .

After quite a bit of fiddling around, and learning that the .Net Micro Framework doesn’t have Linq, Generics, and a host of other things I take for granted these days – I got a little working solution running.

In the video here I demonstrate the concept, both using the netduino’s built-in LED and button, and using the Seeed Studio Electronic Brick Starter Kit, which adds the possibility of click-on extensions.

There are two sets of code here:

- the really simple, written in one Program.cs file, which only uses the netduino boards button and LED
- a more advanced one which supports any number of inputs and notification components in a class hierarchy which implements interfaces for a code-your-own-extension style app.
They are both available for download here floppy

If you have the Electronic Brick Starter Kit, you need the ?LiquidCrystal library for interfacing with the LCD display.

The netduino is a LOT of fun :) .

------------------------

UPDATE 28 December 2010

Yay - my favorite webzine (MakeZine.com) found my project and posted it :D

http://blog.makezine.com/archive/2010/12/minecraft_timer_app_for_netduino.html

EPIC WIN!!!1 :)

And Kotaku as well - yay! http://kotaku.com/5720244/make-your-own-minecraft-alarm-clock