Azure for Students: Setting up a high score server – Part 1: Creating and publishing a web app

I recently gave a “Rather Useful Seminar” at Hull University in which I talked about and tried to show off how we can do cool things using the free Microsoft Azure subscription that students can access through Microsoft’s DreamSpark program. One of the things I went through was setting up a server to store and retrieve high scores from a web server.

However, there’s only so much I can get across in a 10-minute talk, so in this post I’m going to go through that in more detail. I’m going to assume that anyone reading this has at least basic knowledge of programming in C#, but not necessarily any experience with web development. If you need to brush up on C#, I’d recommend Rob Miles’ Yellow Book.

To follow along, you’ll need three things:

  • A Microsoft account
  • The Azure SDK (which you can download from Microsoft’s website)
  • A copy of Visual Studio 2015 – any edition (including Community) should work

What’s Azure?

Microsoft Azure is Microsoft’s cloud platform. A bunch of server farms located all over the world are operated by Microsoft, and you can host things on them such as web apps and databases and access them from anywhere. A big advantage of this is that it lets you run an app, store data, and retrieve data without needing any infrastructure. That’s useful for students, especially, as it means that the university doesn’t have to host anything, and you don’t need access to a physical server to run anything either – Microsoft takes care of all of that for you. All you need to do is publish your app.

Setting up an Azure subscription

If you have a DreamSpark subscription through your university, you can set up an Azure account for free, by doing the following:

  1. Go to the DreamSpark software catalogue: https://www.dreamspark.com/Student/Software-Catalog.aspx
  2. Select “Microsoft Azure for DreamSpark” under “Servers and Applications”
  3. Follow the instructions to finish setting up your account. You will be asked to provide proof of academic enrolment. Usually, this involves confirming your identity with your .ac.uk email address or entering credentials for your account at the university.
  4. You’ll be able to link your Azure subscription to a Microsoft account here – one you’ve done this, you’re good to go with your Azure subscription.

What we’re making

What this post will go through is the basics of setting up a server to store high scores on a video game. To do this, we’ll be setting up a web service with a REST API which lets us retrieve scores and submit them. Then, to store the scores between sessions, we’ll be linking the web service to a MySQL database.

What’s a REST API?

REST stands for “REpresentational State Transfer”. A RESTful service is a web service that performs different actions depending on the web request sent to it.
For example, sending a GET request might retrieve some data, whereas sending a POST along with some data might store that data in the database.

Getting started

The first thing we need to do is open a new project in Visual Studio. Select “Web > ASP.NET Web Application” from the list of project types:
ASPnetAppSelected

Then, select “Web API” from the list of templates. Set the “Authentication” to “No Authentication”.

To make things a bit easier later on, sign in to Visual Studio using the Microsoft account your Azure subscription is linked to.

Setting up a web app on Microsoft Azure

On the last screenshot, you probably noticed a checkbox saying “Host in the cloud”. If you tick it, you’ll be prompted to create a new web app on Azure from within Visual Studio, and your site can be published to there. You can also create a web app after creating your project, which is what we’re going to go through here.

Setting up a web app is relatively easy. The first thing you need to do is go to manage.windowsazure.com and sign in with the Microsoft Account you used to set up your Azure subscription.

From here, you’ll be taken to the Azure management portal, which should look a bit like this:
AzurePortal

This portal lets you set up and manage everything you’ve got running on Azure. Now we’re here, we can set up a new web app. Click “New”, and then select “Web and Mobile” > “Web App”:
NewWebAppSelected

Give it a unique name (the portal will validate it to make sure it’s unique), select “Dreamspark” under “Subscription”, and click “Create” to start creating a new web app on Azure. As you haven’t uploaded anything to it yet, this is basically a placeholder for now.

Publishing our app to Azure

Now that we’ve created a web app, we can publish our code to it. To do this, right-click the project in Visual Studio. From the menu, select “Publish”:
PublishSelected

On the wizard, select “Microsoft Azure App Service” and click “Next”. On the list of web apps, select the app you just set up and click “OK”. Finally, click “Publish” to upload all the files from your web app, and you now have a site hosted in the cloud.

You’ve probably noticed that there’s nothing but the default content on our web service. Next post, I’ll go through linking a database to our site and setting up a custom API.

“There is a missing project subtype…” error on adding a Windows 10 UAP project in MonoGame 3.4

I decided it was a good idea for me to enter the Hull Windows 10 Game Jam (or Windows 10 Three Thing Game, or Yorkshire Game Jam) this year, drawing on my nearly non-existent knowledge of game development and the tiny amount of work I did with XNA a couple of years ago.

Hey, I never said it was actually a good idea.

