Bit’s Blitz – Puzzle Game

Bit's Blitz - Puzzle Game

Bit’s Blitz – Puzzle Game

In the third year of my Computer Science BSc (2013) as part of the Commercial Games Development module, we were placed into groups and tasked to produce a computer themed game designed for children. Each of the group members had to produce a game design document, one of which would be chosen for the group to develop. My group consisted of me, Aaron Ridge, Michael Killingbeck, Andrew Woodrow, Joshua Twigg and Alex Lynch.

The group decided to go with my game design which was inspired by the classic puzzle game Chip’s Challenge, with the idea being to reimagine it and modernise the graphics.

Game synopsis:
 “‘Bit’s Blitz’ is a fun 2D puzzle game following the escapades of its protagonist ‘Bit’. The game takes place across a series of levels increasing gradually in difficulty, gradually introducing new game-play elements. The player controls ‘Bit’ around a grid, constrained by a series of maze-like blocks and hazards. ‘Bit’ must successfully collect all the computer components that are scattered around the level and then repair his computer to proceed to the next level.”

Details:
Developed using C# and the XNA framework for the PC platform (Windows XP+).

 

The nice thing about this game design was that we could focus on the puzzle aspect of the game, time and imagination permitting, due to the simple overhead on technical implementation. The tile-based game engine was written from scratch using XNA, utilising XML data structures to store level data and a custom made loader. A cool and free little program called Tiled was used to ‘paint’ the level layout and export it into our XML format. I’d strongly recommend this to any considering 2D tile-based games for constructing levels, having said that, it’s a nice programming exercise to develop your own editor if you get the chance.

All gameplay aspects including animations and particle systems were programmed for the game, using no other libraries except XNA. I designed the game framework based on the State Design Pattern which worked out really well and continue to use it for game development.

With the use of XML and Tiled it allowed us to churn out level designs at an alarming rate and the final product has over 20 levels! Not bad considering the 2 week development time. When giving the presentation of the game, we literally only had time to demonstrate about 5 of the best levels, odd considering level variety tends to be in short supply for prototypes.

Sound effects were added (free assets) however I’ve removed these from the video and added music since honestly, they weren’t brilliant! The above gameplay video demonstrates various levels (played by me). I could barely remember most of the levels so it’s pretty much a blind play-through with some genuine mistakes.

For the project we all chipped in and the group worked well together. The game was never released or published anywhere, though if anyone is interested I could stick the executable on here for download.

CUDA Ray Tracer – Dissertation Project

Featured

After on and off work for a year, and many thousand words later, my final year BSc dissertation project and report was completed. Can a ray tracer ever be truly ‘complete’? This post a brief description and summary of my project.

A download to my full dissertation report can be found below and as well as a few renderings from my prototypes:

Report:

540 Downloads

Prototype Renderings:

The project from a personal point of view was an important one. It was a period where I gained heightened interest in graphics programming, gaining an understanding of the principles of computer graphics, the mathematics involved and also the creative satisfaction that comes from it. When creating realistic virtual graphics from essentially nothing but code, maths and a display, on the face of it, it’s very easy to gloss over the ‘magic’ of it all, especially when you understand the complexity of how we actually perceive the Universe and the shortcuts that must be taken for computers to accurately mimic the natural phenomena of our brain’s visual perception.

 

CUDA Ray Tracer - Dissertation Project

CUDA Ray Tracer – Dissertation Project

 

A Bit of Biology and Philosophy:

The modern computer when you think of it, is really just a primitive extension of our own bodies, simple enough that we can manipulate, manage and understand it, with much greater control and predictability then our biology. They allow us to achieve things we could not otherwise do and many of the components inside a computer carry out very similar roles to organs found within us. Of course we can think of the CPU as a brain, but what else? Going into more detail, the GPU could be seen as a specialised part of the brain engineered to handle visual computation, just as our brain has it’s own visual cortex. A virtual camera in a rendering program replicates the capabilities of part of our eye, defining an aperture or lens through which to calculate rays of light, and like-wise, an ‘image plane’ positioned in front of the camera, carries out essentially the same functionality as our retina, but using pixels to make up the visual image of what we see.

When you understand the detailed steps required to render something in 3D, you realise that we are essential trying to recreate our own little simplified universe, it’s a pretty profound concept that when taken much further, manifests itself in popular science fiction such as the Matrix. After all, is mathematics not simply the ‘code’ of our Universe? It’s perhaps not as silly as it may sound, when you get down to the fundamentals of game developers creating virtual worlds, graphics programming being an essential component, and looking just how real and immersive these worlds are starting to become.

So What Is Ray Tracing?

Ray Tracing

Of all popular rendering techniques, it’s ray tracing that perhaps stands out the most in respect to my previous comments above. We all know roughly how and why we see, where light rays shine from a light source such as our Sun, they travel millions of miles to get to us and out of all the infinite number of rays, the tiniest percentage may find it’s way directly into our eye. This could be from directly looking at the Sun (not recommended!), and also from scattered or reflected light that has hit a surface, finding it’s way on a collision course with our eye.
This is fundamentally close to how ray tracing works, but with important differences. If a computer had to calculate the trajectory of all possible rays been fired out from a light source, this would be impossible with modern hardware, there are just too many potential rays, of which, only an infinitesimally small amount would ever find there way into the camera (eye) of the scene, and it’s only these rays we are interested in anyway. Instead, and referred to as ‘Backwards Ray Tracing’, light is fired from the camera (eye) into the scene and then traced backwards as it is reflected, refracted or simply absorbed by whatever material it hits. We then only have to fire a ray from the camera for each pixel in the image, which is still potentially a considerable number of rays (1920×1080 = 2073600 primary rays) and that’s without counting all the secondary rays as light scatters throughout the scene, but at least this reduced number is quite feasible.

