Java drawing a grid of cards for a game

Hey, I'm trying to make a caterpillar dungeon and I'm stuck on map generation. I want random rooms to be there, but before I can do all this, I have to draw a map on the screen. I want the map to be top to bottom and pretty much a grid that I will add to it later. My way of thinking is to create a JFrame and draw a Rectangle2D with paintComponent and a for loop to create a grid of squares. Is this the right way? And also how do I get the character to go from square to square using the keyListener?

EDIT: Dungeon Teen is a top-down game in which you control one character and move them around on a grid. You kill monsters, get weapons and items that they throw, level up, etc. Right now I just want to find a better way to print the map on the screen. I only start with a grid where the character moves from square to square and presses the arrow keys. Then I'll move on to generating random maps!


source to share

2 answers

Better to create an abstraction layer first. Start with an array that contains information about each cell (empty, obstacle, enemy, player, element, etc.).

Something like that

int[][] a={
  {0,1,0,0,0}, //"1" - obstacle
  {2,0,1,0,0}, //for example "2" is player


Now just draw your rectangles (or images that actually look better :)) using this map. Usually each cell should be the same size, so just draw rectangles in some increments.



You need to create a BufferedImages size that matches your map size, get its Graphics object and draw the map using that object, and then delete it. Then you can easily display it in an ImageIcon stored in a JLabel or in a JPanel method paintComponent(...)




All Articles