As MonoGame added Windows 10 support a little while back, I thought I’d try and get some practice in with it before the event. So, after setting up a Windows 10 dev box and downloading MonoGame, I created a new solution and added a MonoGame Windows 10 UAP project to it.

When I added the project, I ran into an error saying “There is a missing project subtype. Subtype ‘{[GUID]}’ is unsupported by this installation”. This was because I didn’t have the Windows 10 development tools installed – all I had to do to fix it was install the tools from here.

Problem connecting to TFS 2015 RC in browser from machine on same domain

I’ve been playing a little bit with TFS 2015 recently. The setup I’ve got going at the moment is a Hyper-V server with 3 virtual machines in a domain: a DC, a TFS server, and a build machine.

Build agents are deployed differently in TFS 2015 than they were in TFS 2013. Instead of having to run the TFS installer on each build machine, you can now download a build agent from your TFS server through your browser. So, to set up my build machine, I opened up a browser, typed in the TFS server’s URL… and was immediately greeted with the generic “Internet Explorer could not display this page” error message.

The culprit in this case was firewall rules. It turns out that when TFS is installed, it adds a rule to allow connections through port 8080, but it only adds this for the public profile. Changing this rule to allow connections from the same domain fixes the problem:

TFS Firewall Rule After

How to send data to an Azure event hub in a Windows Store app

I’ve been working on a Windows Store app recently which would generate data and push it to an Azure Event Hub. Unfortunately, the Event Hub API doesn’t work with Store apps as the NuGet package fails to install. This means that I had to fall back to using the REST API (documented here).

The idea here is to send a POST request in the following format:

POST https://{service bus namespace name}.servicebus.windows.net/{event hub name}/publishers/{publisher name}/messages HTTP/1.1
Authorization: {token}
Content-Type: text/plain; charset=utf-8
Host: {service bus namespace name}.servicebus.windows.net
Content-Length: {message length}
Expect: 100-continue

{Message}

Everything in {braces} is stuff that can or will need to be changed to send data to your own event hub. For example, if you leave all the parameters at the top of the code below with their default values, the request that gets sent looks an awful lot like this:

POST https://pwrblogdemo-ns.servicebus.windows.net/pwrblogdemo/publishers/test/messages HTTP/1.1
Authorization: SharedAccessSignature sr=pwrblogdemo-ns.servicebus.windows.net&sig=T2iCRtFA%2BEeDfGMryzNssI3ssa8%2BQ0Q3xO2qPetrsk8%3D&se=1429046553&skn=SendRule
Content-Type: text/plain; charset=utf-8
Host: pwrblogdemo-ns.servicebus.windows.net
Content-Length: 14
Expect: 100-continue

{Message:Test}

For this to work, I’m going to assume you already have an event hub set up. If you don’t, then follow the guide here to get one up and running. You’ll also need a shared access policy with “Send” permissions.

Below, I’ve written out some code you can use to send data to your own event hub. Simply change the parameters at the top to set the endpoint and message.

eventHubName and serviceBusNamespace are pretty self-explanatory, and match {service bus namespace name} and {event hub name} in the example request. ruleName will need to be set to the name of a shared access policy with “Send” permissions, and ruleKey will need to be the primary key of that policy.

{token} is a Shared Access Signature token. I’ll talk more about how this is generated below.

An event hub is designed to receive ‘event data’ from ‘Event Publishers’. The documentation’s (purposefully?) vague on this one, but it looks like ‘Event Publisher’ is just a catch-all term for any device which sends data to an event hub. The only thing we have to worry about is giving it a name and sending that name with every request – that’s what {publisher} is in the request examples above. ‘Event data’ consists of a message body and some metadata. I’m not sure how exactly this is formatted, but the metadata is all placed on it when it reaches the event hub, so all we need to worry about sending is the message body, which is sent as the payload for our request. This can be in any format you want.

publishername and message set the publisher’s name and the message in the code below.

[code language=”csharp”]
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;

class EventHubSender
{
//Parameters:
private static string eventHubName = "pwrblogdemo";
private static string serviceBusNamespace = "pwrblogdemo-ns";
private static string ruleKey = "YJaiGMQAHvNrCajrxl1fsO2Ol4KZwOmokHafo/7Qhhk=";
private static string ruleName = "SendRule";
private static string publisherName = "Test";
private static string message = "{Message:Test}";

public async Task SendToEventHub()
{
string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace);

string authToken = GenerateAuthToken(serviceBusUri);

HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Clear();

var authHeader = new System.Net.Http.Headers.AuthenticationHeaderValue(
"SharedAccessSignature", authToken);
client.DefaultRequestHeaders.Authorization = authHeader;

string body = message;
var content = new StringContent(body, Encoding.UTF8);
client.BaseAddress = new Uri(string.Format("https://{0}", serviceBusUri));

await client.PostAsync(string.Format("/{0}/publishers/{1}/messages", eventHubName, publisherName), content);

client.Dispose();
}