Still, it is ray tracing’s close semblance to how light interacts with us in the real world that makes it a very elegant and simple algorithm for rendering images, allowing for what is known as ‘physically based rendering’, where light is simulated to create realistic looking scenes with mathematically accurate shadows, caustics and more advanced features such as ‘global illumination’, something that other faster and more common rendering techniques like rasterization (pipeline-based) cannot do.

Illumination and Shading:

Phong Shading

Phong shading

The ultimate main job of firing the rays into a scene in the first place is to determine what colour the pixel in our image should be. This is found by looking at what a ray hits when fired into a 3D scene. Put simply, if it hits a red sphere, the pixel is set to red. We can define the material information for every object in the scene in similar fashion to how we know in the real world that a matt yellow box reflects light. Technically, the box is yellow because it reflects yellow light, and is matt (not shiny) because it has a microscopically uneven surface (diffuse) that scatters the light more evenly away from the surface. Compare this to light hitting a smooth (specular) surface, most of the light would bounce off the surface in the same direction and appear shiny to our eyes. Clearly, for computer graphics, we are not likely to program a surface material literally in such microscopic detail as to define if it is rough or smooth, but we can cheat using a popular and effective local illumination model such as Phong, essentially using the ‘normal’ of a surface, the directions of our light source and camera and some vector math to put it all together and calculate the colour of the surface based on it’s material and angle, creating a smooth shaded object rather than a ‘flat’ colour.

Intersections, Distance Functions and Ray Marching:

Implicit Functions

So we know why we need to fire the rays, but how do know a ray has hit a surface? There’s a few different ways this can be done, all down to the complexity of the geometry you’re trying to render. Ray intersections with simple shape such as planes or spheres can be calculated precisely using linear and quadratic equations respectively. Additionally, for complex explicit 3D models made from triangle mesh, linear algebra and vector math can also be used to compute the intersections.

Another technique, has been gaining popularity in recent years, despite been around quite some time in academic circles. Rendering complex implicit geometry using ‘distance functions’ with nothing but a pixel shader on your GPU as shown on websites like Shadertoy have popularised a subset of ray tracing called ‘ray marching’, requiring no 3D mesh models, vertices or even textures to produce startlingly realistic real-time 3D renderings. It is in fact, the very freedom from mesh constraints that is apparent when you observe the complex, organic and smooth ray marched geometry possible using the technique. Ray marching allows you to do things you simply cannot do using explicit mesh, such as blending surfaces seamlessly together, akin to sticking two lumps of clay together to form a more complicated object. Endless repetition of objects throughout a scene at little extra cost using simple modulus maths is another nifty trick allowing for infinite scenes. By manipulating the surface positions along cast rays, you can effectively transform your objects, twist, contort and even animate; it’s all good stuff.

The Dissertation Project:

My development project was comprised of two parts, a prototype phase to create a ray tracer using GPGPU techniques and a hefty report detailing the theory, implementation and outcomes. For those unfamiliar, General-purpose computing on graphics processing units (GPGPU) is a area of programming aimed at using the specialised hardware found in GPU’s to perform arithmetic tasks normally carried out by the CPU, and is widely used in supercomputing. Though the CPU hardware is singularly much more powerful than the processors in a GPU; GPU’s make up for it in sheer numbers, meaning they excel and outperform CPU’s when computing simple highly parallel tasks. Ray tracing, is one such highly parallel candidate that is well suited to GPGPU techniques and for my dissertation I was tasked to use NVIDIA’s GPGPU framework called CUDA to create an offline ray tracer, done from scratch using no existing graphics API. Offline rendering means not real-time, and is clearly unsuitable for games, yet is commonly used in 3D graphics industry for big budget animations like those by Pixar and DreamWorks, with each frame individually rendered to ultra high quality, sometimes over a period in excess of 24 hours for a single frame.

In the end I produced four different ray tracing prototypes for comparison, incorporating previously mentioned techniques. Prototype 1, running purely on a CPU single thread using simple implicit intersections of spheres and planes. Prototype 2, the same but implemented using a single CUDA kernel and running purely on the GPU across millions of threads. Prototype 3, a CPU ray marcher using distance functions to render more complex implicit geometry. Prototype 4, the same as 3, but implemented using CUDA. My aim for the project was to assess GPGPU performance and the rendering qualities of the ray marching technique, the findings of which can be found in the report.

I knew when I picked this project that I was not taking an easy topic by any stretch, and a great thing I can take away from this is the extensive research experience and planning needed to simultaneously implement many different difficult concepts I had no prior knowledge about, yet still managed to produce a cohesive project, and fully working prototypes, achieving an 88% mark for my efforts, which I am very pleased with. As expected, with heinsight there are things that I would do differently if repeated, but nothing too major, and really, it’s all part of the learning process.

