PHP Hex Map Graphics
« Tracking Finances Though Benign Neglect
» Freemium and Segmentation
Code: hex maps, image generation, PHP, web games
1 comment
This PHP code uses the GD functions to create hex map images (eg. for wargames).
Features:
- Shapes: rectangule, hexagonal (‘circle’), freeform (‘free’)
- Variable hex sizes
- shape() to calculate distance in hexes
- highlight a hex
- set a border on a hex
- color a hex
- add text to a hex
- I swear it used to allow setting a background picture, but I don’t see that functionality so maybe I dreamed it or lost it when I misplaced this code for four years.
Known Issues
The code has ugly styling (tabs, odd spacing, no optional braces) – sorry, I was young(er) and stupid(er).
There’s a fair amount of temporal coupling in there – functions that you can’t call before other functions, etc. I hadn’t heard of the command pattern or closures yet.
There’s a bug in the ‘circle’ shape (that the following code exercises):
set_color('bg', 255, 255, 255);
$map->set_l(20);
$map->set_shape('circle', $radius);
$map->start();
for($x = 1; $x <= $map->xsize; $x++) {
for($y = 1; $y <= $map->ysize; $y++) {
$map->text($x, $y, 'black', $map->steps($x, $y, $radius, $radius));
// nice for getting a feel for coordinates
//$map->text($x, $y, 'black', "$x,$y");
}
}
header('Content-Type: image.png');
$map->finish(); // calls imagepng()
?>
Future
One of the guys in #bbg on irc,freenode.net is building a browser-based game with a hex map and I remembered this code was squirreled away somewhere on my hard drive. I have no plans to fix, improve, or in any way maintain this code. I figure I may as well release it so someone can do something with it.
License
I release this code to the public domain. You may use it for any purpose with or without attribution. It would be polite to mention my name and let me know you come up with, but it’s not at all required.
Cool. I have an idea for a strategy game that I keep going back and forth between whether I want to use a standard grid or a hex grid. Hex grids tend to alienate a lot of people for some reason but square grids have the issue with diagonal movement either being faster than straight-line movement or require additional processing.
I’ll probably try both methods during my play testing and see which is preferred.