private static string GenerateAuthToken(string serviceBusUri)
{
int expirySeconds = GetExpirySeconds();
string expiry = expirySeconds.ToString();

string signature = GetSignature(serviceBusUri, expiry);

string authToken = string.Format(
"sr={0}&sig={1}&se={2}&skn={3}",
WebUtility.UrlEncode(serviceBusUri),
WebUtility.UrlEncode(signature),
expiry,
ruleName);
return authToken;
}

private static string GetSignature(string serviceBusUri, string expiry)
{
var hashAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
var encoding = BinaryStringEncoding.Utf8;
string stringToSign = string.Format("{0}n{1}", WebUtility.UrlEncode(serviceBusUri), expiry);
var keyBuffer = CryptographicBuffer.ConvertStringToBinary(ruleKey, encoding);
var valBuffer = CryptographicBuffer.ConvertStringToBinary(stringToSign, encoding);
var hash = hashAlgorithmProvider.CreateHash(keyBuffer);
hash.Append(valBuffer);
var hashedDataBuffer = hash.GetValueAndReset();
string signature = CryptographicBuffer.EncodeToBase64String(hashedDataBuffer);
return signature;
}

private static int GetExpirySeconds()
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
DateTime expiryTime = DateTime.Now.AddHours(1);
int expirySeconds = (int)expiryTime.Subtract(epoch).TotalSeconds;
return expirySeconds;
}
}
[/code]

The code is doing two things: generating an SAS token; then it is placing this on an HTTP request along with the publisher name and message and sending it.

The SAS token for sending data to an event hub is in the following format:
sr={Service Bus URI}&sig={Signature}&se={Expiry}&skn={Shared Access Policy Name}

The service bus URI is the URL-encoded URI for the service bus namespace (for example, ‘pwrblogdemo-ns.servicebus.windows.net’). The expiry is expressed as the number of seconds between the desired expiry time and midnight on January 1st, 1970. The shared access policy name is the name of the policy you set up to grant send access to the event hub. The signature is an HMAC-SHA-256 authentication code that is obtained by creating a string consisting of the service bus uri and the expiry, separated by a newline e.g. “pwrblogdemo-ns.service.windows.netn1429046553”, then signing this with a hash created from the shared access policy’s primary key.

Useful links:
Event Hub overview
Azure Event Hub REST API documentation

“Why does my IQ feel all small?” | Thoughts on Future Decoded 2014 – Part 1: The Keynotes

Yesterday, I was lucky enough to attend the Future Decoded Tech Day. This a conference run by Microsoft where “techies will get a comprehensive picture of the latest trends in the industry as well as Microsoft’s products & services”. Translated from marketing-speak, this was a technical conference covering several areas Microsoft have been pushing recently and bandwagons that they’re trying to jump on, such as DevOps and cloud services (if you hate your liver, drink every time Microsoft plug Azure). It’s also notable for being free – however, I don’t think that was originally the plan, and the (rather large) cynical part of me believes that they desperately needed more bums on seats. That aside, the entire day was filled with some absolutely fascinating stuff, and I thoroughly enjoyed it. Below, I’ll be talking through the keynote speakers and my slightly rambling, inane thoughts on them.

The talks kicked off with Sir Nigel Shadbolt discussing open data. He has probably done more than almost anyone to push organisations and governments to make their data open to the public, and the sheer amount that’s now available thanks in no small part to his and Tim Berners-Lee’s efforts with the Open Data Institute is absolutely stunning. I’ve run across people talking about open data before, but until yesterday I didn’t really appreciate just how powerful it could be and how much can be done with it – as exmplified by the numerous examples Sir Nigel showed, including a website which mapped which companies owned which other companies in the world, and a map of Haiti’s capital created entirely by users contributing small amounts of geographical data.

The next talk was given by Michael Taylor, the IT director for the Lotus F1 team on how much racing both owes and has contributed to technology and innovation. It’s certainly exciting stuff, but as someone who has never really understood the appeal of F1 as a spectator sport I feel a lot of it was lost on me. However, I think there’s definitely common ground between programmers and F1 teams – they both rely on cycles of constant small changes, and each cycle they aim to push just a little bit more performance out of their equipment or a little bit more use out of their product. I’d definitely rather be compared to an F1 team than a ninja or martial artist – but then again, programmers referring to themselves as ‘ninjas’ is a personal bugbear of mine.

