Jump to content
  • Advertisement

Search the Community

Showing results for tags 'Java'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Categories

  • Audio
    • Music and Sound FX
  • Business
    • Business and Law
    • Career Development
    • Production and Management
  • Game Design
    • Game Design and Theory
    • Writing for Games
    • UX for Games
  • Industry
    • Interviews
    • Event Coverage
  • Programming
    • Artificial Intelligence
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Engines and Middleware
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
  • Archive

Categories

  • Audio
  • Visual Arts
  • Programming
  • Writing

Categories

  • Game Dev Loadout
  • Game Dev Unchained

Categories

  • Game Developers Conference
    • GDC 2017
    • GDC 2018
  • Power-Up Digital Games Conference
    • PDGC I: Words of Wisdom
    • PDGC II: The Devs Strike Back
    • PDGC III: Syntax Error

Forums

  • Audio
    • Music and Sound FX
  • Business
    • Games Career Development
    • Production and Management
    • Games Business and Law
  • Game Design
    • Game Design and Theory
    • Writing for Games
  • Programming
    • Artificial Intelligence
    • Engines and Middleware
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
    • 2D and 3D Art
    • Art Critique and Feedback
  • Community
    • GameDev Challenges
    • GDNet+ Member Forum
    • GDNet Lounge
    • GDNet Comments, Suggestions, and Ideas
    • Coding Horrors
    • Your Announcements
    • Hobby Project Classifieds
    • Indie Showcase
    • Article Writing
  • Affiliates
    • NeHe Productions
    • AngelCode
  • Topical
    • Virtual and Augmented Reality
    • News
  • Workshops
    • C# Workshop
    • CPP Workshop
    • Freehand Drawing Workshop
    • Hands-On Interactive Game Development
    • SICP Workshop
    • XNA 4.0 Workshop
  • Archive
    • Topical
    • Affiliates
    • Contests
    • Technical
  • GameDev Challenges's Topics
  • For Beginners's Forum
  • Unreal Engine Users's Unreal Engine Group Forum
  • Unity Developers's Forum
  • Unity Developers's Asset Share

Calendars

  • Community Calendar
  • Games Industry Events
  • Game Jams
  • GameDev Challenges's Schedule

Blogs

There are no results to display.

There are no results to display.

Product Groups

  • Advertisements
  • GameDev Gear

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


About Me


Website


Role


Twitter


Github


Twitch


Steam