Ray tracing, ray marching, GPGPU, CUDA, distance functions and implicit geometry were all concepts I had to pickup and learn. I bought some books, but in the end, research on the internet in the form of tutorials, blogs, academic papers and lectures proved more beneficial. Sometimes, it takes a certain kind of way to present the information for your brain to ‘click’ with certain principles, and all of us are different. The Internet is a treasure trove in this regard, if you spend the time, you can usually eventually find some explanation that will suit your grey matter, failing that, re-reading it a million times can sometimes help!

Future Plans:

On the back of this, I will be continuing this subject into my masters degree and will likely be pursuing this further during my masters dissertation. I am already busy at work on a real-time implicit render with UI functionality running in DirectX 11 (A couple of early screenshots above). Additionally, I’d love to get a chance to contribute to a research paper on the subject, but we’ll see.

I plan to make some easy to follow tutorials on implementing ray tracing and ray marching at some point for this website, when I get the chance. Hopefully, they could  help out other students or anyone else wanting to learn the aforementioned topics. I know first hand and from friends, that at times it can be frustrating since although there is theory out there, there is comparatively very little information on actual implementation details for the subject, when compared to say pipeline-based rendering.

OpenGL Cross-platform PC/PSP Game Coursework

Last semester as part of the Advanced Graphics module of my CS degree at Hull University, we were tasked with a group project to produce a cross-platform OpenGL mini-game for the PC and Sony PSP based on a specification. The game premise was to move around a 3D ‘maze’ consisting of four rooms and connecting corridors, avoiding a patrolling AI that would shoot you if within its line of sight. The objective was to collect 3 keys to activate a portal to escape and beat the game.

The groups were selected at complete random with 4 members. As per usual, group coursework assignments are particularly difficult due to the extra concerns of motivating members and assigning work and by year 3 of University, you get a good idea on the best way of operating within them to secure good grades. I went in with the mindset of doing as much work as possible after we assigned tasks. Hopefully each would carry out their allocated work, if not, I’d just go ahead and do it, no fuss. Luckily one chap in my group was a friend and he did an excellent job coding the AI, mini-map and sound while I worked on coding the geometry, camera, lighting and player functionality etc.

1

Mini-maze model

Static environment lighting

Static environment lighting

Cross-Platform Limitations:

Having worked with OpenGL and shaders last year for my 3D ‘The Column‘ project, it was some-what limiting when I realised that the PSP didn’t support them and that fragment-based lighting was a no go. With one requirement of the game being a torchlight effect that illuminated the geometry, this would therefore mean that for PSP compatibility, vertex-based lighting would need to be implemented and that meant tessellation of primitives to prevent the lighting looking very blocky and…well very 90’s. Luckily the PSP did atleast have support for VBO (Vertex Buffer Objects) which meant effectively each tessellated model could loaded onto the graphics card only once to improve performance.

Unified Code

An interesting aspect of this project was the required consideration for a consolidated code-base that where possible allowed shared functionality for both the PC and PSP platforms i.e limiting how much platform specific code was used. This was essential since the game would be a single C++ Solution for both platforms.

I designed the code structure based around principles Darren McKie (the course lecturer) described, and produced the following class diagram that reflects the final structure:

Unified Cross-platform Class Diagram

Unified Cross-platform Class Diagram

The majority of game code resides in ‘Common Code’ classes that are instantiated by each particular platform ‘Game’ object. Certain code such as API rendering calls were kept platform specific but made use of the common classes where necessary. A particular nice way of ensuring the correct platform specific object was instantiated was carried out using ‘#Ifdef’, ‘#ifndef’ preprocessor statements and handled by a ‘ResourceManager’ class.

As mentioned earlier, per-vertex lighting had to be implemented due to PSP compatibility. A primitive with a low number of vertices would thus result in very blocky lighting. To prevent this I created a tessellation function that subdivided each primitives vertices into many more triangles. I played around with the tessellation depth to find how many iterations of subdivision could be achieved before inducing lag and was very happy with the lighting result considering there is no fragment shader; a given for today’s modern pipelined-based rendering.

Active Portal

Active Portal

The PSP implementation proved more tricky due to getting to grips with the PSP SDK and having access to very little documentation, however the game was successfully implemented onto a PSP device and ran with decent performance after compressing the textures down and removing geometry tessellation to allow for the PSP’s limited memory capacity.

The game was written in C++ and  the following libraries and software were used:

  • GXBase OpenGL API
  • Sony PSP SDK
  • OpenAL
  • Visual Studio 2012
  • Paint .Net

Exchange Reports Project Overview

During this summer, in-between semesters I was fortunate enough to get a software development job for a local company just 10 minutes walk from my door. The project was to produce an ‘Exchange Reports’ system that would provide email messaging statistics exactly to the customers specification. The system would be automated so that after reports were designed, they would be generated programmatically by a service and emailed to any recipients that had been setup to receive each report. The solution was to be comprised of 3 distinct programs that would need to be developed along with configuration tools to setup the non-GUI processes in the solution (namely the services).

I have produced the following diagram to demonstrate the solutions processes, ( Click to enlarge):