The next talk was an interview with Or Arbel, CEO of Yo. Yo is an app which sends a notification to your friend and causes their phone to play a mildly annoying “Yo!” sound effect.
“Can’t I just get my friend’s attention using any other social app? Why should I use this thing?”, you may ask. Unfortunately, that wasn’t one of the questions answered in the interview, and I sure as hell don’t have an answer for you.

That is, perhaps, a little unfair. In this interview, they also showed off one of Yo’s new features: companies can now send bits of content to people following them on Yo. This, I’m sure, is great for the sort of person who wakes up in the morning and thinks:
“Golly, it sure would be a fine thing if someone tried to advertise something to me today. If only they’d send me a distracting notification along with their advert as well, that sure would be mighty fine.”
Obviously, no-one actually thinks this exact thought – for one, I doubt anyone says “golly” outside of Enid Blyton novels – but Arbel and his investors seem to think that plenty of people share this sentiment. I hope I never meet any of them.

On a positive note, Arbel has done something pretty cool and made the API open to the public. Despite myself, I quite like the concept of these little, single-button, single-function apps, and I think Yo is as good a starting point as any for developers looking to make something like this. That said, I’ve not used Yo’s API myself, so I really can’t say how useful it is.

David Braben, creator of Elite and Elite: Dangerous, is nuts. There is no other explanation for why he would spend millions of pounds aggregating reams of astronimical data and using it to create a near-perfect model of our galaxy, down to the last star, and then simulating the formation of millions of planets and satellites around these, just to create the world that Elite: Dangerous takes place in. With an almost childlike excitement, Braben showed how he has simulated planets coalescing into being, colliding, and rings forming around them. It’s a truly breathtaking amount of effort just to create a pretty backdrop for a space trading game, and if it’s even half as complete and immersive as Braben, biased as he is, made it look then I’ll quite happily lose hundreds of hours to playing it.

Finally, it was time for the headline act: Professor Brian Cox, also known as “that science bloke off the telly”, discussing how our universe came to be and how physicists figured out how it all began. In person, he is even more charismatic and entertaining, and I wish I had even a tenth of his ability to enrapture an entire exhibition hall full of people while talking through some physics equations. He is the main reason for this post’s title being what it is – anyone who, like Brian and his colleagues, can find new ways of furthering our understanding of how the universe came to exist and then pass this knowledge on is far smarter than they have any right to be.

The technical talks took place in the afternoon. I’ll probably cover them in a future post, as this post is long enough already and I feel the technical talks are somewhat of a change of pace compared to the keynotes, so they don’t really fit in the same post anyway.

How to check for visibility on a HTML control using Microsoft Coded UI tests

As you may have gathered from the title, I had written a test where I had to check if a control was visible on the page after I pressed a button. I wrote the test, clicked the button, everything was fine. Then I decided to double-check the test by reversing the condition (e.g. swapping an Assert.IsTrue for an Assert.IsFalse, or something similar). If this succeeded, then my test was probably working, and not just throwing a false positive. As always with these things, the test still passed, and that led to this post.

To give you a grossly simplified example, imagine a web page with a button. After we press the button, the words “Ta-dah!” appear on the page. Or for those of you with terrible imaginations, this JSFiddle should work.

We want to check that when the page first loads up, the words “Ta-dah!” aren’t visible. Here’s our first stab at it:

[code language=”csharp”][TestMethod]
public void FirstAttempt()
{
//Open up our web app
using (var window = BrowserWindow.Launch(AppUri))
{
//Set up some search properties for our control
HtmlControl control = new HtmlControl(window);
control.SearchProperties.Add(HtmlControl.PropertyNames.Id, "invisible");

//This should mean that we only find visible controls, right?
control.SearchConfigurations.Add(SearchConfiguration.VisibleOnly);

UITestControlCollection matches = control.FindMatchingControls();

//If we haven’t found anything, then I guess we’re good
Assert.AreEqual(0, matches.Count);
}
}[/code]

A bit of a hack, but it’s simple enough. We set up our search terms and tell the framework to find all the controls which match those, as usual. If the control’s not visible, it shouldn’t be found by our search and so there won’t be any matches.

Unfortunately, when we run the test, it fails. This is because SearchConfiguration.VisibleOnly doesn’t work on HTML controls, so even controls which aren’t shown on the page will be found by the search. In order to find our control, we’re going to have to use another method. In the example, the hidden paragraph is hidden by setting its style to ‘display:none’, and conveniently enough there’s a very simple method we can use in that situation: when a control’s been hidden this way, its bounding rectangle will have a negative height and width. So, with that in mind, we can use a simple extension method to ensure we only grab visible controls:

[code language=”csharp”]public static class HtmlControlExtensions
{
public static UITestControlCollection FindVisibleMatches(this UITestControl control)
{
UITestControlCollection matches = control.FindMatchingControls();
matches.RemoveAll(x => !IsVisible(x));
return matches;
}

private static bool IsVisible(UITestControl control)
{
return
control.BoundingRectangle.Width > 0 &&
control.BoundingRectangle.Height > 0;
}
}[/code]

Then, instead of using FindMatchingControls, just use the extension method:

[code language=”csharp”][TestMethod]
public void SecondAttempt()
{
//Open up the web app
using (var window = BrowserWindow.Launch(AppUri))
{
//Set up some search properties for our control
HtmlControl control = new HtmlControl(window);
control.SearchProperties.Add(HtmlControl.PropertyNames.Id, "invisible");

//Use the extension method to only grab visible controls
UITestControlCollection matches = control.FindVisibleMatches();

//And now this assert succeeds
Assert.AreEqual(0, matches.Count);
}
}[/code]

This second test succeeds. Finally, we can write a test to check whether the control is visible after the button is pressed:

[code language=”csharp”][TestMethod]
public void WordsAreVisibleAfterButtonIsPressed()
{
//Open up the web app
using (var window = BrowserWindow.Launch(AppUri))
{
//Press the button
HtmlControl button = new HtmlControl(window);
button.SearchProperties.Add(HtmlControl.PropertyNames.Id, "button");
HtmlControl foundButton = button.FindMatchingControls()[0] as HtmlControl;
if (foundButton == null)
{
Assert.Fail("Button was not of an appropriate type");
}
else
{
Mouse.Click(foundButton);
}

//Set up some search properties for our control
HtmlControl control = new HtmlControl(window);
control.SearchProperties.Add(HtmlControl.PropertyNames.Id, "invisible");

//Use the extension method to only grab visible controls
UITestControlCollection matches = control.FindVisibleMatches();

//We should be finding the paragraph now
Assert.AreEqual(1, matches.Count);
}
}[/code]

and know that it’s only going to find the paragraph if it’s visible.

Before I go, I should point out that this won’t work if the control is hidden in a way which means it still takes up room on the page (for example, adding visibility:hidden to its style). If you have a way of doing that, or any other questions, ideas, criticisms, then leave a comment below. If you have none of those things, but you want to leave a comment anyway – perhaps you’re on fire, and the only way you can call for help is by leaving a comment – then by all means, feel free.

GameBoy programming tutorial: Hello World!

This tutorial will guide you through the steps of programming a ROM which, when run using a GameBoy emulator, will write the words “Hello world” on the screen. The code in this tutorial will all be the assembly language used by the Game Boy processor, which is a slightly modified version of the Zilog Z80. If you don’t know any assembly language, don’t panic! I’ll be going through this almost line by line and explaining everything along the way. I will, however, assume you know what a ROM is, and what an emulator is. Some stuff here might also be a bit difficult to follow if you’ve never done any programming before – and, to be honest, if you haven’t programmed before, then jumping right into assembler like this is probably not the best way to learn.

Before you go on, however, you need a few things first: an editor so you can actually write some code; an assembler and linker which will allow you to make your assembly language program into an actual, working ROM; and finally, an emulator so you can run your program.

To view and edit assembly language, I use Vim, because a) it’s free, and b) it has a few features, like syntax highlighting and line numbering, which make it fairly useful for coding. I also found a Vim syntax highlighting file for Game Boy assembler, which you can download from here. Of course, you don’t need Vim for this – you can use any text editor that can open .asm files, including Notepad.

The compiler and linker I used were the RGBDS tools, which you can download for free from their creator’s website. I’ll be going through how to use these tools to make your ROM later on.

Finally, you’ll need an emulator to run your code. It’s really your choice which emulator you use – I used VisualBoyAdvance.

The Code

Now that all that’s out the way, we can start coding. The first bit of code we’re going to look at is these two lines:

INCLUDE "gbhw.inc"
INCLUDE "ibmpc1.inc"

These two lines import two include files. The first one, gbhw.inc, attaches names to a load of locations in the GameBoy’s memory – meaning that we don’t have to remember exact addresses for all of this stuff. Where we run across one of these names further on, I’ll point it out along with which location that name represents. The second include file, ibmpc1.inc, defines the ASCII font set as a set of 8×8 pixel images, also known as “tiles”. This is really important, as it’s how we can display our text in the first place.

