blib/lib/Games/TMX/Parser.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1  
2 =head1 NAME
3  
4 Games::TMX::Parser - parse tiled game maps from http://www.mapeditor.org
5  
6 =head1 SYNOPSIS
7  
8 use Games::TMX::Parser;
9  
10 $map = Games::TMX::Parser->new(
11 map_dir => 'maps',
12 map_file => 'tower_defense.tmx',
13 )->map;
14  
15 # ----- the map ------------------
16 $width = $map->width; # all sizes in pixels
17 $height = $map->height;
18 $tile_width = $map->tile_width;
19 $tile_height = $map->tile_height;
20  
21 $tileset = $map->tilesets->[3];
22 $tile = $map->get_tile('some_tile_id'); # find in all tilesets
23 $layer = $map->get_layer('some_layer_name');
24  
25 # ----- a tileset of tiles --------
26 $tile = $tileset->tiles->[2];
27 $image = $tileset->image; # image file name in map_dir directory
28 $width = $tileset->width;
29 $height = $tileset->height;
30 $tile_width = $tileset->tile_width;
31 $tile_height = $tileset->tile_height;
32 $tile_count = $tileset->tile_count;
33  
34 # ----- a tile from a tileset -----
35 %props = %{ $tile->properties };
36 $value = $tile->get_prop('some_tile_property_name');
37 $tileset = $tile->tileset;
38  
39 # ----- a layer on the map --------
40 $cell = $layer->get_cell($column, $row);
41 $cell = $layer->rows->[$row]->[$column]; # same as above
42 @cells = $layer->find_cells_with_property('some_tile_property_name');
43 @cells = $layer->all_cells;
44  
45 # ----- a cell in a layer ---------
46 $tile = $cell->tile;
47 $layer = $cell->layer;
48 ($col, $row) = $cell->xy;
49 $cell = $cell->left;
50 $cell = $cell->right;
51 $cell = $cell->above;
52 $cell = $cell->below;
53 $cell = $cell->seek_next_cell; # follow a path of tiled cells on a layer
54  
55 =head1 DESCRIPTION
56  
57 From http://www.mapeditor.org:
58  
59 Tiled is a general purpose tile map editor. It's built to be easy to use,
60 yet flexible enough to work with varying game engines, whether your game is
61 an RPG, platformer or Breakout clone.
62  
63 This package provides Perl access to the maps generated by Tiled, the general
64 purpose tile map editor. You could use it for drawing you perl game maps in
65 Tiled, or for writing Perl scripts which improve/analyze maps- extract
66 waypoints, decorate corners with shadows, add random trees, etc.
67  
68 Drawing your maps in Tiled is more fun that writing your own map format and
69 then drawing ASCII art.
70  
71 The TMX map format documentation describes the main entities:
72  
73 https://github.com/bjorn/tiled/wiki/TMX-Map-Format
74  
75 =head1 HOW TO USE
76  
77 In Tiled, draw your map and place properties as markers on special tiles you
78 want to read in Perl. Then in your Perl game, read the map and use:
79  
80 my @cells = $map->get_layer('layer_with_stuff')
81 ->find_cells_with_property('my_special_tile_marker');
82
83 To find your special cells (spawn points, enemy locations, etc.).
84  
85 Draw a layer by iteating over:
86  
87 @{ $layer->rows };
88  
89 Which will give you an ARRAY ref of cells, one per column. Then you can find
90 the tile of the cell using:
91  
92 $cell->tile;
93  
94 And then access its properties, or cut the correct image from the tileset image file:
95  
96 $tile->tileset->image;
97  
98  
99 =head1 EXAMPLE
100  
101 The distribution contains an example which computes creep waypoint column/row
102 for any map with a simple path drawn on it.
103  
104 =head1 TODO
105  
106 No support for base64 or compression of maps, uncheck the correct check boxes
107 in Tiled before you save.
108  
109 No support for object layers.
110  
111 =head1 DEVELOPMENT
112  
113 Send pull requests to:
114  
115 https://github.com/eilara/Games-TMX-Parser
116  
117  
118 =head1 AUTHOR
119  
120 Ran Eilam <eilara@cpan.org>
121  
122 A big hug to mst for namespacing help.
123  
124 =head1 COPYRIGHT AND LICENSE
125  
126 Copyright (C) 2011 by Ran Eilam
127  
128 This library is free software; you can redistribute it and/or modify
129 it under the same terms as Perl itself, either Perl version 5.10.1 or,
130 at your option, any later version of Perl 5 you may have available.
131  
132 =cut
133  
134 package Games::TMX::Parser;
135  
136 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
137 1 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
138 0 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
139  
140 has [qw(map_dir map_file)] => (is => 'ro', isa => 'Str', required => 1);
141  
142 has map => (is => 'ro', lazy_build => 1, handles => [qw(get_layer)]);
143  
144 has twig => (is => 'ro', lazy_build => 1);
145  
146 sub _build_twig {
147 my $self = shift;
148 my $twig = XML::Twig->new;
149 $twig->parsefile
150 ( File::Spec->catfile($self->map_dir, $self->map_file) );
151 return $twig;
152 }
153  
154 sub _build_map {
155 my $self = shift;
156 return Games::TMX::Parser::Map->new(el => $self->twig->root);
157 }
158  
159 # ------------------------------------------------------------------------------
160  
161 package Games::TMX::Parser::MapElement;
162  
163 use Moose;
164  
165 has el => (is => 'ro', required => 1, handles => [qw(
166 att att_exists first_child children print
167 )]);
168  
169 # ------------------------------------------------------------------------------
170  
171 package Games::TMX::Parser::Map;
172  
173 use Moose;
174  
175 extends 'Games::TMX::Parser::MapElement';
176  
177 has [qw(layers tilesets width height tile_width tile_height tiles_by_id)] =>
178 (is => 'ro', lazy_build => 1);
179  
180 sub _build_layers {
181 my $self = shift;
182 return {map { $_->att('name') =>
183 Games::TMX::Parser::Layer->new(el => $_, map => $self)
184 } $self->children('layer') };
185 }
186  
187 sub _build_tiles_by_id {
188 my $self = shift;
189 my @tiles = map { @{$_->tiles} } @{ $self->tilesets };
190 return {map { $_->id => $_ } @tiles};
191 }
192  
193 sub _build_tilesets {
194 my $self = shift;
195 return [map {
196 Games::TMX::Parser::TileSet->new(el => $_)
197 } $self->children('tileset') ];
198 }
199  
200 sub _build_width { shift->att('width') }
201 sub _build_height { shift->att('height') }
202 sub _build_tile_width { shift->att('tile_width') }
203 sub _build_tile_height { shift->att('tile_height') }
204  
205 sub get_layer { shift->layers->{pop()} }
206 sub get_tile { shift->tiles_by_id->{pop()} }
207  
208 # ------------------------------------------------------------------------------
209  
210 package Games::TMX::Parser::TileSet;
211  
212 use Moose;
213 use List::MoreUtils qw(natatime);
214  
215 extends 'Games::TMX::Parser::MapElement';
216  
217 has [qw(first_gid image tiles width height tile_width tile_height tile_count)] =>
218 (is => 'ro', lazy_build => 1);
219  
220 sub _build_tiles {
221 my $self = shift;
222 my $first_gid = $self->first_gid;
223  
224 # index tiles with properties
225 my $prop_tiles = {map {
226 my $el = $_;
227 my $id = $first_gid + $el->att('id');
228 my $properties = {map {
229 $_->att('name'), $_->att('value')
230 } $el->first_child('properties')->children};
231 my $tile = Games::TMX::Parser::Tile->new
232 (id => $id, properties => $properties, tileset => $self);
233 ($id => $tile);
234 } $self->children('tile')};
235  
236 # create a tile object for each tile in the tileset
237 # unless it is a tile with properties
238 my @tiles;
239 my $it = natatime $self->width, 1..$self->tile_count;
240 while (my @ids = $it->()) {
241 for my $id (@ids) {
242 my $gid = $first_gid + $id;
243 my $tile = $prop_tiles->{$gid} ||
244 Games::TMX::Parser::Tile->new(id => $gid, tileset => $self);
245 push @tiles, $tile;
246 }
247 }
248 return [@tiles];
249 }
250  
251 sub _build_tile_count {
252 my $self = shift;
253 return ($self->width * $self->height ) /
254 ($self->tile_width * $self->tile_height);
255 }
256  
257 sub _build_first_gid { shift->att('firstgid') }
258 sub _build_tile_width { shift->att('tilewidth') }
259 sub _build_tile_height { shift->att('tileheight') }
260 sub _build_image { shift->first_child('image')->att('source') }
261 sub _build_width { shift->first_child('image')->att('width') }
262 sub _build_height { shift->first_child('image')->att('height') }
263  
264 # ------------------------------------------------------------------------------
265  
266 package Games::TMX::Parser::Tile;
267  
268 use Moose;
269  
270 has id => (is => 'ro', isa => 'Int', required => 1);
271 has tileset => (is => 'ro', weak_ref => 1, required => 1);
272  
273 has properties => (is => 'ro', isa => 'HashRef', default => sub { {} });
274  
275 sub get_prop {
276 my ($self, $name) = @_;
277 return $self->properties->{$name};
278 }
279  
280 # ------------------------------------------------------------------------------
281  
282 package Games::TMX::Parser::Layer;
283  
284 use Moose;
285 use List::MoreUtils qw(natatime);
286  
287 has map => (is => 'ro', required => 1, weak_ref => 1, handles => [qw(
288 width height tile_width tile_height get_tile
289 )]);
290  
291 has rows => (is => 'ro', lazy_build => 1);
292  
293 extends 'Games::TMX::Parser::MapElement';
294  
295 sub _build_rows {
296 my $self = shift;
297 my @rows;
298 my $it = natatime $self->width, $self->first_child->children('tile');
299 my $y = 0;
300 while (my @row = $it->()) {
301 my $x = 0;
302 push @rows, [map {
303 my $el = $_;
304 my $id = $el->att('gid');
305 my $tile;
306 $tile = $self->get_tile($id) if $id;
307 Games::TMX::Parser::Cell->new
308 (x => $x++, y => $y, tile => $tile, layer => $self)
309 } @row];
310 $y++;
311 }
312 return [@rows];
313 }
314  
315 sub find_cells_with_property {
316 my ($self, $prop) = @_;
317 return grep {
318 my $cell = $_;
319 my $tile = $cell->tile;
320 $tile && exists $tile->properties->{$prop};
321 } $self->all_cells;
322 }
323  
324 sub get_cell {
325 my ($self, $col, $row) = @_;
326 return $self->rows->[$row]->[$col];
327 }
328  
329 sub all_cells { return map { @$_ } @{ shift->rows } }
330  
331 # ------------------------------------------------------------------------------
332  
333 package Games::TMX::Parser::Cell;
334  
335 use Moose;
336  
337 has [qw(x y)] => (is => 'ro', isa => 'Int', required => 1);
338  
339 has tile => (is => 'ro');
340  
341 has layer => (is => 'ro', required => 1, weak_ref => 1, handles => [qw(
342 get_cell width height
343 )]);
344  
345 my %Dirs = map { $_ => 1 } qw(below left right above);
346 my %Anti_Dirs = (below => 'above', left => 'right', right => 'left', above => 'below');
347  
348 sub left { shift->neighbor(-1, 0) }
349 sub right { shift->neighbor( 1, 0) }
350 sub above { shift->neighbor( 0,-1) }
351 sub below { shift->neighbor( 0, 1) }
352  
353 sub xy { ($_[0]->x, $_[0]->y) }
354  
355 sub neighbor {
356 my ($self, $dx, $dy) = @_;
357 my $x = $self->x + $dx;
358 my $y = $self->y + $dy;
359 return undef if $x < 0 || $y < 0;
360 return undef if $x > $self->width || $y > $self->height;
361 return $self->get_cell($x, $y);
362 }
363  
364 sub seek_next_cell {
365 my ($self, $dir) = @_;
366 my %dirs = %Dirs;
367 delete $dirs{$Anti_Dirs{$dir}} if $dir;
368 for my $d (keys %dirs) {
369 my $c = $self->$d;
370 return [$c, $d] if $c && $c->tile;
371 }
372 return undef;
373 }
374  
375 1;
↑ Summary