Launching the Terminal app from Xcode on OS X with System Integrity Protection

If you occasionally use Xcode to create command line tools or applications, chances are that you’ve set up a scheme to launch those applications in the Terminal app from within Xcode, something like this:

Launch terminal

You then pass your app as an argument, like this:

App passed as argument

If you’ve recently upgraded your OS X installation to El Capitan you might have found Xcode is now refusing to launch the Terminal app and is giving you the message “Message from debugger: cannot attach to process due to System Integrity Protection”.

System Integrity Protection is a new security feature introduced in El Capitan. It is intended to stop malware from either modifying system critical parts of the file system or from attaching to system critical processes and injecting code.

On the whole, this is a good thing. Unfortunately the Terminal app is considered to be a system critical process so Xcode is no longer able to attach to it.

There are a couple of workarounds:

  1. You can disable System Integrity Protection. You’ll find details for this in the Apple documentation
  2. You can just build your app in Xcode and then launch it manually from the Finder.

However, both of these are hellish compromises to have to make. There is a third way. Xcode refuses to attach to Terminal because it’s an app that’s shipped with OS X. So the solution is to make it look like a user-installed app. Here’s how:

  1. Find the terminal app in Finder. It’s usually located at Applications > Utilities
  2. Copy it
  3. Paste the copy inside Applications (but outside of Utilities)
  4. Rename it, e.g. MyTerminal.app (This is important so you can easily identify that you are attaching to a copy and not the original)
  5. Now edit your scheme to launch this version of Terminal:
    Launch alternative version of terminal app

You should now find that your application launches quite happily again from within Xcode.

 

Posted in Application Development | Tagged , , , | Leave a comment

OS X Games from the Ground Up: Building a User Interface with NCurses (1)

You can see an index of all the posts in this series: go to index.

If you are starting from this point, you can download the starter files here: introducing_ncurses

In the previous post you learned how to link the NCurses and Panel libraries to the Hexapawn project and you were introduced to how windows and panels work in NCurses. In this part we’ll start using these features to build a text-based user interface for the game.

We could just build the windows we need manually, but since we will have quite a few different windows to build on this project, it makes sense to create some generalised functions to manage them. As this project will grow to be a lot bigger than either of the two previous games we’ve worked on, another thing we’ll do is start organising functional areas of the game into different files. Let’s start by creating a new file to hold our windows-related functions. With the project open in Xcode, open the File menu and select New > File…. In the dialogue window that appears, make sure OS X and Source are selected on the left, and then select the C File template on the right.

Hexapawn new file

Click Next. Name the file hexwindows and make sure that Also create a header file is ticked. We’ll learn what the header file is for a little later.

Hexapawn name new file

Click Next again. In the next dialogue window, just check that the proposed location for the file is the Hexapawn folder (you should see main.c already in there), and check that the file will be put into the Hexapawn Group and that Hexapawn is selected in the Targets section.

Hexapawn create file

 

If all looks well, click Create. You should now see two new files in the Project Explorer:

Hexapawn new files

Let’s move the NCurses initialising code into its own function. Open hexwindows.c and enter the following code:

You’ll notice I’ve taken the opportunity to add a couple more function calls to our initialisation code. Normally the characters you type as input are placed in a buffer and are not made available to the programme until the return key is pressed. Line 16, cbreak(), disables this behaviour so that characters are available to the programme immediately that they are typed. Line 18, keypad(stdscr, TRUE), causes special keyboard keys, such as function keys and arrow keys to be returned as a single value in the input stream. This will make it easier for us to implement our user interface because we won’t have to interpret the escape sequences that are normally generated by these keys.

OK, let’s try our new function out. Go back to main.c and replace  lines 12 to 15 with a call to our new function:

You’ll immediately get an error: Implicit declaration of function ‘initialise_curses’ is invalid in C99. What’s going on? Well the problem is the function is in a different C file, so main.c can’t see it. You’ll recall from the earlier parts of this series that we got around issues of function visibility by adding a function declaration to the top of the file. But which file should we add it to? We can’t add it to hexwindows.c because we’ve already established that main.c can’t see the contents of that file. We could add it to the top of main.c. That would work, but what would happen if we wanted to use that function in another C file that we create later? We’d have to add the declaration there as well.

The solution is to use something called a header file. A header file is a file that contains all the information, including function declarations, that you want to share with other parts of your programme. Let’s start the header file for hexwindows.c. Open hexwindows.h and add the following code:

 

Note that the lines beginning with # have been added for you automatically by Xcode. Don’t worry about what these are for now (we’ll come back to them in a future post), just be sure that any code you add to this file is placed after #define __Hexpawn__hexwindows__  and before  #endif /* defined(__Hexapawn__hexwindows__) */ .

Now go to main.c and add the following line, after line 7:

Note that when we are including header files that we have created, we use quotes rather than the angle brackets we’ve been using to include library header files. You should now see that the error has disappeared and the programme should build and run successfully.

