Thu
Apr 2nd

Let’s Make a Game

This tutorial series will show you how to make a game.  The game will be:

  • A version of Snake
  • Cross platform (Windows, Mac, Linux)
  • Written in Ruby

Please remember to visit this article on our site rather than in your feed reader to get the code examples.

Cross Platform Games

There aren’t many ways to easily write cross platform GUI applications, let alone games.  Rather than use Adobe Air or a similar web-based technology, let’s use Shoes.

Shoes provides a rich toolkit for developing graphical software for Windows, Mac OS and Linux.  I’ll be working in Mac OS, but I’ll keep the code simple and portable.

Getting Started

Download Shoes for your platform from the Shoes download page.  Unpack the application and double-click it to run.  Click Help, then Console to open the console.  This is where error messages are displayed.

Here’s what you should see:

Typical Workflow in Shoes

When I write software with Shoes I go through the following steps:

  • Sketch a basic interface
  • Look at the Shoes Manual for ideas about how to implement the interface (there’s a lot of built-in functionality)
  • Think about the classes my code will need
  • Create a basic script and load it in the Shoes app (File, Open)
  • Display the console (Help, Console)
  • Work on the code, and re-open the file each time

Snake’s Interface

Snake is a game of squares: each square has a property.  Some make the snake longer, and some make it crash.  The movement of the snake is interesting: the head moves along and each block takes the position of the next block along the snake.

User input is received through keyboard commands: up, down, left and right.  We’ll use the arrow keys to make this easy.

Our game will need:

  • A “game item” class to represent the blocks in the game.  This will have an x and y position and some graphical attributes.
  • The snake itself: we’ll need to know where the snake is, how long it is and how many segments it has.
  • A snake segment class: this will probably be similar to the block class.
  • A main loop where input can be received and drawing operations fired off

Basic Layout

The previous requirements suggest the following structure:

That looks simple enough, but if your Ruby is a little bit rusty (or if you haven’t learned it), just follow along and try experimenting with the final example at the end.

Keyboard Input in Shoes

Shoes lets you receive keyboard commands in keypress blocks.  It also gives friendly names for many keys, so arrow keys are just up, down, left and right:

Main Loop and Animation

When handling the main loop’s animation, we can’t just use a loop.  This will cause Shoes to hang.  Instead, use a call to animate with the number of frames per second.

Combine this with the instructions for moving the snake and you get:

Snake Movement

The snake’s direction changes when the player presses the keyboard.  Direction can be modelled with a positive or negative value for X and Y:

Notice that this ties in with the names for the keyboard directions very neatly.

Each segment of the snake must be moved: the snake never stops.  That means for each frame of animation we need to:

  • Loop through each segment
  • Move the first segment on according to the current direction
  • Move the last segment to the next segment’s position, and repeat for each segment

In Ruby this algorithm can be written as follows:

The segments of the snake are reversed, looped through, and each segment’s position is updated to the next segment’s position, except the first.  The first is updated based on the current direction.

Shoes App Blocks

By adding some basic drawing commands and sensible defaults to each class’s initialize method, a basic snake game is almost ready.  The only thing missing from this picture is the application object.

As I explained earlier, Shoes apps are created inside Shoes.app blocks.  This allows you to say “rect” to simply draw a rectangle: you don’t need to say Shoes::App.rect like a typical API.  This means that to access rect within your Snake class you need to pass around a reference to it.

In my final example, look for references to the app object: it’s initially passed to the Snake class by using self (because it’s passed from within the Shoes.app block).

Final Example (for Part 1!)

Create a file called snake.rb and load it from Shoes on your Mac or PC.  The result will let you move a snake around, and it will look like this:

Comments (View)
Wed
Apr 1st

Introduction to OpenLayers

This is the third part of my open source mapping series.  See Part 1 for an overview of open mapping technologies, and Part 2 for details on running OpenStreetMap.

In this part I’m going to explore the basics of OpenLayers.  OpenLayers allows you to put a dynamic map on any web page, and displays map tiles loaded from various sources.  It can also draw vector shapes on maps, and plot markers.

Getting OpenLayers

Download OpenLayers from here: http://openlayers.org/download/.  Make sure you get the version with documentation: OpenLayers-2.7-withdocs.tar.gz.  This version includes API docs, loads of examples and various tools and scripts.

Displaying the Map and Controlling Position, Zoom

Note: These examples might not show in your feed reader.

To display a map, create an OpenLayers.Map, and a WMS for the tiles:

Notice that I’ve used new OpenLayers.LonLat(1, 50) with map.setCenter() to zoom into Western Europe.

Displaying Markers

Markers must be displayed on a layer, and their size, position and icon must be provided.  Markers can be attached to mouse click events, and displayed with different colours and opacity.

Distribution Examples