The reason we need our letters as tiles is because of how the Game Boy stores and displays graphics. The GameBoy can store and display two different kinds of images: “tiles”, which are 8×8 images; and “sprites”, which are either 8×8 pixel images, or 8×16 pixel images. The GameBoy can’t display anything other than images – there’s no text output – so any writing we’re storing has to be displayed as images. Because we aren’t using sprites in this program, I’ll ignore them for now and focus on tiles – of course, if you’d rather get right back to coding, then ignore the next bit.

Tiles

The GameBoy draws its graphics to a “buffer”, which is then displayed on the screen. There are multiple buffers used by the GameBoy, but the one we’ll be worrying about is the background tile buffer. This buffer consists of 256×256 pixels, or 32×32 tiles – remember that tiles are 8 pixels by 8 pixels – arranged in a grid. Because the GameBoy only has a 160×144 pixel screen, this means that only part of the background can be displayed at a time. We won’t be using them much in this tutorial, but the SCROLLX and SCROLLY registers store the co-ordinates of the background buffer which will be displayed in the top left corner of the screen. For example, setting these to 0 will mean that we’ll see the first 160 columns and 144 rows of pixels, while setting SCROLLX to 160 will mean that we see the last 96 columns of pixels. The background buffer is also kind of interesting in that it wraps around. This means that if we set SCROLLX to 150, we won’t get gaps – instead, we’ll see the last 96 columns, and then the first 64 columns on the right-hand side of the screen.

Interrupts

Now, the next few bits of code we’re dealing with are these ten lines, here:

SECTION "Vblank", HOME[$0040]
ret
SECTION "LCDC", HOME[$0048]
ret
SECTION "Timer_Overflow", HOME[$0050]
ret
SECTION "Serial", HOME[$0058]
ret
SECTION "p1thru4", HOME[$0060]
ret

Now, these lines don’t actually do anything in this program. They’re there because of a particularly important concept in GameBoy programming, called interrupts. An interrupt is a signal, sent by another part of the hardware, that stops the program executing normally until it’s performed another task – hence the name “interrupt”. Different hardware generates different interrupts, and the programmer can use these sections to decide how the program handles each kind of interrupt. When an interrupt occurs, the program will jump to the relevant section and execute what’s in there before picking up where it left off in the main program. In this case, we won’t actually be using interrupts at all, so none of these routines do anything – the only instruction in any of them is “ret”, which is used to exit the interrupt handler and go back to where the program was interrupted.

The numbers in square brackets are locations in memory, which we’ve attached labels to. The $ sign before the number is used to mark the number as hexadecimal i.e. instead of going from 0 to 9 before adding another digit, like decimal (base-10) numbers, the numbers go from 0 through F before rolling over to another digit.

Setting up the ROM header

The next bit of code after that is this:

SECTION "start", HOME[$0100]
nop
jp begin

ROM_HEADER ROM_NOMBC, ROM_SIZE_32KBYTE, RAM_SIZE_0KBYTE

On startup, the first thing an actual GameBoy does is execute a small (256 byte) program, which reads the memory locations from $100 to $14D – an area also known as the ‘ROM header’ – and uses the information there to perform various bits of setup, which I won’t go into too much detail about here because it’s not particularly important for this program. The line beginning with ROM_HEADER up there executes a macro which handles most of the stuff we need in there. The three arguments we’ve put in to that macro, ROM_NOMBC, ROM_SIZE_32KBYTE, and RAM_SIZE_0KBYTE, tell the GameBoy that our ROM is just a simple, 32 kilobyte ROM – 32 kilobytes is the minimum size for a GameBoy ROM.

The next thing it does is jump to memory location $100, and executes the code there. In this case, it’s the code you see up there – which, incidentally, are also the first assembler instructions we’ve seen so far. If you’ve ever seen any assembler language before, the syntax should be pretty familiar. There is only one instruction on each line, and each instruction consists of one or more parts. The first part, the ‘mnemonic’, tells the GameBoy what kind of instruction it’s executing, while if there are more parts then those are the ‘arguments’ or ‘parameters, which are bits of data the instruction uses. In other words, the mnemonic tells the GameBoy what to do, and the parameters tell the GameBoy what to do stuff to.

The first instruction, nop, is unfortunately not particularly interesting. It’s a ‘no-op’ instruction: all the GameBoy does is wait for 4 CPU cycles, before moving on to the next thing. Th next one, jp begin, is a bit more exciting. jp is a ‘jump’ instruction – when the program runs across it, it skips straight to the address in memory given as its argument. In some cases, this will be a number – here, however, we’re using a label, ‘begin’, to tell it where to go.

It begins…

‘begin’ is the address in memory where our code actually starts:

begin:
nop
di

‘di’ stands for Disable Interrupts – because they’re not being used in this program, I’m turning them off and keeping them off.

Stacks ‘n stuff

ld sp, $ffff