What’s next? Well ideally we want to create another function that will create a game window for us. Let’s think about what that function should do:

  • It should accept the dimensions for the new window as parameters
  • It should create a new window to those dimensions
  • It should set the window up to accept special keys as input (e.g. function keys, arrow keys)
  • It should draw a border round the edge of the window
  • It should create a new panel and associate it with the window
  • It should return a pointer to the panel and the window

That all looks absolutely fine except for the last bit. How can we return more than one value from a single function? I’ll let you into a little secret here – there is a way of doing it, and we’ll find out what that is later on. But for now let’s explore a different solution.

You might recall from an earlier part of this tutorial series that we introduced the idea of indirection – referring to an object in memory by using using its address rather than its name. We used this when we wanted to modify an existing string in a function. We simply passed a pointer to the string to that function. The function was then able to access the string directly so it could modify it. So why don’t we take the same approach here? If we create a pointer to a window and a pointer to a panel outside of the function, we can simply pass the addresses of those pointers to the function so it can modify them directly.

Add a new function header to hexwindows.h that looks like this:

And add a new function to hexwindows.c that looks like this:

Woah! What’s the deal with those double asterisks? Weren’t we just going to pass through the addresses of the window and panel pointers? Well yes, but let’s think about what’s going on here. When we create a new window, e.g.

what gets returned to us is a pointer to the data for that window (in other words, the address of the data). If we were to pass that value directly to a function, e.g.:

what the function is getting is the address of the window data:

wrong_level_of_indirection

This is not what we want. We want our function to modify the pointer variable itself, not the data it points to. So what we need to pass to our function is the address of the pointer variable, in other words a pointer to the pointer variable!

right_level_of_indirection

 

Now that we have the address of the pointer variable in the function, how do we read or write the value inside it, for example, when we want to set it the address of some new window data we’ve just created? You would be forgiven for thinking we could just do this:

But this wouldn’t work, because this line is asking C to take a pointer to a pointer to some window data and turn it into an ordinary pointer to some window data:

wrong_level_of_indirection_2

 

But actually we want to modify the content of the pointer, and we can get to that content by using the asterisk operator in a slightly different way:

Which has this effect:

right_level_of_indirection_2

 

Don’t worry if you are struggling to follow this. As I’ve said before, pointers are the most difficult aspect of C to get to grips with, especially when you start dealing with multiple levels of indirection. Stick with it, and one day it will all just click into place. You will get plenty of practice during the rest of this series of tutorials. My advice is, if something doesn’t make sense, try drawing a diagram of what’s happening, like those above.

Let’s now go back to our new function and see what it’s doing. Line 27 is creating a new window and making our window pointer point to it. In line 29 we set the window up to accept special keys. In line 32 we create a new panel and associate it with the new window, we then make our panel pointer point to this panel. Finally in line 35 we draw a box around the window. Notice how we use the * operator everywhere we want to refer to the content of the pointer.

OK, so how do we use this new function? Go back to main.c and change the code that creates and displays the windows to this:

Note that we are using the address-of operator (&) to pass through the address of the window and panel pointers rather than their content. If you forget to include this operator, Xcode will complain, because it’s expecting a pointer to a pointer here.

In the next part of this series we’ll continue to build our interface by creating the first of our actual game windows. In the meantime, here’s a challenge for you. Like all the other main windows in the game, the game window, in which you play a game against the computer, will be 24 rows high by 80 characters wide and will be positioned at the top-left corner of the terminal window. It will have a border, and a title – “Hexapawn: Play a game”. You now know enough about NCurses to be able to build this window using the functions we have created so far. See if you can do it, and we’ll look at one possible solution in the next post.

Posted in C, Games, Programming Tutorials | Tagged , , , , | 2 Comments

OS X Games from the Ground Up (Volume 2): Index

This index explains what you’ll learn in each part of volume 2 of OS X Games from the Ground Up. It also includes download links for the starter files for each part of the project. This makes it easier for you to start, or restart, at a particular point without having to work through from the beginning. To start at any post other than the beginning, download the starter files from the link that is immediately before the post you want to start from.

Note that volume 2 assumes you are familiar with:

  • C variables and data types (including pointers)
  • Decision structures with if… then… else… and switch
  • Loops using while, do …. while and for
  • C functions (including passing arguments to a function and returning values from a function)
  • The main function
  • How to construct simple command line programmes in Xcode

If you are new to any of these topics, you might want to take a look at the index for volume one and start with one of the posts from that volume.

Hexapawn

  • Introducing the game we will be creating: Hexapawn

There are no starter files from this part.

Hexapawn – BASIC programme

  • Source code for the programme to be converted: HEXAPAWN.BAS

There are no starter files from this part.

Introducing the NCurses Library

  • Planning a text-based user interface
  • Linking additional libraries in Xcode
  • Using the NCurses library for text-based interfaces
  • Initialising and closing NCurses
  • Sending output to stdscr in NCurses
  • Creating NCurses windows
  • How windows are redrawn
  • Using the panels library to add z-order to windows

Starter files from the end of Introducing the NCurses Library: introducing_ncurses