Found 161 results

  1. In this post, I add the keyboard management to the facade, and I propose a way to detect key sequences. These sequences are used, for example, in games like Street Fighter II, where characters move according to specific key combos. Keyboard facade I first design the keyboard facade. As I did for the mouse, I use a Factory Method pattern: I add a getKeyboard() method to the GUIFacade class that returns an instance of a Keyboard interface. This interface is defined as follow, and uses two other interfaces KeyEvent and KeyEventType: The method isKeyPressed() returns true if the key corresponding to keyCode is pressed. The key codes are the ones defined in java.awt.event.KeyEvent, for instance java.awt.event.KeyEvent.VK_UP. It is part of the Java standard library, so they are always available, we don’t need to create new ones. This method could be the only one in the Keyboard facade if we don’t need to detect key sequences. The three other methods of Keyboard and the two interfaces KeyEvent and KeyEventType are dedicated to the detection of key sequences. They assume that there is a buffer that holds a list of key events. The user can access this buffer thanks to the following methods: setMaxKeyEventLifeTime() defines the maximum lifetime of a key in the buffer (in nanoseconds). It means that key combos must happen in limited time; for instance for fast games, we can ask for combos succeeded in less than 200ms. getKeyEvents() returns the list of last key events. I show below examples of parsing of this list. clearKeyEvents() empties the event buffer. Once a key sequence is detected, we must remove it; otherwise, we will detect it at every game update. The KeyEvent interface returns information about a key event: the key code with getKeyCode(), the event type with getType(), and the time when the event happens with getKeyTime(). The time is relative, it can only be used for comparison, for instance, for computing the delay between two key events. Keyboard state If we only need to know which key is currently pressed (or not), we only need the isKeyPressed() method of the Keyboard interface. For example, if we want to know the status of the arrow keys: Keyboard keyboard = gui.getKeyboard(); # gui points to a GUIFacade rightArrow = keyboard.isKeyPressed(java.awt.event.KeyEvent.VK_RIGHT); leftArrow = keyboard.isKeyPressed(java.awt.event.KeyEvent.VK_LEFT); upArrow = keyboard.isKeyPressed(java.awt.event.KeyEvent.VK_UP); downArrow = keyboard.isKeyPressed(java.awt.event.KeyEvent.VK_DOWN); This code should be put in the input handling part of the Game Loop pattern, for instance, the processInput() method I introduced in the mouse post. Then, in the game update part of the Game Loop pattern, we can move a character: if (rightArrow) { characterX += 1; } if (leftArrow) { characterX -= 1; } if (upArrow) { characterY -= 1; } if (downArrow) { characterX += 1; } Finally, in the rendering part of the Game Loop pattern, we draw the character gui.drawSprite(characterX,characterY,spriteId); I assume that drawSprite() is a method that draws the sprite spriteId at location (characterX, characterY). With this approach, we can move a character at a speed that depends on several refresh rates (display, game state). It leads to many issues I’ll address in future posts. Detect key sequences Now let me present how to detect key sequences using the Keyboard facade I propose... Continue reading on learngameprog.com...
  2. Graphic libraries usually provide methods to draw text on the screen. These handy methods are often quite slow to run because they recompute many parameters at each call. To save computational time, the flyweight pattern can be used to provide text parameters with low memory and cpu usage. Facade design As usual, I start by adding new methods to the GUI Facade. There are many possibilities, here is an example that allows the drawing of messages of any size and color (NB: I only show new methods, I assume that the ones from the previous posts are still there): The setColor() method sets the text color. It uses java.awt.Color to defines the colors. I could create my own Color class, but it won’t lead to significant changes, and java.awt.Color is always in the Java standard library; The setTextSize() method sets the text height in pixels; The getTextMetrics() method computes the bounding box of a text to print. It also uses a class from AWT, namely java.awt.Dimension; The drawText() method draws text at coordinates (x,y). It also clip the text if it is too large. The clipping rectangle is defined by (x,y) and (width,height). AWT Implementation Implementing this facade with AWT is easy for setColor(), getTextMetrics() and drawText(). This is only a wrapping of existing methods: @Override public void setColor(Color color) { if (graphics == null) return; graphics.setColor(color); } @Override public Dimension getTextMetrics(String text) { if (graphics == null) return new Dimension(0,0); FontMetrics fm = graphics.getFontMetrics(); int textWidth = fm.stringWidth(text); int textHeight = fm.getHeight(); return new Dimension(textWidth,textHeight); } @Override public void drawText(String text, int x, int y, int width, int height) { if (graphics == null) return; FontMetrics fm = graphics.getFontMetrics(); graphics.clipRect(x, y, width, height); graphics.drawString(text, x, y+fm.getAscent()); graphics.setClip(null); } For the setTextSize() method, there is no existing method in AWT. A solution is to search for the font that has the required text height in pixels: public void setTextSize(int size) { if (graphics == null) return; for (int i=2*size;i>=4;i--) { Font font = new Font("Arial",Font.PLAIN,i); graphics.setFont(font); FontMetrics fm = graphics.getFontMetrics(); if (fm.getHeight() < size) { break; } } } This method is time-consuming and can be called many times at each frame rendering. Multiplied by the number of frames per second (usually 60), this can lead to a lot of unuseful computations since most of these calls will return the same values! A first approach consists of manually caching the parameters (in this example the AWT font instance). This saves computation time but requires additional work for the user and the implementer of the facade. A more efficient approach is based on the Flyweight pattern. Flyweight Pattern The Flyweight pattern... Continue reading on https://learngameprog.com ...
  3. After loading a level, I now propose to add interaction with the use of a mouse. This will be an opportunity to see two other patterns: the Observer Pattern to handle mouse events, and the Game Loop Pattern for synchronization between controls, updates, and display. This post is part of the AWT GUI Facade series Mouse Facade To add the management of the mouse to the facade, I propose to introduce a new Mouse interface that contains all the functions related to the mouse: Separating the interface for the mouse from the general interface of the facade has two advantages: lighten the general interface and allow the simultaneous management of several mice. As far as methods are concerned, I chose the simplest API possible: isButtonPressed() method: returns true if a button is pressed; getX() and getY() methods: return the (x, y) coordinates of the cursor in the window This API is also lowlevel, to match what most graphic libraries offer. In addition, it allows having at any time the complete state of the mouse, which is often necessary for video games. For the general GUIFacade interface, a new getMouse() method is added to return an implementation of the Mouse interface. Mouse handling in AWT To implement this interface, AWT library included in the standard Java library is still used. This one offers a high-level API, which meets the needs of office applications. It is based on the Observer Pattern, which allows an element to observe (or listen to) another element, and to be notified when an event occurs. In the case of the mouse, these events are for example the pressure of a button or the movement of the cursor. This API is divided into several interfaces, for example, the interface MouseListener allows to manage the events related to the buttons: The MouseListener interface contains the methods implemented by the observer: for example, when a button is pressed, the mousePressed() method is called and the observer can then act accordingly. The Component class, which is the superclass of many graphic components within AWT, can be observed by anyone who requests it thanks to the addMouseListener() method. For the example of this article, it is the Canvas used to make the level of the game that is observed: each action of the mouse in its display area causes calls to the methods of the MouseListener interface. Facade implementation I propose that the implementation of the Mouse interface of the facade takes the form of an AWTMouse class: The class implements the Mouse, MouseListener, and MouseMotionListener interfaces. The first methods provide information about the mouse (contained in its attributes): public class AWTMouse implements Mouse, MouseListener, MouseMotionListener { private final boolean[] buttons; private int x; private int y; public AWTMouse() { buttons = new boolean[4]; } @Override public boolean isButtonPressed(int button) { if (button >= buttons.length) { return false; } return buttons[button]; } @Override public int getX() { return x; } @Override public int getY() { return y; } ... The following ones respond to mouse events and update mouse information: @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { if (e.getButton() <= 3) { buttons[e.getButton()] = true; } } @Override public void mouseReleased(MouseEvent e) { if (e.getButton() <= 3) { buttons[e.getButton()] = false; } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { x = e.getX(); y = e.getY(); } @Override public void mouseMoved(MouseEvent e) { x = e.getX(); y = e.getY(); } } Finally, the AWTWindow class contains as before the canvas, and this one is used to “listen” the events of the mouse: public void init(String title, int width, int height) { ... mouse = new AWTMouse(); canvas.addMouseListener(mouse); canvas.addMouseMotionListener(mouse); } Game Loop It only remains to exploit this new interface in an example. To do this, I propose to introduce the Game Loop Pattern in its simplest version (without multi-threaded considerations). It is based on a set of methods that can be grouped together in the same class: The init() method is called at startup to initialize the game and its data; The processInput() method is called at each iteration of the game to manage the controls (keyboard, mouse, …). In short, its main role is to transform the user’s “instructions” into more abstract “orders” or “commands” that the game engine knows how to interpret. Considering time, these operations go to the rhythm of the user. The update() method applies changes to game data based on various sources, such as commands produced by user controls or operations that must be applied to each update. Considering time, these operations go to the speed of the game engine. The render() method handles display. This method will most often order or transfer data on the graphics card, the latter dealing with very low-level tasks at the pixel level. Considering time, these operations go to the refresh rate of the screen (default 60Hz). The run() method calls the previous ones and contains the actual game loop. In this example, I don’t implement all the elements required to meet all these principles. I propose here a basic form of this pattern, sufficient to begin to understand all these notions. For the init() method, we build the two layers and initialize the window: public void init(Level level) { this.level = level; backgroundLayer = gui.createLayer(); backgroundLayer.setTileSize(level.getTileWidth(),level.getTileHeight()); backgroundLayer.setTexture(level.getTilesetImage(0)); backgroundLayer.setSpriteCount(level.getWidth()*level.getHeight()); groundLayer = gui.createLayer(); groundLayer.setTileSize(level.getTileWidth(),level.getTileHeight()); groundLayer.setTexture(level.getTilesetImage(1)); groundLayer.setSpriteCount(level.getWidth()*level.getHeight()); gui.createWindow("Exemple de contrôle avec la souris", scale*level.getTileWidth()*level.getWidth(), scale*level.getTileHeight()*level.getHeight()); } For the processInput() method, if the following conditions are met: the left button is pressed; there is a cell of the level under the cursor; the tile of this cell is in the second set of tiles (the one of the second layer), then we put a tile with grass (this will erase all buildings in the map): public void processInput() { Mouse mouse = gui.getMouse(); if (mouse.isButtonPressed(MouseEvent.BUTTON1)) { int x = mouse.getX() / (scale*level.getTileWidth()); int y = mouse.getY() / (scale*level.getTileHeight()); if (x >= 0 && x < level.getWidth() && y >= 0 && y < level.getHeight()) { if (level.getTileset(x,y) == 1) { level.setTileset(x,y,0); level.setTile(x,y,new Point(7,0)); } } } } For the update() method, the content of the level data is used to define the sprite textures. It is the same as in the previous post, except that this operation is repeated regularly: public void update() { for(int y=0;y<level.getHeight();y++) { for(int x=0;x<level.getWidth();x++) { int index = x + y * level.getWidth(); backgroundLayer.setSpriteLocation(index, new Rectangle(scale*x*level.getTileWidth(), scale*y*level.getTileHeight(), scale*level.getTileWidth(), scale*level.getTileHeight())); if (level.getTileset(x, y) == 0) { Rectangle tile = new Rectangle(level.getTile(x, y), new Dimension(1,1)); backgroundLayer.setSpriteTexture(index, tile); } else { backgroundLayer.setSpriteTexture(index, null); } } } for(int y=0;y<level.getHeight();y++) { for(int x=0;x<level.getWidth();x++) { int index = x + y * level.getWidth(); groundLayer.setSpriteLocation(index, new Rectangle(scale*x*level.getTileWidth(), scale*(y-1)*level.getTileHeight(), scale*level.getTileWidth(), scale*2*level.getTileHeight())); if (level.getTileset(x, y) == 1) { Rectangle tile = new Rectangle(level.getTile(x, y), new Dimension(1,2)); groundLayer.setSpriteTexture(index, tile); } else { groundLayer.setSpriteTexture(index, null); } } } } The render() method just draws the two layers: public void render() { if (gui.beginPaint()) { gui.drawLayer(backgroundLayer); gui.drawLayer(groundLayer); gui.endPaint(); } } Finally, the run() method contains the game loop that calls the other methods at most 60 times per second: public void run() { int fps = 60; long nanoPerFrame = (long) (1000000000.0 / fps); long lastTime = 0; while(!gui.isClosingRequested()) { long nowTime = System.nanoTime(); if ((nowTime-lastTime) < nanoPerFrame) { continue; } lastTime = nowTime; processInput(); update(); render(); long elapsed = System.nanoTime() - lastTime; long milliSleep = (nanoPerFrame - elapsed) / 1000000; if (milliSleep > 0) { try { Thread.sleep (milliSleep); } catch (InterruptedException ex) { ex.printStackTrace(); } } } gui.dispose(); } This basic implementation of the Game Loop pattern does not respect all its principles. There is no real notion of control, and it will be difficult to run each part at different rates. In addition, in terms of design, there are also questionable choices, like the Level class that serves as both a level loader, storage for the level, and a form of buffer. Through future posts, I will present all that is needed to achieve more effective implementations. The code of this post can be downloaded here: awtfacade06.zip To compile: javac com/learngameprog/awtfacade06/Main.java To run: java com.learngameprog.awtfacade06.Main The post AWT GUI Facade (6): Mouse and Game Loop appeared first on Design Patterns and Video Games. View the full article
  4. I'm working on my first Android game and I have a few questions. I need to scale the graphics for different screen sizes/resolutions. I'm working in 16:9 and plan to use letter boxing to maintain this aspect ratio. Everything is fine for standard screen resolutions. Going from 320:180 to 640:360, one pixel just becomes four. I'm a little confused though as to what happens when you letterbox on a screen with a unusual resolution. Say, just for exsample, my original graphics are 160:90. Then to fit the devise I stretch everything by 1.1 and end up with a final resolution of 176:99. Its still 16:9 but now everything is a mess. If I had a sprite that used to be at x-33 y-33 it's new location would now be at x-36.3 y-36.3. Would I just drop the 0.3 of a pixel, round down and accept that it's no longer in its exact position? Secondly what exactly happens when you stretch images by an amount like 1.1? How dose it decide what pixels to add to the image to make it bigger?
  5. I continue the extension of the graphic facade (see previous article), with here the addition of a very classic form of drawing for video games: tiles. These make it possible to compose an image using small images called tiles. There are several types of tiles, I propose in this article the simplest case with rectangular tiles. This post is part of the AWT GUI Facade series. For the implementation, the approach that I propose to follow is similar to the one used for images: we use a factory (Factory Method Pattern) to instantiate layers that allow drawing with tiles. On the GUIFacade main interface side, I add the following two methods, one to create a layer, and the other to draw it: For layers (Layer interface), I propose to manage the tiles with one texture image by layer, and with tiles of a fixed size. In addition, the rendering of tiles can be memorized by the layer: in doing so, it is sufficient to indicate which tiles should be displayed in which places, and then the layer will display these tiles continuously. These renderings are called in this article sprites, so as not to confuse them with tiles (e.g., a tile is just a small picture, and a sprite is a small picture displayed at a specific location on the screen). At this stage of design, layers able to renders independently may seem unnecessary: we could continuously consult the game data for rendering. Later, when it will be necessary to make multi-threaded synchronization, independent layers are a blessing. In addition, for low-level implementations (such as OpenGL), it allows you to use vertex buffers, which greatly speeds up rendering. These properties can be obtained via an interface like the following one: The getTileWidth() and getTileHeight() methods return the size of the tiles (for example, 16 by 16 pixels); The getTextureWidth() and getTextureHeight() methods return the number of tiles in the texture image, in width and height; The setTileSize() method is used to set the size of tiles; The setTexture() method is used to define and load the texture image; The setSpriteCount() method is used to set the number of sprites managed by the layer; The setSpriteTexture() method is used to define the tile used by a sprite. The tile rectangle defines the used tile: they are coordinates in tiles, and not in pixels. For example, if the tile size is 16×16 pixels, and the tile rectangle is (3,4,1,2), then the tile location in pixels is (3 * 16,4 * 16,1 * 16,2 * 16) = (48,64,16,32). By convention, if the rectangle argument is null, then the sprite is disabled; The setSpriteLocation() method is used to define the location where the sprite is drawn. The rectangle is in pixels, and may be larger or smaller than the tiles used, to achieve a zoom effect. AWT Implementation For the implementation, we still use the AWT library, with the AWTLayer class (the methods of the Layer interface are not repeated): The tileWidth, tileHeight, textureWidth, and textureHeight attributes define the size of the tiles and the texture image; The texture attribute contains the texture image; The texture and location arrays contain all sprite information: tiles to use and render locations; The draw() method draws the entire layer. Most methods are accessors / mutators (getters / setters) whose implementation is very simple. The draw () method is less obvious: public void draw(Graphics graphics) { for (int i = 0; i < locations.length; i++) { if (textures[i] != null) { graphics.drawImage(texture, locations[i].x, locations[i].y, locations[i].x + locations[i].width, locations[i].y + locations[i].height, textures[i].x * tileWidth, textures[i].y * tileHeight, (textures[i].x+textures[i].width) * tileWidth, (textures[i].y+textures[i].height) * tileHeight, null); } } } All sprites are traversed (l.2), if a sprite is well defined (l.3), we draw an image (l.4-13). Lines 5 to 8 define the rendering location, in pixels: it is the coordinates of the upper left corner and the lower right corner of the rectangle. Lines 9 to 12 define a rectangle in the texture image: all coordinates are multiplied by tile size (tileWidth, tileHeight). Use case To illustrate this facade with tile drawing, I propose to consider two layers: one for the background, and the other for the buildings. In both cases, we consider the same tile size of 16 × 16 pixels, and the same area of rendering (the level of the game) of 17 × 17 tiles. In addition, a scale factor is used to zoom tiles. These parameters are placed in variables: int scale = 2; int tileWidth = 16; int tileHeight = 16; int levelWidth = 17; int levelHeight = 17; For the background layer, each sprite uses only one tile, and we always use the same one: Layer backgroundLayer = gui.createLayer(); backgroundLayer.setTileSize(tileWidth,tileHeight); backgroundLayer.setTexture("advancewars-tileset1.png"); backgroundLayer.setSpriteCount(levelWidth*levelHeight); for(int y=0;y<levelHeight;y++) { for(int x=0;x<levelWidth;x++) { int index = x + y * levelWidth; backgroundLayer.setSpriteLocation(index, new Rectangle(scale*x*tileWidth, scale*y*tileHeight, scale*tileWidth, scale*tileHeight)); backgroundLayer.setSpriteTexture(index, new Rectangle(new Point(7,0), new Dimension(1,1))); } } Lines 1-4 instantiate and initialize the layer. Then, for each cell of the level (l, 5-6), we associate a sprite (l, 7). To achieve this association, it is necessary to define a unique number for each cell of the level: to do this, the cells are numbered from left to right then from top to bottom. The rendering area of each sprite is defined in lines 8-9, which is a simple scaling: everything is multiplied by the tileWidth, tileHeight, and the global scale. Finally, the tile is selected in lines 10-11, with the 8th column of the first line of the texture Point (7,0) and the size of a tile Dimension (1,1) The following layer is used to display buildings, with the particularity that these have a height of two tiles in height: Layer groundLayer = gui.createLayer(); groundLayer.setTileSize(tileWidth,tileHeight); groundLayer.setTexture("advancewars-tileset2.png"); groundLayer.setSpriteCount(2); groundLayer.setSpriteLocation(0, new Rectangle(scale*8*tileWidth, scale*6*tileHeight, scale*tileWidth, scale*2*tileHeight) ); groundLayer.setSpriteTexture(0, new Rectangle(new Point(0,2), new Dimension(1,2))); groundLayer.setSpriteLocation(1, new Rectangle(scale*8*tileWidth, scale*7*tileHeight, scale*tileWidth, scale*2*tileHeight) ); groundLayer.setSpriteTexture(1, new Rectangle(new Point(0,4), new Dimension(1,2))); Lines 1-4 instantiate the layer and initialize its properties: tile size, texture image, and sprite numbers (2). Lines 6 through 11 define the properties of the first sprite (index 0): its render location is at cell (8,6) of the grid (l. 7), its render size equals a tile width and two heights of tiles (l. 8). Its tiles are at coordinates (0,2) in the texture and use a tile of width one and height two (l. 11). Lines 13 to 18 define the properties of the second sprite: it is drawn on the cell just below, and its tiles start at the coordinates (0,4) in the texture. If all goes well, the top of the second building sprite should cover the bottom of the first: Finally, in the game’s main loop, displaying layers is as easy as displaying an image: if (gui.beginPaint()) { gui.drawLayer(backgroundLayer); gui.drawLayer(groundLayer); gui.endPaint(); } The code of this article can be downloaded here: awtfacade04.zip Some improvements have been made compared to the version of the previous article: it uses a canvas and limits the number of images per second. These improvements are purely related to the problems of video games, and does not change the concepts presented above. To compile: javac com/learngameprog/awtfacade04/Main.java To run: java com.learngameprog.awtfacade04.Main Next post in this series View the full article
  6. In this article, I propose to use the Visitor Pattern to easily load a level. The GUI facade in the previous post is used to display the level. This pattern allows (among other things) to easily browse a data structure to extract information. In our case, it is an XML file created by “Tiled Map Editor” which is analyzed to load a level in memory. This post is part of the AWT GUI Facade series I start by creating a level in XML with Tiled: You have to choose in the left panel Tile layer format as “XML”. This produces an XML file that looks like this: <map version="1.0" orientation="orthogonal" renderorder="left-up" width="16" height="16" tilewidth="16" tileheight="16" nextobjectid="1"> <tileset firstgid="1" name="advancewars-tileset1" tilewidth="16" tileheight="16" tilecount="256"> <image source="advancewars-tileset1.png" width="256" height="256"/> </tileset> <tileset firstgid="257" name="advancewars-tileset2" tilewidth="16" tileheight="16" tilecount="256"> <image source="advancewars-tileset2.png" width="256" height="256"/> </tileset> <layer name="Ground" width="16" height="16"> <data> <tile gid="41"/> <tile gid="41"/> <tile gid="41"/> <tile gid="41"/> <tile gid="41"/> <tile gid="41"/> <tile gid="41"/> <tile gid="41"/> ... <tile gid="41"/> </data> </layer> <layer name="Objects" width="16" height="16"> <data> <tile gid="0"/> <tile gid="0"/> <tile gid="0"/> <tile gid="0"/> <tile gid="0"/> ... <tile gid="0"/> <tile gid="0"/> <tile gid="0"/> </data> </layer> </map> We first have a <main> tag with global properties, then two <tileset> tags that define the tile sets used (one for the background, the other for the objects), and finally two <layer> tags that define the tiles for two layers (one for the background, the other for the objects). To decode this file, I propose to use the XML parser included in the standard Java library. It is based on the Visitor pattern, and allows you to easily work on tags without having to worry about character decoding issues. Visitor Pattern The Visitor pattern can be presented as follows: The IElement interface represents the elements of the structure. In this example, there are two possible types of objects: ElementA and ElementB. The interface requires a method like accept() which takes as argument a visitor who implements the IVisitor interface. There can be several ways to visit the structure, and so many other methods similar to accept(). Parameters can also be used to influence the traversal. The IVisitor interface is implemented by the user who wants to traverse the structured data. In general, the interface methods correspond to the different types of elements that compose it: in this example, they are the ElementA and ElementB classes. It is quite possible to imagine other cases that may interest a user, such as being at the beginning or at the end of an element. In all cases, the accept() method calls the methods of the IVisitor interface according to the cases encountered during its course. Within these methods, the user is free to view and modify the data. Load a level To read and store the level information, I define a Level class that contains this information in attributes: public class Level { private ArrayList<String> tilesetImages = new ArrayList(); private int tileWidth; private int tileHeight; private int width; private int height; private int[][][] level; private int tilesetWidth; private int tilesetHeight; private int x; private int y; ... The tilesetImages attribute contains the file names of texture images; The tileWidth and tileHeight attributes contain the width and height of a tile (16 x 16 pixels in our example); The width and height attributes contain the width and height of the level (16 x 16 cells in our example); The level attribute contains for each cell coordinate: the (x, y) tile coordinates of the tile to draw, and the tile set to use. The following attributes are only used to decode the information in the file. To decode the file, I define a LevelLoader class that implements org.xml.sax.helpers.DefaultHandler. The LevelLoader class is the equivalent of the Visitor class in the diagram above, and DefaultHandler is the equivalent of IVisitor. I’m only interested in the startElement() method, equivalent to the visitElementA() and