The design was in place when I started and an existing code-base was also present, but still required the vast majority of the functionality to be added. It was the first time having worked professionally as a software engineer and therefore also the first time getting to grips with existing code made by developers no longer around. More so, understanding the solutions technical proposal well enough to execute exactly what the customer and my employer wanted. I think working in IT professionally for a lot of years certainly helped me get into a comfortable stride after an initial information overload when taking on solely what was a surprisingly large but beneficial technical project compared to what I had envisioned. Being thrown into the deep end is probably the fastest way you can improve and I feel that above all, I have taken a lot from this experience which will prove valuable in the future. I’m very pleased with the outcome and successfully got all the core functionality in and finished in the time frame that was assigned. I whole heartily would encourage students thinking of getting professional experience to go for it, ideally with an established company from which you can learn a great deal. Having experienced developers around to run things by is great way to improve.

Now onto the technical details. The project was coded in C# and used WinForms for initial testing of processes and later for the configuration programs. I used a set of third-party .NET development tools from ‘DevExpress’ that proved to be fantastic and a massive boon to those wanting to create quick and great looking UI’s with reporting functionality. SQL Server provided the relational database functionality, an experience I found very positive and very much enjoyed the power of Query Language when it came to manipulating data via .NET data tables, data adapters, table joins or just simple direct commands.

Using the diagram as a reference, I’ll briefly go through each process in the solution for A) those interested in such things and B) future reference for myself while it’s still fresh in my mind because i’ll likely forget much of how the system works after a few months of 3D graphics programming and Uni coursework :P.

Exchange Message Logs: 

In Exchange 2010 Message Tracking logs can be enabled quite simply and provide a wealth of information that can be used for analysis and reporting if so desired. They come in the form of comma delimited log files that can be opened simply with a text editor. They have been around a lot of years and in the past during IT support work I have found myself looking at them from time to time to diagnose various issues. This time I’d be using them as the source of data for a whole reporting system. The customer was a large international company and to give an example from just one Exchange system they were producing 40 MB-worth of these messaging logs each day. With these being effectively just text files that’s an awful lot of email data to deal with.

Processing Service: 

The first of 3 core components of the solution, the Processing Service as the name suggests is an install-able Windows Service that resides on a server with access to the Exchange Messaging log files. The service is coded to run daily at a specified time and it’s purpose is comprised of 5 stages:

1. Connect to the Exchange server and retrieve a list of users from the Global Address List (GAL). This is done using a third-party Outlook library called ‘Redemption’ that enables this information to be extracted and then check it for any changes to existing users and/or any new users. The users are placed in a table on the SQL database server and will be used later to provide full name and department information for each email message we store.

2. Next, each Exchange Message log is individually parsed and useful messaging information is extracted and stored into various tables on the database server. Parsed log file names are kept track of in the database  to prevent reading logs more than once.

3. Any message forwards or replies are identified and tallied up.

4. A separate Summary table on the database is populated with data processed from the prior mentioned message tables. This table is what the reports will look at to generate data. Various calculations are made such as time difference between an email being received and then forwarded or replied to gauge estimates of response times being just one example; a whole plethora of fields are populated in this table, much more than could comfortably fit on a single report. Due to this large amount of potentially desirable data we later allow the user to select which fields they want from the Summary table in the ‘Report Manager’ if they wish to create a custom report or alternatively and more typically, they use predefined database ‘Views’ that have been created for them based on the customers specification which allows them to access only the data they need. Database Views are a really neat feature.

5. The databases Messaging tables are scoured for old records beyond a threshold period and deleted. This maintenance is essential to prevent table sizes growing too large. Their associated Summary data that has been generated is still kept however but I added functionality to archive this by serializing this data off and deleting it from the database if required.

Report Manager:

Initially we had thought to utilise DevExpress’s ‘Data Grid’ object controls in a custom Form application but we decided that the appearance of the reports that were generated from this were not satisfactory. This turned out to be a good design decision since we later discovered DevExpress has remarkable reporting controls that allow very powerful design and presentation features that completely overshadowed that of the Data Grids. After some migrating of code from the old ‘Report Manager’ program and having to spend a day or two researching and familiarising myself with the DevExpress API I had a great looking new application that the customer will be using to design and manage the reports.

Report Manager program

Report Manager program

The Report Manager allows you to design every aspect of a report through an intuitive drag and drop interface. Images and various graphics can also be added to beautify the design, though that wasn’t something I did nor had the time to attempt! The data objects can be arranged as desired and the ‘data source’ information for the report is saved along with it’s design layout via a neat serialization function inherent to the ‘XtraReport’ object in the DevExpress library which is then stored in a reports table on the database server for later loading or building. You can also generate the report on-the-fly and export it into various formats such as PDF or simply print it. Another neat built-in feature is the ability to issue SQL query commands using a user-friendly filter for non-developers in the report designer which is then stored along with the layout, thus the user designing the report has absolute control over the data i.e a quick filter based on Department being “Customer Services” would return only that related message data without me needing to code in some method to do this manually like was the case when using the Data Grids.