Building a User Interface with NCurses(1)

  • Creating new C and header files in Xcode
  • Why we use header files
  • Multiple levels of indirection

Starter files from the end of Building a User Interface with NCurses(1): user_interface_1

Coming soon … Building a User Interface with NCurses(2)

Posted in BASIC, C, Games, Programming Tutorials | Tagged , , , , | 4 Comments

Review of HarvardX MOOC Introduction to Computer Science (CS50x)

CS50x, which is available through the EdX platform, is a self-paced MOOC based on Harvard University’s successful introduction to computer science and programming. The course consists of videos of the lectures given at Harvard, supplementary tutorial videos on specific topics, and problem sets.

The course is marked based on achievement in problem sets and the submission of a final project. It’s run annually, with a new version of the course made available at the start of each year. You can progress through the course at your own pace, as long as you complete all the problem sets and submit a final project by the end of the year.

Unless you really do have a lot of spare time, I would suggest allowing at least 15 weeks to complete the course – 12 weeks to complete the course material and an extra three weeks for your final project. So, if you are planning on starting the course any later than the beginning of September, it is probably best to wait and start the course at the beginning of the following year.

The problem sets begin using the C language, but later include problems requiring HTML and PHP. One of the nice things about the way these are set up is that you install a virtual machine running the programming environment in Linux. This means everybody on the course gets the same experience, regardless of the hardware they are using.

Problem sets come in two flavours – the basic problem set (which is the one that is graded), and an advanced version (which is optional). The advanced versions are fun to try, but they do not contribute to your final grade, despite requiring a significant additional time commitment. For that reason, I would suggest working through all the basic versions and your final project first and then going back and tackling the advanced problem sets.

One of the most appealing things about CS50x is that, although it’s a rigorous course, the teaching style is a lot less dry than similar offerings from other educational institutes. Lecturer David Malan and his team do a fantastic job of introducing the course material in a fun and engaging way.

This is a course you could quite happily take on without any prior programming experience, provided you are prepared to put the hours in. I can’t recommend it enough.

Posted in Education, MOOCs | Tagged , , | Leave a comment

OS X Games from the Ground Up: Hexapawn – Introducing the NCurses Library

You can see an index of all the posts in this series: go to index.

In the previous post we analysed the original BASIC programme, identified a few things we need to fix and noted several enhancements we could make.

Both of the games we’ve developed so far in this series have been text-based games that have run in a simple terminal window. This game will also be a text-based game but, unlike the previous two games, it will have a user interface.

Before we started coding our previous two games we made a flowchart to show how the game mechanics worked. When you are creating a game with a user interface, it’s also important to map out the interface before you start. My tool of choice for this sort of work is Omnigraffle, but pencil and paper work just fine. Here’s an example of a UI map for the version of Hexapawn we will be building:

hexapawn_interface

As you can see, your interface map doesn’t have to be a work of art, neither does it need to show every detail of every screen. What it does need to show are what elements will go onto each screen and approximately how they will be laid out.

Once you have your interface map, you can use it to walk through typical user journeys to make sure they make sense. For example, here the player starts at the main menu in the centre. From there the menu items will take them to different screens for playing a game (top left), browsing the current state of the AI (top middle), browsing the game history (top right), saving/loading AI and game history (bottom left) or viewing instructions (bottom middle). I’ve also shown how a dialogue window will look (bottom right).

OK, now that we know what we’re building, let’s get started. Open Xcode and create a new OS X Command Line Tool Application, as you have done for the previous games in this series. Make sure you select C for the language.

Before we can start coding, there’s a small change we need to make to the project. For the previous two games we were able to run and test the games using the output panel in Xcode. Now that we will have a user interface, that isn’t going to work. Instead of running the application directly we will need to run it in an external terminal window.

To set this up, go to the Product menu and select Scheme > Edit Scheme. Make sure that Run Debug is selected.

The Executable is currently set to Hexapawn. Open this list and select Other…. This will open a dialogue window for you to choose a different application. Find and select your Terminal application. On my machine, this was found at Applications>Utilities>Terminal.app.

Now we need to tell the Terminal app which executable to launch. Select the Arguments tab. In the Arguments Passed on Launch section, click the + symbol. In the text box that appears, enter the following:

${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME} 

Hexapawn edit scheme

These are placeholders that will cause Xcode to pass the build directory and filename to the Terminal app each time we run the Debug version.

To check that everything is working, click Close, then click the Play button on the toolbar. All being well, the application should build successfully, and you should see a terminal window appear that looks something like the one below:

Hexapawn test launch

If you see something else, go back and check you have followed all the steps correctly. Especially check that the Arguments Passed on Launch line is correct. If you don’t see a window at all, it might have opened behind the Xcode window – use cmd + tab to check. If you have configured your Terminal to be something other than the default size of 80×24 or the default colour scheme of black on white, you might find it easier to temporarily re-enable these defaults while you are working through these tutorials.

Note that to close an application launched in this way, you can’t just click the close button on the application window. Instead, come back to Xcode and click the Stop button. This will close the process, including any windows it has open.