The examples in the OpenLayers download include:

  • Showing multiple markers quickly using a data text file
  • Using Flickr, GeoRSS and JSON to show data on a map
  • Using different tile sources (Yahoo! for example)
Comments (View)
Tue
Mar 31st

Introduction to Building Apps with OpenStreetMap

OpenStreetMap is an open source initiative that offers similar technology to Google Maps.  To really get the most out of OSM you should start by running the server locally and checking out their code.

Running OpenStreetMap

The frontend for OpenStreetMap is a Ruby on Rails application.  OSM refers to this as The Rails Port, and they have detailed documentation for installation.

It depends on RMagick for generating graphics, which means you’ll have to install ImageMagick to get it working.  This can be difficult on some platforms — if you’re using Mac OS I recommend installing ImageMagick with MacPorts.

Code is distributed using Subversion, and can be downloaded with the svn command:

svn co http://svn.openstreetmap.org/sites/rails_port

You’ll need to edit config/database.yml to set up a database.  It’s probably best to use MySQL rather than sqlite because it’s the one OSM recommend, and some databases don’t provide features geocoding software often requires.

Next, rake db:migrate and if you’ve got the required gems installed it should set up the database for you.

If any gems are the incorrect version, install them using the -v flag, for example:

sudo gem install -v=0.9.93 composite_primary_keys

Once the database migrations have run, edit config/environments/development.rb and add:

ENV['RAILS_ASSET_ID'] = ''

Next, start script/server and visit http://localhost:3000.

Running a Tile Server

The Rails app uses tiles from openstreetmap.org.  It’s possible to run your own tile server instead: detailed instructions can be found in Build Your Own OpenStreetMap Server.

Embedding the Map

You could edit a view in the Rails app to make a suitable page for an iframe, similar to this article: Creating Easy Map Embedding.

Web API

The Rails app has several APIs: OpenStreetMap APIs.

Comments (View)
Mon
Mar 30th

Open Map Technology

Google Maps is an incredible piece of technology.  The API are easy to learn and naturally enhance many kinds of projects.  However, there are several reasons to use other technologies: special agreements are required for corporates, high traffic sites and private sites.

Google’s terms and conditions might not always pass your company’s legal department.  In cases where you want full control over your geographical services, Google Maps is tempting but not always the best option.

There are realistic alternatives.  In this article I’m going to explore a selection of open mapping technologies and geographical data.  In the next part I’ll give you some code examples.

OpenStreetMap

OpenStreetMap is an open source project largely based in the UK.  Their initiative is focused on collecting geographical data.  They have a guide explaining how to gather data with GPS technology and add it to their maps.  Their FAQ explains why they’re building the service:

Geographical data (geo data) is not free in many parts of the world, like the United Kingdom. Generally these places have given the task of mapping to various government agencies who in return get to make money by selling the data back to you and me.

Geographical data like postcodes must be licensed in the UK, which obviously stifles innovation and seems like a needless bureaucratic layer over something which we surely all own.  Nevertheless, projects like OpenStreetMap aim to side-step this by encouraging the community to collect data.

Free The Postcode

Free The Postcode aims to collect GPS co-ordinates for UK postcodes.  There’s an iPhone app to make collecting data easy.  The resulting data is placed in the public domain and can be accessed here: http://www.freethepostcode.org/currentlist as a space separated file.

OpenLayers

OpenLayers is an open source JavaScript library that provides the interface for maps and methods for geographical data access.  OpenLayers even lets you build single file maps so you can create simple map navigation for your website.

GeoNames

GeoNames provide open data for countries, cities, time zones and more.  The data sets include ISO country shortcodes, alternative names and GPS co-ordinates.

The licensing is creative commons:

cc-by licence (creative commons attributions license). You should give credit to GeoNames when using data or web services with a link or another reference to GeoNames.

There’s a download server and web service.  For more details see the export documentation.

Comments (View)
Sat
Mar 28th

Quite Useful Weekly Roundup

This week we published a summary of all our features over the past few months.  There’s everything from media centre tips to hacking websites with screen scraping.  We also tracked the memory performance of several popular Twitter clients — useful information if you leave Twitter in the background all day!

We also reviewed Streamy, a new social networking site that brings together your other networks into one place.

Here are my picks from our Twitter posts this week.

Designer and Developer

Styleneat is a handy little tool for tidying up CSS.  It works with uploaded CSS, pasted or from a URL.  It adds syntax highlighting in the results as well.

Getting Ready for Core Data in 3.0 is a list of Core Data resources for iPhone developers.  Apple’s adding Core Data support in the new iPhone software, which will make managing data easier.  It will be familiar to existing Cocoa developers.

Building OAuth Compliant Twitter Apps in Ruby explains how to use OAuth in your Ruby projects.  Twitter applications no longer need to store usernames and passwords, so it’s worth reading if you’re building something in this area.