This instruction is one of the more important bits of setup code we’re running. What it does is set the stack pointer to $ffff, which is one more than the highest memory address the GameBoy can access. The ‘stack’ is the bit of memory the GameBoy uses to store things when it’s running, including arguments, variables, and return addresses – this is something it has in common with most processors. There are two things the GameBoy can do with the stack – it can ‘push’ a piece of data onto it, and it can ‘pop’ the last bit of data added to the stack and use it. The stack pointer is used to keep track of where the ‘top’ of the stack is – this is the bit of memory that stores the last item to be pushed onto the stack and not subsequently popped.

Setting the stack pointer higher than where the GameBoy can access might seem counter-intuitive, but it’s because of how the GameBoy pushes values onto the stack. When a GameBoy pushes a piece of data onto the stack, it performs two operations:

  1. It subtracts 1 from the stack pointer.
  2. It writes the data being pushed to the memory location that the stack pointer is pointing to.

For example, if we were to push the value 5 onto the stack, we would first move the stack pointer so that it’s pointing at memory location $FFFE (1 less than $FFFF), and then write 5 to that memory location.

The stuff above describes what that line of code is doing, but not how it’s doing it. To explain that, let’s take a look at the GameBoy’s CPU. Like any CPU, a GameBoy CPU has several ‘registers’, which are parts of the processor that can store a value so it can be accessed quickly later on. The Gameboy has eight 8-bit registers, which can store values up to 255, called A,B,C,D,E,F,H and L. There are also two 16-bit registers, called SP and PC. SP stands for ‘stack pointer’, and is where the address that the stack pointer is pointing to is actually stored. The instruction ‘ld’, used up there, stores its second argument in its first one – in this case, storing $FFFF in the SP register.

Setting up the screen

But enough about stacks – the next bits of code are a bit more interesting, and useful for us at the moment.

ld a, %11100100
ld [rBGP], a

This stores the value 11100100, expressed in binary numbers, in register A, and then stores the contents of A in memory location $ff47 (which [rBGP] is standing in for here). $ff47 is the memory location that stores the background tile palette, which are the shades of grey used by the GameBoy when it draws its graphics. The value 11100100 can be split into 4 parts (11, 10, 01, and 00), representing the colours black, dark grey, light grey, and white. Essentially, taken together, these 2 lines set up the palette so that any tiles drawn will use these 4 colours.

The next set of instructions sets the scroll registers (mentioned above) to 0, meaning that the screen will show everything starting at the top-left corner of the buffer.

ld a, 0
ld [rSCX], a
ld [rSCY], a

The next thing to do after that is to turn the screen off, and then copy our data into the video RAM. Turning the screen off is a bit of an awkward procedure – what we actually need to do is check if the screen’s already on, tell it to turn off, and then wait for a bit until it actually finishes turning itself off. That sounds like a lot (or a few lines, at least) of work to do something we can sum up pretty easily in a few words, so this seems like the perfect time to introduce something new: subroutines. If you’ve programmed before, you’ll have seen these, although you might have called them “methods” or “modules”. They’re just sets of related statements, which have all been grouped together and given a name:

TurnLCDOff:
ldh a,[$ff44]
cp $90
jr nz, TurnLCDOff
xor a
ldh [$41], a
ret

That goes down at the bottom, after all your other code. Then, in the main bit of the program, you can ‘call’ your newly minted subroutine:

call TurnLCDOff

The ‘call’ command basically means ‘find this subroutine, and do everything in it’. The ‘ret’ instruction in our subroutine up there is how we get back out the routine once we’ve finished doing everything in it. This works a lot like a method call in a language like C# or C++ – it’s a bit more complicated in those languages (for reasons I won’t go into here), but if you look at the assembler code your compiler generates when you call a method in C++, there will be a ‘call’ statement there.

On to the next thing: loading our letters into tile memory. To do this, we’re using a subroutine from that ‘memory.asm’ file we included earlier, called mem_CopyMono. This uses three of our processor registers: HL, which is where the routine pulls data from; DE, which is where the routine copies data to; and BC, which stores how many bytes we’re copying. So, first, we make sure that wherever we’re pulling tile data from actually has the tiles in it, like so:

ld hl, TileData

Next, we set up DE so that it’s storing the location in RAM where tile memory starts on a GameBoy.

ld de, _VRAM

Finally, we store the value (8 * 256) in bc, and call mem_CopyMono. This is because the ASCII character set we’re using has 256 characters, with 8 bytes each – and we want to make sure we’re copying all of them in.

ld bc, 8*256
call mem_CopyMono

Now that we’re done messing around with tile memory, it’s safe to turn the screen on again. So, let’s do that:

ld a, LCDCF_ON|LCDCF_BG8000|LCDCF_BG9800|LCDCF_BGON|LCDCF_OBJ16|LCDCF_OBJOFF
ld [rLCDC], a

Now, all we need to do is clear our screen. We can do that by setting every bit of the screen to a blank space, which is why we’re loading 32 into the A register here (32 is the ASCII space character in decimal).

ld a, 32
ld hl, _SCRN0
ld bc, SCRN_VX_B * SCRN_VY_B
call mem_SetVRAM

And, now, finally, the bit you’ve all been waiting for: writing to the screen. To set up our message, put this at the end of your code:

Title:
DB "Hello World!"
TitleEnd:

And then put this in the main bit:

ld hl, Title
ld de, _SCRN0+3+(SCRN_VY_B*7)
ld bc, TitleEnd-Title
call mem_CopyVRAM

mem_CopyVRAM works a lot like mem_CopyMono above, and it’s from the same header file. What we’ve just done is told it to load the characters in “Hello World!” into video RAM, and set them up at position _SCRN0+3+(SCRN_VY_B*7) – aka “3 columns across, 7 rows down”.

Now, there’s just one final thing to do:

wait:
halt
nop
jr wait

This just makes us stay in an infinite loop until the user closes the window. It does this with the combination of a label, ‘wait:’, and the instruction ‘jr wait’, which just means “Jump back to ‘wait:'”. And, with that in there, you should be able to see the output.

How to make a ROM

That’s the code written – now, we can make it into a ROM. We do this using RGBDS tools from the beginning. To get a working ROM from your assembler source file, simply store the RGBDS tools in the same folder as your assembly code. Then, open up a command prompt, and type in the following:

rgbasm -o hello.o hello.asm
rgblink -o hello.gb hello.o
rgbfix -v -p 0 hello.gb

(just replace “hello.” with whatever you called your file.)

It should then compile and link, and your shiny new ROM will appear in the same folder, ready to be run in whatever emulator you like (provided that it runs GameBoy games, anyway).

And, we’re done here! I hoped you enjoyed reading this. It’s a cliché, but I had a lot of fun writing it. I’ve also put the full source code up on GitHub, so by all means take a look if you get stuck. A lot of it was also borrowed from the sample code John Harrison wrote for a course in GameBoy programming at Wichita State University – you can see more about that here.

Links

A course in GameBoy programming at Wichita State University.

Everything You Always Wanted To Know About GameBoy:
A complete GameBoy specification, including info about important memory locations, the CPU’s design, and definitions for the complete Z80 instruction set. Also available in slightly modified form as a PDF.

RGBDS tools and Vim syntax file

Example code

Hello, World!

It’s not particularly original, but I thought that this was the perfect thing to call the first post on this blog. For most programmers – or at least the ones who started learning in the 1980s or later – a program that outputs the words “Hello World” will have been the first program they write. It’s still the first thing I try and make whenever I’m starting to learn a new language, and I’m pretty sure I’m not alone in that. I’ll be coming back to this topic a bit later on, but first I wanted to give a little bit of background about why I’ve decided to start this blog off.

Last Friday, I took part in an event called the Mad March Hack. This was a 24-hour coding event at Platform Studios in Hull, for students and ex-students from the university, and organised by James Croft, who’s done a really cool write-up of the whole thing on his blog. I decided, for reasons that I’m not entirely sure of now, to try and produce a Game Boy emulator. Note the try in that sentence – I didn’t succeed in doing much more than reading a ROM and outputting some garbage to the screen. Still, despite this rather inauspicious start, someone was interested enough to ask me if I’d be keeping up development on it, and if there was anywhere that I’d be putting out updates on its progress. And that, right there, is when I decided: I need to get me a blog.

So, back to “Hello World”. Like I said, it’s pretty much been everyone’s first program since about 1978, when it was used as the first example in Kernighan and Ritchie’s book The C Programming Language. And, at this point, it’s been done to death. Googling around has turfed up examples in pretty much every language from Basic:

10 PRINT "HELLO WORLD"

to Brainfuck:

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

(By the way, if you can’t figure out what the hell is going on there, I don’t blame you. The Wikipedia page for Brainfuck has a pretty good explanation of it.)

so it’s kinda hard to show off anything that might be new to anyone. But, while

#include <iostream>

using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}

will always be kinda special to me as the first program I ever wrote, I thought I’d rather show off something a bit different. So, if you happen to have a Game Boy emulator handy (I used VisualBoyAdvance), then download and load up the following ROM:

hello.gb

Or, if that sounds like too much work, just look at the screenshot below:

hello

If you want to know more about how I made that ROM, then have a look at my tutorial about it, here.