OK, so how do we begin to build a text-based user interface that supports multiple windows and screens and positioning of text? Well we could try and build a system to do that from the ground up, but that would be an enormous undertaking. One of the key principles you should keep in mind as your programming projects become more complex is to avoid reinventing the wheel. Fortunately there is already a widely used C library for building text interfaces. It’s called Curses. In fact the latest version is called NCurses (for New Curses).

Luckily for us, the NCurses library is a standard part of OS X, so we don’t even have to download and compile it. We do have to let Xcode know that we want to link to it though. To do that, make sure you have Hexapawn selected at the top of the Navigator Panel. You should see the Build Settings in the main window. Select the Build Phases tab. Click Link Binary with Libraries to open that section and click the + symbol.

In the Search box for the dialogue window that appears, enter cur. You should now see a much smaller list. One of the items on that list will be libncurses.dylib. Select it and then click the Add button. Your screen should now look like this:

Hexapawn linked curses library

To see what NCurses does for us, let’s convert the default Hello World programme to work with the NCurses library. In the Project Navigator, select the main.c file, and change it to match the listing below.

Press Play to build and run the code. You should see a terminal window that looks like this:

Hexapawn hello world

The programme his displayed the text “Hello, World!” and then put a cursor on the following line. If you are just seeing a blank screen with a cursor, check that you changed the printf function to printw.

At the moment the programme is hanging around, waiting for you to press the x key. Do that now (if it doesn’t work, make sure caps lock is off), and the screen should clear to be replaced with a few lines of text ending with [Process Completed]. Remember that, even though our programme has ended, you still need to go back to Xcode and click the Stop symbol to close the process.

Let’s have a look at what’s going on in this new version of Hello World. In line 6, we are now including the header for the NCurses library rather than the usual standard I/O library. In our first two games, all our output was written to the stdout stream, which, as we saw, can be easily redirected to various places. NCurses takes over the terminal window and maintains its own structures for input and output. By default, output goes to a stream called stdscr. To initialise these, we use the initscr() function on line 11.  This sets the terminal to curses mode and clears the screen.

On line 14, we have replaced the normal formatted output command, printf, with NCurses own version, printw. These two functions work identically, except that printf directs output to stdout, while printw directs output to stdscr.

Line 17 does nothing except hang around waiting for the user to type a lower case x. Why do we need this? Try commenting out this line and running the programme again. You won’t see Hello, World! at all, just a few lines of text ending with [Process Completed]. This is because, when we end NCurses with the endwin() function on line 20, the stdscr output is lost and no longer visible. To see it, we need to keep the programme running until we are ready to end it. For now we are doing this by waiting for an arbitrary key press, but later we’ll provide a cleaner way for the user to exit the programme.

Uncomment line 17 and run the programme again to look at a couple of other features of the default NCurses output. You’ll notice that NCurses has placed a cursor on the screen. Try typing something, e.g. Hello yourself! (make sure whatever you type does not include the letter x). You should see something like this:

Hexapawn echo

NCurses conveniently echoes your typing to the screen. You might not want either of these features to be enabled for a game, Fortunately, it’s easy enough to switch them off, with these lines:

So far I’m sure you’re completely underwhelmed. It seems like we’ve used quite a few lines of code to do something we previously achieved with one line. Let’s redeem the situation by starting to use the power of NCurses. Suppose we want our Hello, World! greeting to appear in the centre of the screen? Change the programme as shown below:

When you build and run again, you should see this:

Hexapawn centered hello world

(Note that all the examples in this sequence of tutorials assume you have your Terminal app set to the default colour scheme (black on white) and size (80×24).)

What’s changed? Firstly, in lines  12 and 13, we’ve disabled the echoing of input and the visible cursor. In line 16 we’ve used a slightly different form of the formatted print function. This version, mvprintw wants two additional arguments –  y and x coordinates. It first moves the cursor to that location and then outputs the formatted string.

Two things to watch out for with all the NCurses functions are that they want the y coordinate first, then the x coordinate and these are relative to the top-left corner, not the bottom-left. If text does not appear where you expect it to on the screen, check you haven’t inadvertently swapped the y and x arguments and you are counting rows from the top down not the bottom up.

If positioning text on the screen was all the NCurses library did, it would hardly be worth the effort of using it. Fortunately it does a lot more, and one of its advanced features we’ll be taking advantage of is windows. In addition to stdscr, we can also create and send output to different windows. Let’s see how these work. Change your code to:

The function refresh() in line 14 redraws stdscr. Even though we don’t have anything on stdscr at this point we need it here because of an (ahem) “undocumented feature” of NCurses which prevents windows being properly displayed until stdscr has been updated at least once.

in line 17 newwin creates a new window. The arguments passed to this function are the window’s height, width, and the y and x coordinates. It returns a pointer to an area in memory that keeps track of the properties of the window and its contents. In a later part of this series we’ll explore how this works in more detail, but for now just accept that this WINDOW pointer, which we’re storing in the variable window1, is how you will access the window.

