Not sure how to approach this problem.
Basically, I want a Pixel -> Tile representation of a 400x400 window. Each coordinate on the screen, e.g 120x300 should be part of a tile. My smallest sprite is 4 pixels, so we can say that 1 tile = 4 pixels. The player and enemy sprites are all 20 x 20, so each player/bad guy will occupy 5 tiles.
Then I want to use this Map class to:
Retrieve the x/y coordinates of a player/monster sprite by suppling the index/id of the tile.
Knowing where the boundaries are, so it doesn't move the sprite beyond 400x400, thus hiding it.
Collision detection, knowing whether a tile is vacant or not.
How can this be done? Talking specifically about the x,y->tile or tile index->x,y conversion (for drawing the sprites appropriately) here.
解决方案
Firstly, split out the concept of a pixel, which is just concerned with representation, with a tile, which is an actual game object with constraints it places on the game.
I find a good way to disentangle things like this is to start out sketching out the rough API of what you want. Something like:
public class Board {
public Board (int width, int height){.. }
public boolean isOccupied(int x, int y){.. }
public void moveTo(Point from, Point to) { ..
(maybe throws an exception for outofbounds )
where all internal units of the board are in tiles, not pixels.
Then pixel information can be derived from the board independantly from the tile representation with a bit of internal multiplication-
public Point getPixelPosition(int xTilePos, int yTilePos, int pixelsPerTile)..
The tiles can be internally represented as a 2d array or a single array, in which case you'd use some kind of internal representation scheme to map your array to the board squares, thus the mod arithmetic.