In the top left you’ll see specific icons that provide the necessary plumbing for the database server. ‘Save’, ‘Save As’ and ‘Load’ respectively writes the serialized report layout to the database, creates a new record with said layout or loads an existing saved report from the database into the designer. Loading is achieved by retrieving the list of report records stored in the reports table and placing it into a Data Grid control on a form where you can select a report to load or delete. The ‘Recipients’ button brings up the interface to manage adding users who want to receive the report by email, this retrieves the user data imported by the Processing Service and populates a control that allows you to search through and select a user or manually type a name and email address to add a custom recipient. Additionally, upon adding a recipient to the report you must select whether they wish to receive the report on a daily, weekly or monthly basis. This information is then stored in the aptly named recipient table and then relates to the reports via a reportID field.

Report Service:

Nearly there (if you’ve made it this far well done), the last piece in the solution is another Windows Service called the ‘Report Service’. This program sits and waits to run as per a schedule that can be determined by a configuration app that i’ll mention shortly. Like the Processing Service, as part of it’s logic, it needs to check if it’s the right time of the day to execute the program, of course the service continuously polls itself every few minutes to see if this is the case. Upon running it looks to see if it’s the right day for daily reports, day of week for weekly reports, or day of month for the (you guessed it) monthly reports. If it is, it then it runs and grabs the ‘joined’ data from the reports and recipient tables and proceeds to build each report and fire them out as PDF email attachments to the associated recipients. It makes a final note of the last time it ran to prevent it repeatedly running on each valid day.

Configuration Tools:

Two configuration apps were made, one for the Processing Service and one for the Report Service. These two services have no interfaces since they run silently in the background, so I provided a method via an XML settings file and the two apps to store a variety of important data such as SQL connection strings, server authentication details (encrypted) and additionally also through the need to provide certain manual debugging options that may need to be executed as well as providing an interface to set both services run times and the report delivery schedule.

Screens below (click to enlarge):

So that’s the solution start to finish, depending on time I’m told it’s possible it could be turned into a product at some point which would be great since other customers could potentially benefit from it too.

The great thing about a creative industry like programming, whether business or games, is that you’re ultimately creating a product for someone to use. It’s nice to know people somewhere will be getting use and function out of something you have made and just one reason why I’ve thoroughly enjoyed working on the project. I’ve learned a lot from my colleagues while working on it and hope to work with them again. You also get a taste for real life professional development and how it differs in various ways to academic teachings, which although are very logical and sensible are also idealistic (and rightly so) but in the real-world when time is money and you need to turn around projects to sustain the ebb and flow of business, you have to do things in a realistic fashion that might mean cutting some corners when it comes to programming or software design disciplines. I always try my best to write as clean code as possible and this was no exception but ultimately you need to the get the project done first and foremost and it’s interesting how that can alter the way software development pans out with regards perhaps to niceties like extensive documentation, ‘Use Case’ diagrams and robust unit testing potentially falling to to the wayside in favor of a more speedy short-term turn around. Certainly I imagine, larger businesses can afford to manage these extra processes to great effect, but for small teams of developers it’s not always realistic, which I can now understand.

Hypermorph Wins Three Thing Game Competition

So it’s been a frantic couple of weeks, plenty of course-work to do and last weekend was the much anticipated Three Thing Game competition. For anyone not in the know this is held each semester at Hull University and challenges teams to come up with a game based around three auctioned words per team. Judges then score based on the games relevance to the words and the quality/fun of the game. The competition involves a marathon 24 hour programming session to get your game finished on the day. This one was the biggest yet with 39 teams competing. We really couldn’t have asked for better “Things” because a combination of good bidding and luck meant we came out with “Flying”, “Tank” and “Bombs”. Considering another team got “Teddy bear”,  “Deodorant”  and “Pop Tart” I think we did ok!

Last year we came second with Shear Carnage and and I can say that honestly this year, we really really wanted to win it. This was evident to myself just by the focus we had this year and when the day of the competition came, I think I probably left my seat half a dozen times in the whole 24 hours! In hindsight we probably took it far too seriously and as a result I think it sacrificed a lot of the enjoyment of the competition and resulted in some contention regarding ideas that seemed inevitable considering vested interests and no one leader within the team. I think on a personal note, much was learnt regarding team work and there are aspects of the planning and design process I would do differently next time. Luckily it all turned out worth it in the end and so it’s very hard to regret any decisions, but this was by no means a painless endeavour!

Me on the right, Russ in the middle, John on the left. Lee Stott at the back.