The box function in line 18 draws a box around the edge of the specified window. You can specify which characters to use to draw the box using the second and third parameters. Setting these to 0, as we’ve done, uses the default characters.

Line 19 introduces another new function, mvwaddstr. This expects to be passed a pointer to a window, the y and x coordinates and an unformatted string. It then writes the string to the specified window at those coordinates. Note that all the other coordinates we’ve used so far have been relative to the top left corner of stdscr. When we use functions that output to a window, coordinates are relative to the top left corner of the window, not the screen.

Any output you send to a window is written to that special area of memory we talked about, but you won’t see that output until you add the window’s content to the screen. This is done using the wrefresh function on line 20.

If you run this code you’ll see this:

Hexapawn first window

What happens when we add a second window to the mix? Add the following lines of code after the line that calls the wrefresh(window1);  function.

When you run the code again, you’ll see that part of window 1 is now covered by window 2:

Hexapawn second window

When two or more windows overlap like this, what you see in the overlapping area depends entirely on the order in which the windows are refreshed. You can verify this for yourself, by moving line 20 (wrefresh(window1);) so that it comes after line 25 (wrefresh(window2);). If you do this and run again, you’ll see that window 1 now appears in front of window 2.

Now add another wrefresh(window2); function call after the first two so you have:

So this should show window2, then show window1 on top of window2, and finally show window2 on top of window1, so the net effect is that window2 will appear on top right? If you run it you might be surprised to see that window1 is still on top:

Hexapawn window order

What’s going on? Well, whenever you write something to a window, NCurses marks that window as having been changed. Each time you call wrefresh for that window, it marks the window as updated and unchanged. So when it receives the second wrefresh call for window2, it looks at the window and sees that nothing has changed since the last wrefresh and decides there’s no need to redraw the window!

So what do you do if you want to draw window2 on top again, even if nothing new has been written to the window? Well there is a workaround. Add the following line of code just before the second call to wrefresh(window2);:

If you now run the code again you’ll see that window2 is back on top. The touchwin function marks the window as if it had changed. Now, when the second call to refresh happens, NCurses sees that the window needs to be updated and writes it back to the screen.

If you had to manage several different stacked windows, you can see that trying to keep track of which order they need to be refreshed in and which ones had been changed or not changed would soon become messy.

Fortunately there is a companion library to NCurses, the panel library, that is intended to take the headache out of exactly this sort of window management. Panels add a capability to give windows a precise depth order (also known as a z-order) and to draw them correctly based on this order.

You add this library in exactly the same way you did NCurses, but this time the library you need to add is called libpanel.dylib. With the panel library linked to the project, update your code to look like this:

In line 7, we are now also including the header for the panel library. In lines 17 to 21 we create window1, draw it and refresh it as before. In line 22 we create a panel for that window. In lines 24 to 29 we do the same for window2.

The routine to read the keyboard, in lines 31 to 44, still checks for the user pressing x to exit, but it now also checks for the s key being pressed to switch the order of the windows. The order variable, keeps track of which window is on top. If it’s 1, then window1 is on top, and if it’s 0 then window2 is on top. Line 41 swaps the order each time s is pressed.

The top_panel function in line 38 brings the specified panel to the top of the stack. The update_panels function in line 39, redraws all the windows according to the current order of the panels and do_update writes all these changes to the actual screen.

If you run this code, you can swap the order of the windows simply by pressing s. Note that the windows are redrawn correctly, even though they have not been changed since they were last drawn. When you get bored, press x to exit.

Now that you have a solid grounding in how NCurses works, in the next part we’ll start using it to build a user interface.

Posted in C, Games, Programming Tutorials | Tagged , , , , | 4 Comments

Review of Berklee College of Music’s Songwriting MOOC

Berklee College of Music‘s Songwriting is the third MOOC in the Modern Musician Specialisation on Coursera. Absolutely the best thing about this course is the instructor, Pat Pattison. In this six week course, he will transform the way you think about writing lyrics.

He covers a complete development model for songs, starting from using a box model to develop a concept, through rhyming schemes to optimising stressed and unstressed syllables to get exactly the effect you want.

What I liked about this course is that it uses a lot of examples, so you can see and hear the effect that each technique has on a song. One section that is particularly impressive and inspirational is a recorded masterclass in which Pat listens to a student’s song and helps her transform it into a much more effective piece just by making more effective use of rhyming and phrasing.

To get the most of out of this course, you need to participate. That will involve being brave enough to put your work in front of other students via Soundcloud, or a similar service. I am not a great singer, so I was nervous about singing my own work and letting other students listen to it. However, most students understand that they are critiquing the songwriting and not the singing/playing, and I found that the peer review environment was very supportive and encouraging.

Because, in most weeks of the course, you are expected to do some work on a song, you will want to ensure you set aside enough time each week to do the work, record  and upload it. If you are able to do that, I can thoroughly recommend this course for musicians of all levels of experience.

 

Posted in Education, MOOCs, Music, Production, Theory | Tagged , , , , , , , | Leave a comment