Social

Wikirank shows trends on Wikipedia.  In case you’re wondering how they can track how popular Wikipedia pages are, they explain it all on the Wikirank About page:

the charts on Wikirank are based on logs from Wikipedia’s HTTP Squid proxy servers. That means every single page load is recorded, whether initiated by a human with a browser or a Web spider crawling through

iStopOver is a cool idea: it provides a way of finding homes with rooms to rent when you’re travelling.  I thought it was US only at first, but they’ve got country controls at the top right of each page.

Tweleted helps you find deleted tweets.  It actually works, which means you can now find each other’s spelling mistakes.

Comments (View)
Fri
Mar 27th

Review: Streamy

Streamy aims to bring your social networks together in one place, and give recommendations based on your “personal interest profile.”

There’s a video that summarises Streamy’s main features: About Streamy.  The track in the video is Iz-Us by Aphex Twin — they’ve clearly got good taste, but I hope they’ve got permission to use that music!

Setup

Streamy’s an early adopter of all the safe ways to interface with social networks.  OAuth is used for Twitter, which means Streamy doesn’t need to know your username or password.

Setting up the connection between Streamy and Twitter looks like this:

Easy, and no password required.

Customisation

Each page is displayed as a set of panels, with controls for managing columns and drag and drop reordering.  Removing a panel is slightly awkward; it must be dragged to a cross icon at the top-right of the page.  I understand that they want to keep the interface simple by not showing a delete/remove icon on each panel, but it doesn’t seem as intuitive.

Apart from that minor quibble the interface is intuitive: status updates automatically load more when the bottom of the page is reached and drag and drop works well for widget management.

Basic Usage

Streamy displays an overview of your social networks in one place.  I set up Flickr, Twitter, Facebook and FriendFeed.

This lets me post status updates to multiple social networks:

Notice that Streamy also counts as a social network in their list.  Streamy features both friends, chat and group chat, which means you can find and add people within Streamy.

Recommendations

The home page displays news recommended for you, based on your profile.  It’s picking up a lot of geeky stuff for me, which is about right to be honest:

It doesn’t seem to offer recommendations for friends, but seeing as the service has built in social networking features I expect they’re working on this.

Social Network Integration

Each social network is represented in-depth: Twitter has the standard features you’d expect: direct messages, @replies; even trends and search.  Flickr also works well, showing friends activity and custom search widgets.

Conclusion

Streamy’s going to make sense to a lot of people.  It’s a richer experience than sites like Ping.fm, without being bloated.  It’s more focused than Netvibes: integrating with social networks rather than generic widgets makes the interaction between networks more natural.

I’d like to see it support multiple accounts for each service (those of us with business/personal Twitter accounts are always asking for this), and perhaps colour options or themes.

Comments (View)
Thu
Mar 26th

Quite Useful Features

We’ve published several features since the start of Quite Useful, so I’ve added a sidebar on the blog to make it easier to find them.  Here’s a guide in case you’ve missed any.

Backups

The backup series started off with tips on how to backup your social network content.  We also featured guides on iPhone backups, online backups (with a mini Automator tutorial), time machine, and videogame systems.

Media Centre Hacking

I’ve hacked most of my games consoles into doing a lot more than just playing games.  That inspired me to write up my (legal) tips for getting the most out of your games consoles for media playback.  We’ve featured Wii and PS3 tips, and are waiting for a 360 followup (I don’t own one).

We also published a guide to playing back video podcasts on your TV.

Firefox Sync

Firefox add-ons make syncing fairly easy, and in some cases without relying on a third-party service: sync bookmarks and passwords with our guides.

Screen Scraping

This was our most recent feature: Part 1, Part 2.

Future Tutorials and Guides

Alex, Quite Useful’s main contributor and editor, is a full-time Ruby, Mac, and iPhone developer.  If you’d like to see tutorials in these areas please let us know, especially as another main contributor Ric is also a Ruby developer.

And send us your web, Mac, iPhone, and Windows apps to review!

Comments (View)
Wed
Mar 25th

Screen Scraping: Cookies, Headers

This is a follow-up to yesterday’s article, An Introduction to Screen Scraping.  I’m going to show you the basics behind reverse engineering headers and cookies.

Note: These posts might not display the examples in your feed reader, so try visiting Quite Useful in a browser to see them.

HTTP POST

Some sites only accept a POST for a particular form.  The example I used yesterday used the Ruby library, open-uri, to perform a GET request.  Whilst this is very clean, it’s also less flexible than the basic HTTP libraries that come bundled with Ruby.

Here’s an example of a HTTP post:

This attempts a login on a service I run; I don’t mind if this example is run.  The code itself is simple:

  • The uri library is used to manipulate a URL, grabbing the hostname and path as required
  • net/http is used to create a HTTP POST request with custom headers
  • The full response is displayed with a message that determines the outcome of the login attempt

Cookies

Many sites use cookies to prevent cross site scripting attempts, or just to make life difficult for us scrapers.  Some people are probably using Microsoft tools to create sites and don’t even know what’s going on, so don’t get too angry if a site is hard to manipulate.

Let’s use cookies with the previous example to actually login and request a document from Helipad.  You’ll probably want to create an account to test this out yourself.

This example fetches the create document page and tests the result for an ID that I know appears on that page.

  • Note that http.get2 has been used to pass headers to the server
  • The cookie (session ID in this case) was captured from the initial login POST and has been used in the GET request
  • If the Preview ID is found in the page, then the create document page has been successfully fetched while logged in

Reverse Engineering Headers

Sometimes headers must be cloned.  This can be extra work, but Firebug makes it easy.

  • Enable Firebug for the site you want to reverse engineer
  • Fill out the form you’re targeting and submit it
  • In Firebug, click Net then HTTP and look at the Request Headers
  • Compare this against the headers you’re sending in your script

You might find mechanisation libraries that streamline some of this work, but once you’ve got working code manipulating POST, headers and handling cookies, most sites can be successfully scraped.

Comments (View)
Tue
Mar 24th

An Introduction to Screen Scraping

Screen scraping is a technique for using software to grab data from websites.  Many websites we use everyday are poorly designed and difficult to use, just look at most Internet Banking sites.  Fortunately, programatically accessing information on these sites can be relatively easy.

Toolkit

The essential elements of a screen scraper’s toolkit are:

  • Firebug, the Firefox plugin (Safari’s Web Inspector is also good)
  • A scripting language (I’m going to use Ruby here)
  • A flexible XML parser (I usually use hpricot)
  • Libraries for dealing with HTTP

Typical Workflow

  1. Identify the form or GET parameters you want to manipulate
  2. Identify where the results appear in the page using Firebug (right-click the element and select Inspect Element)
  3. Attempt to trigger the resulting page successfully
  4. Attempt to process the results and extract the data

Some sites use cookies which will make step 3 an exercise in patience.  Firebug makes reverse engineering pages and HTTP requests easy.

Simple Example

Let’s scrape a shopping site for search results.  I want to get the prices of search results from Play.com.  Play.com works like this:

  1. Search uses HTTP GET and a searchstring parameter - let’s use ruby’s open-uri library to make this easy
  2. The results are in div.info HTML blocks with h5 or h6 headers - hpricot will fetch these variables with a CSS selector: “.info h6”

Further Reading

There are dedicated scraping libraries out there: try scrubyt for starters.  There are also loads of Python and Perl libraries for scraping: many Ruby libraries are derived from Perl’s WWW::Mechanize.

Comments (View)
Mon
Mar 23rd

Twitter Client Memory Usage

I run a Twitter client in the background permanently, and I started to wonder how much memory it used.  I heard TweetDeck uses a lot of memory, so I decided to compare the top Mac clients.

I set the clients up with the same account which has these stats: 140 following, 158 followers, 744 updates.

Each of the clients was running for 12 hours.

EventBox

EventBox currently costs $15 and is made by The Cosmic Machine LLP based in England.  I use it as my main Twitter client.  It also works with Facebook, Flickr, Google Reader, feeds, and Reddit.

Memory usage: 78.77 MB

CPU: 0.1%

Conclusion: EventBox is safe to leave in the background.

TweetDeck

TweetDeck is free and uses Adobe Air.  If you haven’t tried it before, it has a rich set of features that create a dashboard-like overview of your Twitter network and related activity.

Memory usage: 115.95 MB

CPU: 2.0%

Conclusion: CPU occasionally spiked and memory usage seemed to creep up over time, but TweetDeck is currently more stable than it has been.

Twhirl

I set up Twhirl with one account.  Like TweetDeck it uses Adobe’s Air, so it has a larger footprint than native Mac software like EventBox.

Memory usage: 103.70 MB

CPU: 2.8-8%

Conclusion: Twhirl is relatively well behaved.  I didn’t find the memory usage to spiral out of control, but the CPU usage isn’t as good as other clients.

Twitterific

Twitterific is incredibly popular and has been around for a long time.  It’s a solid and simple client that hasn’t crashed for me since I bought it.

Memory usage: 14.99 MB

CPU: 0%

Conclusion: The best performing client that I’ve found.

Conclusion

EventBox is the most sophisticated client here, yet it performs incredibly well.  Twitterific uses the least resources.  When looking for software that you’re likely to leave running in the background, get a native client rather than Air.

Comments (View)
Related Posts Widget for Blogs by LinkWithin