So to the game, Hypermorph is a retro-style side scrolling shooter that takes me back to my childhood days, playing classics such as Xenon 2, R-Type and Menace on the Amiga. Back then the shoot’em’up was a staple video game genre and was hugely popular, now only since the mobile platforms have taken off is the genre again feasible because it’s the perfect style of game to have a quick blast on when wanting to pass a little bit of time. The  thing that’s pretty novel in Hypermorph is the ability for the player to switch between two different forms, a spaceship and a hover tank by simply tapping the screen. We made the game using XNA (C#) for the Windows Phone 7 and coded everything ourselves (no third party libraries).

I produced the art for the game and managing both the art and doing a lot of the programming was a challenge in itself on the day, resulting in most of the art being done in the last few hours. I had a good idea in my head what the game would look like when we were bouncing the initial idea around, however my regret was that I didn’t produce any concept art for it sooner to put the rest of the team at ease; for a long time I think we were left with our own ideas for how the game would look but once I came up with the first concept drawing for the ship, the team were all in favour to my relief!

We had decided to make the game quite dark and moody but with bright weapon and explosion effects to make them really stand out. Additionally, we wanted to make the controls as hands off as possible. We learned from Shear Carnage that using touch too frequently can result in obscuring a lot of the screen so we instead went for a tilt based movement for the player and a single touch to morph between Tank and Spaceship. Importantly we set it to auto-fire constantly since you soon realise that in this genre there’s never a time you don’t want to be firing.

One feature I’m really pleased we put in was the voice effects for powerups and various other things. It adds a lot to the immersion and again, really goes back to the genres roots.

Of course we have plans to get Hypermorph out on both the WP7 and Windows 8 market ASAP but uni coursework is currently being prioritised. At the competition was Lee Stott from Microsoft and guys from the Monogame team. Lee’s encouragement was inspiring and I’d also like to thank him and Microsoft for providing the cool prizes. The Monogame guys were brilliant and we spent a fair time chatting with them regarding getting our games ported to the various platforms, they even ported Shear Carnage and my Robocleaner game for us to show us how easy it is! (albeit there’s some coding required to get them ready for the marketplace).

Ultimately we are going to want to put in a few more levels, enemy types, weapons and powerups before getting it on the marketplace, but the good news is it will most certainly be free!

All in all it was overwhelming and the encouragement we have received from Lee Stott, Rob Miles and the MonoGame guys was great. Ultimately this is why I gave up a career in IT to get into the games industry, because there’s so much satisfaction in putting your heart and soul into producing a game and then seeing others get a lot enjoyment from it. Winning the Peoples Choice award as well as the judges award was the icing on the cake and I’d like to thank everyone who voted for us and gave us great feedback.

Stay tuned for more Hypermorph news soon…

C++ word wrap for console output – Tutorial

I’ve been tinkering in C++ and decided to start making an old fashioned “text adventure” game as a nice little project to grasp the language.

As I started writing the game it quickly became clear that formatting all the strings manually with “new line” characters (n) to get the text to not breakup mid-sentence in the console was going to be hassle. I fancied a challenge and rather than grabbing some pre-written code from the web (how not to learn anything) I decided to work on an algorithm and make my own function that can deal with any string size and wrap the text neatly to the console.

I thought I’d make this little tutorial for anyone who wants to use it in their program but also wants to understand how the code works.

Here’s the function:

Note: Functionality has been gradually added, the updates further down detail the changes. I’ve included a Visual Studio code solution zip with the latest code at the bottom of this page.

Although the function is written here in C++, the algorithm can easily be applied to C# and other languages with just a few syntax changes. I was in two minds whether to go a route of splitting a string at the end of the line and then adding a newline character on the end, then “glueing” the strings together and repeating for each line, or whether to do it the way I did it which was by finding the last character on each line and then looping back through the line until it gets to a space and simply inserting “whitespace” on the end.

I’ll go through exactly what the function is doing:

Here we are preparing to loop through each character in the string to find where we want the line breaks.

This bit of modulo arithmetic checks the current loop iteration value to see if it is a multiple of the console window buffer width (80 default) and thus the character in the strings length that would be at the end of a line. By checking if it’s a multiple it allows us to apply this function to any size string. You’ll need to define BUFFER_SIZE in your program or simply replace it with the number value you want i.e 80.

BUFFER_SIZE could easily be changed via a variable and set to whatever buffer width your console window is using (see bottom of this article on how to get the current console buffer width value).

I initialise this variable for later use to keep track of the number of characters the loop has backtracked through in the string to find a space. (We’ll need to insert this number of whitespace into the string).

Here we are establishing whether the character at the end of the line is already a space. If it is, we don’t need to do anything and it’ll skip to the next loop iteration. Note “(i-1)” here, we do this because “i” is looking at the string based on it’s length with the lowest possible length obviously being 1. However when it comes to looking at the character array of the string “s”, arrays in C languages start at 0, thus we need to subtract 1 from the total length of the string to balance it. I could have adjusted the “for” loop to start at 0 instead and end at (s.length()-1) however this would have meant adjusting the modulo statement and personally it made more sense to me this way.

Once we have the character at the end of a line in “i” and know it’s not already a space, we loop backwards from this position in the string until we find a space i.e the end of a word.

As stated above, we check if each character we loop through is a space (‘ ‘). If it is then we have found the end of the last whole word on the line that fits and thus where we need to insert whitespace. We know how many spaces to insert because each time a character is checked and isn’t a space, we increment the “spaceCount” variable so we know how many spaces to insert to fill the line to the end.

We then output the newly word wrapped string to the console!

It’s great for text adventures or any program that outputs large strings since you can just call this function with any size string (within memory limits!) and it’ll do the rest. I tried to keep the solution as neat and minimal as I could.

Update (14/08/2012): Retrieving the console buffer width value

I thought I’d add in addition a way to get the console buffer width from the console each time text is output. This allows users to change the console window size and the text will wrap to it on the next output.

As you see here I have added at the top a function call “GetBufferWidth()”. This will return an integer with a value of the currently set console buffer width and store it in the bufferWidth variable that the OutputText function uses.

The code for GetBufferWidth is here:

It’s a relatively simple function that makes use of the CONSOLE_SCREEN_BUFFER_INFO class. You will need the ensure you have “#include” for windows.h specifically for the “wincon.h” child library containing the console services.

“dwsize.X” gives us the max number of available character “columns” in the window (by default 80), Note* “dwsize.Y” isn’t needed here but would give us the max number of available character lines for the window so by default it would return a value of 300 since that’s the default limit for console output (it would not give us the value of lines within the visible portion of the window).

Update (20/10/2012): Wrapping string text with newline characters (paragraphs)

I recently had a comment mentioning the problem with using this algorithm with paragraphed text. I had already come across this issue and had added some additional code to allow it to work with strings with “n” (newline) characters in. I’ve been meaning to do a blog post update with it for quite a while. I appreciate comments from people because it means people are using the code I’ve put on here and gives me an incentive to update this post so thanks.

Below is the full modified code. As can be seen from line 11, I have added a new block of code to check for any “n” characters (you could extract this into a separate function for neatness). If a “n” is found it inserts spaces into the string before the “n” character filling to the end of the line and jumps the loop iteration to the first character on the next line. I’ve also added a new char declaration on line 7.

By adding whitespace before the “n” character and thus moving it right to the end of the line, we are effectively countering all that extra space that the console window needs to generate when it hits a newline character. This would completely mess up our algorithms positioning in the console window if it wasn’t at the end of the line.

In detail:

Here if the current character in the string array is a “n” then it enters the new block. It then declares a new temporary variable for use later that contains the characters position within the line (defined by the width of your console window).

Next we calculate the number of spaces we will need to insert into the string from the “n” characters position to move it to the end of the line. We do this by finding the difference between the position of the current character in the line and the last position on the line.

We then insert just before the “n” character the calculated number of spaces.

Then we increment the current loop iteration by the number of spaces we just added which should set the loop index to the first character on the next line and “continue;” which will take us straight to execute the next loop iteration, repeating the process and checking every subsequent character for any more line breaks. If it doesn’t find one, it carries on as normal.

Here’s a screenshot of it in action with double “/n/n” line breaks inserted randomly into the string:

 

Download link for latest version of code (Visual Studio Solution):

415 Downloads

Robocleaner Update..

So, I’ve been progressing with getting my Robocleaner game on the marketplace (I’ve renamed the game from Sweepy Cleaner for originalities sake). It’s been taking a lot longer then initially I thought it would mainly because I wanted to completely redo the graphics and as anyone will find, graphics can be quite time consuming. On the plus side my knowledge of making graphics and using Photoshop and Illustrator has increased ten-fold.

Things I’ve added so far:

A menu system with options for muting sound and changing the control type from tilt to touch. Touch being useful if your not upright when playing. I also improved slightly my background image and removed the eyes from my hoover. Less is clearly more when it comes to hoover eyes since I think my Cyclopean hoover looks more bad ass then when it had two and actually it’s eye is now what used to be it’s nose :)