A simple JavaScript singleton pattern

There are a number of different approaches that can be taken to creating singleton patterns in JavaScript – this one is both simple and effective and supports lazy initialisation.

The following code shows typical usage of constructor functions:

#1: We define a constructor for the Vehicle object.

#2: We use this constructor to instantiate two new Vehicle objects. The javascript new operator will create an empty object and pass this to the constructor, which can then reference it with the this keyword. This is used in the Vehicle constructor to establish two properties of the new object. One of these properties is then updated by each instance of the Vehicle object.

#3: However, the constructor function is not obliged to make use of the object created by new, it can return a completely different object. This is what the Car constructor does. It ignores the object created by new and instead returns an instance of the Vehicle object.

#4: The car variable here is calling the Car constructor, but it will end up referencing a Vehicle object.

#5: The output of these statements will demonstrate that all three objects are indeed Vehicle objects:

Screen Shot 2015-01-13 at 21.48.21

 

Our singleton pattern can make use of this ability of a constructor to return an alternative object by returning an existing instance, if there is one. So how does the constructor know whether there is an existing instance and how can it return it?

To achieve this we will make use of a little-known and little-used feature of JavaScript functions – their ability to have properties. Consider the code below:

#1: This is same constructor function as before, except that it now has an additional line that creates a property of the function.

#2: Here we instantiate a Vehicle object. When the constructor runs, the new object will be populated with the objectString and serialNo properties. The funcprop property will not be part of the object, but will be a property of the constructor function.

#3: The output from these statements will show that the Vehicle object has no access to the funcprop property, which is accessed through the function name:

Screen Shot 2015-01-13 at 22.08.17

So, now we can combine these two features to create an effective JavaScript singleton pattern that supports lazy initialisation:

#1:  The constructor for our Singleton class first checks for the presence of it’s own property called instance. If this property does not exist (which will be the case the first time the constructor is called), then the constructor simply sets this property to the object created by new. On any subsequent invocation of the constructor, the property will exist so the constructor ignores the object created by new and returns the existing object instead.

#2: Here we call the constructor for the first time and add a new property to the object. For this invocation, a new object will be created and this object will be set in the constructor property called instance.

#3: Here we call the constructor for the second time and add a second property. For this invocation, the existing instance will be returned.

#4: The output of these statements demonstrate that both instance1 and instance2 reference the same object:

Screen Shot 2015-01-13 at 22.29.34

Posted in Application Development, JavaScript | Tagged , , , , | Leave a comment

StackHack – A game prototyping project: part 4 – moving to production code

In the previous parts of this series I showed how to develop a concept with a paper prototype, how to transition to the first digital prototype and how to further develop and enhance that prototype. In this part I’ll discuss making the transition to production code.

If you’ve taken your prototyping to the point that you’re happy that you have a project you want to progress with, then it’s time to make the leap from your prototyping code to your production code.

A decision you have to make now is whether there is any part of your prototype that could be repurposed for your production version. There are a number of factors that are going to affect this decision. Clearly if you’ve chosen to build your prototype on a different platform, or using a different technology from the one you intend to use for your target system then you have no choice but to start from scratch.

If, as is the case with StackHack, your target platform and technology is the same as your prototyping platform and technology then you might be able to salvage something. There are three important considerations here:

  1. Don’t be concerned about throwing your prototype code away – that was always going to be a possibility
  2. You should never code your prototype with reusability in mind – quick and dirty are the watchwords here
  3. Only repurpose prototype code if it’s going to be quicker and more productive to do that than to start from scratch

Having said all that, there is no point in throwing the baby out with the bathwater, so if there is stuff that is robust enough to reuse and which will save you some production effort and time then go ahead and use it.

That was certainly the case with StackHack, I was able to create my production code by refactoring a lot of the prototype code, which was a quicker process than starting from scratch.

You can play the version with production code. In case you have not read any of the earlier posts, please note you will need an up-to-date browser on a device with a keyboard. The controls are:

  • Move left: left arrow
  • Move right: right arrow
  • Jump: up arrow
  • Pick up/drop a present: space

Screen Shot 2015-01-07 at 15.17.33

Ostensibly, this version looks very similar to the second prototype, but of course a lot of the work (refactoring and re-creating code) has gone on behind the scenes.

The other thing you are going to want to do at this stage, is add the aspects of the game that are not fundamental parts of the gameplay, but add polish. One of the first elements I added was an animation system for the main character.  Rather than have a static character, the player character now shows the relevant frame from an extended sprite sheet, as shown below.

character

 

Note that I am still using what are often euphemistically described as “programmer graphics”. The point it which it is worthwhile starting work on production-quality art, whether it’s to be created by you or somebody else, is once all your animation code is in place and is working well.

The other thing you should note about this sprite sheet is that the character is only ever facing in one direction. Flipping a character sprite about its vertical access is something that can so easily be done in code, it’s rarely worth the effort of adding these additional frames to your sprite sheet.

The other thing you’ll notice about this version is that the cannon is now animating smoothly between its firing positions.

