Game map part 1: front-end with Leaflet.Js

As I am a web developer and not (yet!) a game developer, I have no idea on how to draw a map of a web based game. Which is why I transformed the task into something I know how to do – display a map on a web site! So, what are we going to use today? Leaflet.Js – an open-source js tiled map redering engine. And … that’s it! 🙂 Intrested? See below for details.

So what is a map? If take a closer look – it is just a set of images that are downloaded from the server and presented in a propper way. In order to save some time, I’ve decided to use an already created engine. So why leaflet?

This is the code I used with some comments:

$(document).ready(function() {

	/**
	 * Reder map
	 */
	var zoom = 6;
	var tileSize = 90;
	var squareSize = (Math.pow(2, zoom) - 1) * tileSize;
	var tilesUrl = passedFromServer.baseUrl + 'map/tile?x={x}&y={y}';

	/**
	 * Create new map object
	 */
	var map = new L.Map('map-container', {
		center : [0, 0],
		zoom : zoom,
		zoomControl : false,
		// the next is the very main line here
		crs : L.CRS.Simple,
		maxBounds : new L.LatLngBounds(
			new L.LatLng(-squareSize, squareSize),
			new L.LatLng(0, 0)
		)
	});

	/**
	 * Add a tile layer (e.g. where do we get the images from?)
	 */
	L.tileLayer(tilesUrl, {
		maxZoom : zoom,
		minZoom : zoom,
		tileSize : tileSize,
		attribution : false,
		continuousWorld : false,
	}).addTo(map);

	/**
	 * Add a popup to a map for debug (yes, this is not yet finished)
	 */
	var popup = L.popup();

	function onMapClick(e) {
		popup
		  .setLatLng(e.latlng)
		  .setContent("You clicked the map at " + e.latlng.toString())
		  .openOn(map);
	}

    map.on('click', onMapClick);
})

The full source file can be found here.

So what is the CSR? The L.CRS.Simple is used for converting the lat/lng coords into the usual geometry coords like X:Y. We will need it to make the map rendering simplier. I am also disabling the zoom, as it craetes extra complexity which I do not need for now. The tilesUrl is the local (same site) url that will provide the client with the tile image. We are requesting the tile by the coord and the zoom. And what the server does? This is the next part of the story!

And this is how it looks in the end:

Game layout preview

As for me, the code is pretty simple and understandable, but please feel free to ask any questions. I will explain the DB structure and the php code for the map generation in the next posts shortly. Stay tuned!

One thought on “Game map part 1: front-end with Leaflet.Js

  1. Pingback: Game map part 2: database tables & schema | game::dev('lamp', 'etc.');

Leave a comment