So far I’ve only made 4 levels out of 8. I’ve got the living room, bathroom, dining room and kitchen finished. I’m trying my best to make each room quite unique to the last and also slightly increase the difficulty as you progress, mainly by introducing more clutter and extra  stuff that harms you.

Bathroom

I’ve added Hazards which are like regular furniture except you can pass straight through them while taking damage e.g water, spilt coffee, broken glass etc..

Additionally a new little chap I’ve added which I’m quite pleased with is a Dust Goblin, he roams around the maps he’s on and if he comes into contact with any dust, he turns it into a Dust Bomb that he hurls at you, if it hits you, you take damage and you also die outright if you touch the goblin. He adds a significant challenge to the game and in later levels there will be multiple goblins, potentially of different types!

I’ve added decorative particle effects into some of the levels to add a bit of realism. In the bathroom for example, the bath tap is running and there’s steam and water droplets splashing onto the floor and on the kitchen map there’s a kettle with steam particles being puffed out.

Sometimes adding cool little things like the particle effects that don’t take much effort can make a nice difference to the polish of a game so I like to add them. You just have to limit yourself on some things otherwise the game would never get finished. Luckily the programming is pretty minimal at the moment since most was done for my course work (except the new stuff) and adding levels is just a few lines of code or less depending on what objects are present in it.

So there it is so far, hopefully I’ll get the other 4 levels done soon and can get it on the  marketplace asap with maybe an on-line scoreboard and time related scores for each level. It’s certainly a nice feeling seeing the game come together and hopefully not just be a uni coursework submission but an standalone fun little game.

Sweepy Cleaner – Windows Phone

I thought I’d finally get around to making a post on my blog and specifically concerning the thing that has taken up the majority of my time over the past week or so. Sweepy Cleaner!

This is a coursework project we had been assigned as part of the the Hull University Computer Science degree. We were given a spec and tasked with making a game plus extras via C# and XNA 4.0.

I decided I wanted to make as polished a game as I could that stuck pretty tightly to the design specification, but still add a decent amount of extras here and there. In the end I’m pleased with the finished product and really enjoyed making the game.