With all the main game mechanics completed, the next stage is to start work on art, audio and level development, and I’ll discuss that in the next part.

Posted in Games, HTML5, Prototyping | Tagged , , , | Leave a comment

StackHack – A game prototyping project: part 3 – developing the digital prototype

In the previous parts of this series I showed how I used paper prototyping to develop a concept for an HTML5 Christmas game called StackHack. I then showed how I transitioned the paper prototype into a digital prototype. In this part I’ll show how the initial digital prototype can be further developed.

Once you have played around with the initial digital prototype for a while, and ideally got some other people to play with it as well and give you their feedback, you should be in a position to decide whether to progress with the concept or not. If you decide not, then it’s time to archive the project materials and move on to something new.

If you do decide to proceed, then the next stage is to start adding more of the elements from your original design to the game. Again, it’s important to remember that you are not trying to create a finished game at this point – this is still very much a prototyping stage, so don’t accelerate into a full-on production. Instead you should prioritise the remaining features of your concept and introduce them to your prototype one at a time.

After you’ve introduced each feature, play with the prototype for a while and ask other people to play it and give you feedback. Ideally you’ll use a mixture of people who have played earlier versions of the prototype and people who are completely new to the game, as you will get a slightly different perspective from each of these groups.

Spend some time tweaking each new feature as you add it, before you move on to the next one.

You can play a later prototype of StackHack. Once again, you will need an up-to-date browser on a device with a keyboard. The controls are:

  • Move left: left arrow
  • Move right: right arrow
  • Jump: jump
  • Pick up/drop a present: space

Screen Shot 2015-01-07 at 09.26.20

The first thing you’ll notice that’s changed is that I’ve introduced a level selection mechanism. Having the ability to play different levels at this stage allows me to focus each level on a different feature of the game.

One thing to note is that the level selection screen, like the game, uses ugly old un-styled HTML. Again, this is a conscious decision – I don’t want play testers distracted by graphics on the level selection screen – it should be purely functional at this point.

Screen Shot 2015-01-07 at 09.30.30

 

The first new feature I added to this prototype was the cannon that fires out the presents. You can see this at the top-centre of the image. The orange present half-way down the right side of the screen has just been fired out. One thing you should notice when you play the prototype is that the cannon doesn’t move smoothly between its firing positions, it goes directly to each one. Although it would look nicer to have the cannon moving smoothly, it is not central to the game play, so it’s not something that should be included in the prototype.

The next thing I added was a timer. You can see the remaining time shown in the top-right corner of the screen. Again, the timer uses plain, un-styled HTML text.

Screen Shot 2015-01-07 at 09.40.22

There’s also a mechanism to end the game and return to the levels screen when the timer reaches zero.

Screen Shot 2015-01-07 at 09.42.46

 

The third feature to be added was to have different types of presents. Again note how I’m denoting these with simple colours at this stage rather than fancy graphics. Hand-in-hand with this was introducing guides that only accept certain types of present. In the image above, the guide with the black outline will accept presents of any colour while the other guides will only accept presents of a matching colour.

Screen Shot 2015-01-07 at 10.10.51

 

And, of course, I also needed to update the check for when a level is completed successfully so that it also enabled a return to the levels screen.

Screen Shot 2015-01-07 at 10.20.07

 

Another feature from the original concept that was added in this prototype was the ability to have platforms on certain levels. Note that in this level the guides are placed on one of the platforms, forcing the player to stack presents to create a temporary mid-level platform. Once again, note that the platforms are rendered using only the debug graphics capability of Box2DWeb.

Screen Shot 2015-01-07 at 10.39.12Screen Shot 2015-01-07 at 10.38.28

 

As well as introducing additional features at this stage, you’ll also want to tweak earlier mechanics based on the outcome of your previous prototypes. The image on the left is from my first digital prototype and shows that, when presents were carried in this version, they were held rigidly in front of the player character. A side effect of this is that the rigidly held present can end up balanced on top of another present, leaving the player character hanging in mid-air, as shown in the image. To fix this, the code for the subsequent prototype was changed to allow the held present to rotate a little. Now, when the held present lands on top of another present, the player character’s weight will pull them down, the held present will rotate upwards and both objects will slide off the other present.

At this stage of the process you’ll want to play test your prototype thoroughly to decide whether this is something that is worth taking to a production stage or if it should be scrapped. Even if you do decide to move forward, you’ll probably want to remove features that aren’t working so well, add others to fill perceived gaps in the experience and tweak those you are keeping so they work as well as they can.

Your criteria for deciding whether to move forward or not will depend on what’s at stake. If you are trying to create a commercial-quality game that is intended to be a source of revenue, then your main criterion is probably going to be “is this something that I think people will be prepared to part with their hard-earned cash for?”. If, like StackHack, the game is more of a personal project, then your criteria might be questions like, “do I think this will provide my family, friends and colleagues a few minutes of amusement?” and “is this a project that is interesting for me to work on and stretches my skills?”.

If you do decide to move on, now is the time to make the transition to production code, and I’ll cover that in the next part of this series.

Posted in Games, HTML5, Prototyping | Tagged , , , | 1 Comment

StackHack – A game prototyping project: part 2 – digital prototyping

In part one of this series I introduced my prototyping project, a Christmas game called StackHack, and showed how early design ideas were worked out using a paper prototype. In this part I’ll explain the transition from the paper prototype to a digital prototype.

The first decision to be made when moving to a digital prototype is “what platform should I use to create the prototype?” In some cases the prototyping platform will be the same as the final target platform, but that’s not always the case. For example, if you were creating a console game, you might choose not to develop your initial prototypes on that console. Instead you might choose to develop an HTML5 prototype or make use of a simple game development engine as a prototyping tool. Generally you will want to choose a prototyping platform that will enable you to very quickly create and test the ideas you worked out during the paper prototyping stage.

In the case of my game, I wanted to meet these criteria:

  • The game should be accessible to as broad an audience as possible
  • The development should not require any investment beyond my time and the software and equipment I already had to hand

For this reason I chose HTML5 as the ideal target platform, because the game could be played by anyone with access to a recent browser, and because HTML5 does not require any specialised tools other than a text editor. (Although in this case I opted to use Adobe Dreamweaver as I already had access to this tool).

I decided that HTML5 would also be suitable as a prototyping platform, both for the reasons listed above and also because I have a good knowledge of HTML, CSS and JavaScript, so I could get a prototype up and running quickly.

Once you have made a decision about a prototyping platform, the tendency is to get straight down to work on the fun stuff – programming a prototype. But this is invariably a mistake. Remember that the key aims of any prototype is to get game concepts up and running quickly so you can evaluate if they work and modify or discard them if they don’t. Since speed is one of the key concerns, it’s important to avoid reinventing the wheel. Instead ask yourself – are there any ideas or tools out there that I can make use of to get me closer to my end goal without any significant effort on my part.

As part of my approach to this project I began by consulting a book on HTML5 game development – the excellent Pro HTML5 Games by the very talented Aditya Ravi Shankar. In his book, which I highly recommend if you are interested in HTML5 games development, Aditya proposes a game system based on two very popular libraries:

  • The ubiquitous jQuery, which makes it much easier for JavaScript programmers to access the browser’s document object model (DOM)
  • The Box2DWeb physics library, which is a JavaScript port of the excellent Box2D C library (the thing that does all the hard work behind the scenes in Angry Birds and hundreds of other great games).

Between them, these two proven libraries do a lot of the hard work for you to give you a basic engine, leaving you to focus on creating the mechanics for the game and saving you a lot of time.

There are three other common mistakes with digital prototyping. The first is to try and squeeze every aspect of your concept into the first prototype. Not only will doing this take a long time, but if the fundamental concept just doesn’t work well, then you’ve wasted a lot of effort on something you are just going to discard.

The second is to try to create reusable, production-quality code. Again this is unnecessary effort on something that may well be discarded, so it should be avoided. Focus more on getting the prototype working quickly and don’t worry so much about the quality of the code at this stage. If you decide to move forward after the prototyping stage, you can either rebuild or refactor your code at that point, when the effort will be worthwhile.

The third is to create nice artwork for the prototype. Again this takes a long time, and again it might be a wasted effort if you end up discarding the prototype, but there’s another very good reason for doing this. When you come to play test your prototype, you’ll find that testers are easily distracted by visual aspects of the game, and their response will be affected by how much they like or dislike your art. What you really want them to be focused on at this stage is the gameplay, so it’s best to keep your prototype art as plain and distraction-free as possible.

You can play my first digital prototype. You’ll need to use an up to date browser on a device with a keyboard. The controls are:

  • Move left: left arrow key
  • Move right: right arrow key
  • Jump: up arrow key
  • Pick up/drop a block: space

Screen Shot 2015-01-05 at 10.44.14

As you can see, this first prototype has just a single level that focuses on the central mechanic of being able to pick up and carry presents and drop them onto the guides. For this initial prototype, I chose to exclude the other elements of the game, such as the cannon, platforms and guides that require specific presents. In fact there aren’t even different types of present in this early version. Making the first prototype this focused allowed me to concentrate on how well the core mechanic worked without being distracted by other features.

You’ll also notice that the graphics in this version are minimal to say the least. In fact most of the graphics in this version are generated by the box2D library; the only graphics that I’ve added are the static stick man and the red box that shows where presents have been successfully locked in guides.

Even though this prototype is very primitive, it enabled me to establish that the core concept worked and was worth proceeding with, and to tweak aspects of the core mechanic, e.g. character movement, picking up and placement of blocks, etc.

At this stage you might well decide that the core concept isn’t strong enough and scrap the prototype. In this case you will at least have the consolation of knowing that you reached that decision without having expended an inordinate amount of effort.

Or you might decide to move on to the next stage, which is to incrementally introduce other game elements to your prototype, and I’ll cover this in the next part.

 

Posted in Games, HTML5, Prototyping | Tagged , , , | 2 Comments