The toughest aspect of the project was the AI path-finding that I wanted to put in the game so that  in “attract mode” it guided itself around the furniture and collected dust of it’s own accord. This sounds simple but in reality it was the trickiest bit of programming I’ve probably done and let’s just say I won’t be bitching about dodgy path-finding in AAA games any time soon. I may actually make a separate post on this and include a dissection of the code I came up with.  I decided to initially look into an A* algorithm but I wasn’t sure how best to apply that to a game where things don’t move along a grid. So I decided to use static waypoint nodes that I manually placed around the level and then added them to a list, sorting them based on distance from each waypoint to the nearest dust to the hoover. I spent a long time trying to perfect it and although still not perfect, (I had to use at least one workaround) it performs convincingly enough with no furniture collisions and I’m very happy with it. I could later adapt it to make a “vs” mode where you have to race the AI hoover to collect the dust.

There’s only 3 levels in the game, I’ll hopefully add more before I get it on the Windows Marketplace.

Fingers crossed that my demo goes ok next Wednesday!

Here’s the artwork I did for the title screen, it does makes me think a 3D version of Sweepy Cleaner could be pretty fun!

C# / XNA: Passing Class instances (objects)

So, not being an expert I was trying to find improved ways of managing external class member access  without resorting to “public static” and ideally wanted an object orientated method, a while ago we were told by Rob Miles how classes or specifically instances of classes (objects) are passed by reference. I understood this however I didn’t really join the dots together for one useful implication it has::

Passing objects as parameters allows the receiving Method and potentially it’s Class, access to the objects members directly. (since its a memory reference to that object, not a copy).

It maybe obvious to some but ultimately,  it means you don’t need to keep feeding objects in as parameters for update methods to show changes, you can just do it once and store it there as a class member. The objects members will all be directly accessible from within that class, even if they are changed elsewhere in your program/game.

I think the thing that didn’t make this obvious to me is the fact that if you pass a class instance member variable instead of the instance itself, this behaviour doesn’t work, you just end up with a copy of the member variable at the point of being passed, but that’s because it’s been passed by value, not reference. Additionally, I found myself repeatedly passing object instances into Update methods, which worked but simply wasn’t needed since a ref could just be passed once and stored for the class. In the context of “Sweepy Cleaner” our Uni course work project, the below highly contrived examples highlight what I mean:

Pass by value Example:

Pass by Reference Example:

The other obvious good thing about passing the class instances instead of specific member variables is that you can of course access all members of that class instead of just the ones you pass. Additionally, it gets around the need to use public static for easy but rather lazy access of class members from outside the class, because only the classes you pass the instance to will be able to access it’s public members, and if you combine with “accessor”/”getter” methods I guess they don’t even need to be public.

(I’ve heard bad things about getter/setters too because it goes against the object orientated nature of C# apparently, but I’m not too bothered about that at this stage).

Anyway, you can of course still pass individual members via the “ref” keyword in the parameter and arguments to achieve the same thing as above but just for a member. I personally think for XNA passing the instance just seems a sound way of doing things. I’m not sure if there are repercussions to doing it like that, but so far it seems sound and hope this may help others who also hadn’t realised its usefulness.

Shear Carnage

So, it all started with an idea based off that gem of a game “Missle Command” (pictured above – and whom most who read this are likely too young to have played) and spiralled uncontrollably into what became a potent concoction of sheep gibbs, explosions and of course laser beams…what else? My one regret is that we didn’t get around to combining that into the direct form of “laser beam firing sheep gibbs that explode”, but I digress.

The Three Thing Game competition is something held by Hull University every 6 months and  is based on teams being given 3 random words and then developing a game about these words within 24 hours (We did have a few days between getting the words to plan and prepare however). Our team “Run Dead Studios” received the words Sheep, Fireworks and High Diving. My good friends and team mates Russ and John have covered all the detail on this marvellously so I won’t cover old ground but do check out their blogs! (You both now owe me a blog plug).

The day was great fun and my first experience of working so closely as a developer on a games (or any software for that matter) project. This itself would have been great enough reward however to actually come second place out of 33 teams and over 100 people, was truly a wonderful thing. We were beaten rather predictable by “The Infamous Two Sirs” who live up to their name I can tell you. They had an excellent game that won hands down in terms of innovation, and though its mechanics are quite hard to explain, rest assured it was good. Next time, I think we’ll go for something more innovative ourselves, now that our confidence has peaked a little. There was certainly an element of playing it safe from us, but like Rob Miles has said on his blog, its much better to make a full game that’s simple,  then a complex one that’s basically just a tech demo.

    

Details wise, we developed it on for the Windows 7 platform using XNA in C#. I’ve got to say I think XNA is a great development library and with the help of Visual Studio and Tortoise/Subversion SVN for source code management, it was pretty much a care free development experience.

I’m incredibly proud of what we achieved, especially considering we are first years and the game is simply great even if I do say so…we certainly had plenty of fun playing it on the day, in fact it was so addictive it may have gotten in the way of us actually trying to get it finished which I think is a good sign.

On behalf of Run Dead Studios, I present Shear Carnage! Coming to a Windows Phone App Marketplace soon, free of course. No Sheep were harmed in the making of this game, however if the sight of cartoon sheep dismemberment is shocking to you, I STRONGLY do not recommend you play this game :D.

Just to add, you can find the video of us presenting the game to the judges (Well, the first presentation anyway) below: