14 Replies - 1051 Views - Last Post: 02 May 2012 - 10:36 AM Rate Topic: -----

#1 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Filling a HashMap based off of an array

Posted 01 May 2012 - 03:57 PM

I have an array:
int[][] temp = new int[40][40];

It is filled with a mix of 1's and 0's. Then I have a hashmap:
HashMap<Integer, Boolean> isSolid = new HashMap<Integer, Boolean>();

How can I loop through the array and set the key of the hashmap to the array's index plus the boolean value to true or false based on if the item in the array is a 0 or 1? For example, when you go through the loop and array index [2][5] was 1 (solid, so the boolean value is true). How could I do isSolid.put(85, true); Of course I would want to do this for everything in the array. And also, how could I do the opposite so I could check which place is solid. I'm asking this because I'm making a grid game which is 400 x 400 and the cubes are 10 x 10. Could you please help me?

Is This A Good Question/Topic? 0
  • +

Replies To: Filling a HashMap based off of an array

#2 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 04:18 PM

Assuming your 85 is coming from [2] * 40 + [5] the easiest way would be

int k = 0;
for(int i = 0; i < temp.length; ++i) {
   for(int j = 0; j < tem[i].length; ++j) {
      isSolid.put(k++, new Boolean(temp[i][j] == 1));
   }
}


Was This Post Helpful? 0
  • +
  • -

#3 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 04:23 PM

View Postpbl, on 01 May 2012 - 04:18 PM, said:

Assuming your 85 is coming from [2] * 40 + [5] the easiest way would be

int k = 0;
for(int i = 0; i < temp.length; ++i) {
   for(int j = 0; j < tem[i].length; ++j) {
      isSolid.put(k++, new Boolean(temp[i][j] == 1));
   }
}



When I was trying to figure out how to do this, I tried something similar but I failed. This works perfectly! Thanks for the help!
Was This Post Helpful? 0
  • +
  • -

#4 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2610
  • View blog
  • Posts: 4,163
  • Joined: 21-June 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 04:25 PM

isSolid.put(k++, new Boolean(temp[i][j] == 1));


You shouldn't use new Boolean. That just creates new Boolean objects unnecessarily. By using Boolean.valueOf instead, you'll reuse existing Boolean objects instead, saving both memory and runtime.

In this case however you can take advantage of auto-boxing and just pass the boolean to put directly and Java will automatically turn it into a Boolean.
Was This Post Helpful? 1
  • +
  • -

#5 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 04:46 PM

Since the screen is 400 x 400 and each square is 10 x 10 and if I have the x, y, width, and height of a certain square, how do I figure out the key of the hashmap for that certain square? Like if I had x = 10, y = 10, width = 10, height = 10, how would I figure out that its key for the hashmap is 41?
Was This Post Helpful? 0
  • +
  • -

#6 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 04:51 PM

You missed the concept here.
The way the HashMap handles the hash code for the key you provided is not really of your business. You access the HashMap by the Key value, you provided, not by the hash code it generated internally to store your data.
Was This Post Helpful? 0
  • +
  • -

#7 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 04:54 PM

View Postpbl, on 01 May 2012 - 04:51 PM, said:

You missed the concept here.
The way the HashMap handles the hash code for the key you provided is not really of your business. You access the HashMap by the Key value, you provided, not by the hash code it generated internally to store your data.



Okay. So if I had x = 10, y = 10, width = 10, and height = 10. To find the boolean value of that square how would I do it?
Was This Post Helpful? 0
  • +
  • -

#8 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 05:30 PM

if (kc == 'w' || event.getKeyCode() == KeyEvent.VK_UP) {
					//This will find the squares position IF it moves.
					rec.translate(0, -MazeData.blockSize);
                                        //MazeData.blockSize = 10
					
					int k = 0;
					for(int i = 0; i < MazeData.data.length; ++i) { //MazeData.data is the int[][] array.
					   for(int j = 0; j < MazeData.data[i].length; ++j) {
					      int xpos = j * MazeData.blockSize;
					      int ypos = i * MazeData.blockSize;
					      
					      System.out.println(xpos + ", " + ypos);
					      System.out.println(rec.x + ", " + ypos);
					      
					      if (xpos == rec.x && ypos == rec.y) {
					    	  System.out.println("Checking if solid.");
					    	  if (MazeData.isSolid.get(k) == true) {
					    		  System.out.println("SOLID!");
					    		  exit = true;
					    	}
					      }
					   }
					}
					
					if (exit) return;

					player.posY = (player.posY <= 0 ? 0 : player.posY
							- MazeData.blockSize);

				}

This does not seem to stop it from hitting a wall.
Was This Post Helpful? 0
  • +
  • -

#9 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 05:30 PM

View PostThe_Programmer-, on 01 May 2012 - 07:54 PM, said:

Okay. So if I had x = 10, y = 10, width = 10, and height = 10. To find the boolean value of that square how would I do it?

What is the relation of these x=10, y=10, width=10, height=10 with your initial array of [40][40] ?
How do you translate these four 10 with the indexes of the initial array ?

And if you have to rebuild such indexes why do you need a HashMap ?
Was This Post Helpful? 0
  • +
  • -

#10 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 05:37 PM

View Postpbl, on 01 May 2012 - 05:30 PM, said:

View PostThe_Programmer-, on 01 May 2012 - 07:54 PM, said:

Okay. So if I had x = 10, y = 10, width = 10, and height = 10. To find the boolean value of that square how would I do it?

What is the relation of these x=10, y=10, width=10, height=10 with your initial array of [40][40] ?
How do you translate these four 10 with the indexes of the initial array ?

And if you have to rebuild such indexes why do you need a HashMap ?

Read my post below the one you just read.
Was This Post Helpful? 0
  • +
  • -

#11 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 01 May 2012 - 05:51 PM

Here, I'll post it here. This should work but doesn't:
if (kc == 'w' || event.getKeyCode() == KeyEvent.VK_UP) {
					//This will find the squares position IF it moves.
					rec.translate(0, -MazeData.blockSize);
                                        //MazeData.blockSize = 10
					
					int k = 0;
					for(int i = 0; i < MazeData.data.length; ++i) { //MazeData.data is the int[][] array.
					   for(int j = 0; j < MazeData.data[i].length; ++j) {
					      int xpos = j * MazeData.blockSize;
					      int ypos = i * MazeData.blockSize;
					      
					      System.out.println(xpos + ", " + ypos);
					      System.out.println(rec.x + ", " + ypos);
					      
					      if (xpos == rec.x && ypos == rec.y) {
					    	  System.out.println("Checking if solid.");
					    	  if (MazeData.isSolid.get(k) == true) {
					    		  System.out.println("SOLID!");
					    		  exit = true;
					    	}
					      }
					   }
					}
					
					if (exit) return;

					player.posY = (player.posY <= 0 ? 0 : player.posY
							- MazeData.blockSize);

				}


Was This Post Helpful? 0
  • +
  • -

#12 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3541
  • View blog
  • Posts: 16,135
  • Joined: 20-September 08

Re: Filling a HashMap based off of an array

Posted 02 May 2012 - 07:04 AM

Quote

if (MazeData.isSolid.get(k) == true) 


doesn't make any sense, as the value of k doesn't change. Do you mean perhaps the following?

if (MazeData.isSolid.get(k++) == true) 

Was This Post Helpful? 0
  • +
  • -

#13 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 02 May 2012 - 09:38 AM

View Postg00se, on 02 May 2012 - 07:04 AM, said:

Quote

if (MazeData.isSolid.get(k) == true) 


doesn't make any sense, as the value of k doesn't change. Do you mean perhaps the following?

if (MazeData.isSolid.get(k++) == true) 

I tried that and then if it's true I return but the player can still move through stuff.
Full code, is there a better way I can use collision detection for this based on if a squares number is equal to a certain number (I know it's messy, I don't care right now, I just want to get it working. And I know pbl will come in here saying DON'T USE THREADS FOR GRAPHICS! I know, I will fix that later.):

package me.kenneth.maze;

import javax.swing.*;

import java.awt.*;

public class Window extends JFrame {

	private static final long serialVersionUID = 1L;
	Dimension dim;
	GamePanel panel;
	Thread controls;
	Thread graphics;
	
	public Window(int width, int height) {
		super("Maze Game - Made By Kenneth Clark");
		dim = new Dimension(width, height);
		panel = new GamePanel(dim);
		setLayout(new BorderLayout());
		add(panel, BorderLayout.CENTER);
		graphics = new Thread(panel);
		
		setSize(dim);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		pack();
		System.out.println("Game set up... Running.");
		
	}
	
	public static void main(String[] args) {
		
		Window frame = new Window(400, 400);
		
		frame.startGame();
		
	}
	
	private void startGame() {
		
		graphics.start();
		panel.setFocusable(true);
		panel.requestFocus();
		
		System.out.println("Control and Graphics thread started.");
		
	}
	
	
	
}


package me.kenneth.maze;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;

public class GamePanel extends JPanel implements Runnable {

	private static final long serialVersionUID = 1L;
	private final Dimension dim;
	public Player player;
	private boolean isKeyDown = false;

	public GamePanel(final Dimension dim) {
		this.dim = dim;
		player = new Player();
		setPreferredSize(this.dim);
		setDoubleBuffered(true);
		setIgnoreRepaint(true);
		addKeyListener(new KeyC());
		requestFocus();
	}

	public void run() {

		MazeData.data = MazeData.parseFile(new File(
				"C:\\Maze\\Data\\Game.mdata"));

		while (true) {
			repaint();
			try {
				Thread.sleep(16);
			} catch (InterruptedException ee) {
				ee.printStackTrace();
				System.exit(1);
			}
		}

	}

	@Override
	public void paintComponent(Graphics g) {

		super.paintComponent(g);

		Graphics2D g2d = (Graphics2D) g;

		BufferedImage img = createGameImage();

		g2d.drawImage(img, 0, 0, 400, 400, null);
		g2d.dispose();
		requestFocus();
	}

	private BufferedImage createGameImage() {

		BufferedImage img = new BufferedImage(400, 400,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = img.createGraphics();
		graphics.setColor(Color.CYAN);

		for (int y = 0; y < MazeData.data.length; y++) {
			for (int x = 0; x < MazeData.data[y].length; x++) {
				
				final int data = MazeData.data[y][x];

				switch (data) {
				case 0:
					graphics.setColor(Color.WHITE);
					graphics.fillRect(x * MazeData.blockSize, y
							* MazeData.blockSize, MazeData.blockSize,
							MazeData.blockSize);
					break;
				case 1:
					graphics.setColor(Color.BLUE);
					graphics.fillRect(x * MazeData.blockSize, y
							* MazeData.blockSize, MazeData.blockSize,
							MazeData.blockSize);
					break;
				default:
					graphics.setColor(Color.BLACK);
					graphics.fillRect(x * MazeData.blockSize, y
							* MazeData.blockSize, MazeData.blockSize,
							MazeData.blockSize);
				}

			}
		}
		// System.out.println("Player pos: " + player.posX + ", " +
		// player.posY);
		graphics.setColor(Color.GREEN);
		graphics.fillRect(player.posX, player.posY, MazeData.blockSize,
				MazeData.blockSize);

		return img;

	}

	private class KeyC implements KeyListener {

		public void keyPressed(KeyEvent event) {

			if (!isKeyDown) {
				
				Rectangle rec = player.getRect();

				char kc = event.getKeyChar();
				
				boolean exit = false;

				if (kc == 'w' || event.getKeyCode() == KeyEvent.VK_UP) {
					
					rec.translate(0, -MazeData.blockSize);
					
					int k = 0;
					for(int i = 0; i < MazeData.data.length; ++i) {
					   for(int j = 0; j < MazeData.data[i].length; ++j) {
					      int xpos = j * MazeData.blockSize;
					      int ypos = i * MazeData.blockSize;
					      
					      System.out.println(xpos + ", " + ypos);
					      System.out.println(rec.x + ", " + ypos);
					      
					      if (xpos == rec.x && ypos == rec.y) {
					    	  System.out.println("Checking if solid.");
					    	  System.out.println(k);
					    	  if (MazeData.isSolid.get(k) == true) {
					    		  System.out.println("SOLID!");
					    		  exit = true;
					    	}
					      }
					      
					      k++;
					   }
					}
					
					if (exit) return;

					player.posY = (player.posY <= 0 ? 0 : player.posY
							- MazeData.blockSize);

				} else if (kc == 'a' || event.getKeyCode() == KeyEvent.VK_LEFT) {
					
					rec.translate(-MazeData.blockSize, 0);
					
					int k = 0;
					for(int i = 0; i < MazeData.data.length; ++i) {
					   for(int j = 0; j < MazeData.data[i].length; ++j) {
					      int xpos = j * MazeData.blockSize;
					      int ypos = i * MazeData.blockSize;
					      
					      if (xpos == rec.x && ypos == rec.y) {
					    	  if (MazeData.isSolid.get(k) == true) exit = true;
					      }

					      
					      k++;
					   }
					}
					
					if (exit) return;

					player.posX = (player.posX <= 0 ? 0 : player.posX
							- MazeData.blockSize);

				} else if (kc == 's' || event.getKeyCode() == KeyEvent.VK_DOWN) {
					
					rec.translate(0, MazeData.blockSize);
					
					int k = 0;
					for(int i = 0; i < MazeData.data.length; ++i) {
					   for(int j = 0; j < MazeData.data[i].length; ++j) {
					      int xpos = j * MazeData.blockSize;
					      int ypos = i * MazeData.blockSize;
					      
					      if (xpos == rec.x && ypos == rec.y) {
					    	  if (MazeData.isSolid.get(k) == true) exit = true;
					      }
					      
					      k++;
					   }
					}
					
					if (exit) return;

					player.posY = (player.posY >= (400 - MazeData.blockSize) ? (400 - MazeData.blockSize)
							: player.posY + MazeData.blockSize);

				} else if (kc == 'd' || event.getKeyCode() == KeyEvent.VK_RIGHT) {
					
					rec.translate(MazeData.blockSize, 0);
					
					int k = 0;
					for(int i = 0; i < MazeData.data.length; ++i) {
					   for(int j = 0; j < MazeData.data[i].length; ++j) {
					      int xpos = j * MazeData.blockSize;
					      int ypos = i * MazeData.blockSize;
					      
					      if (xpos == rec.x && ypos == rec.y) {
					    	  if (MazeData.isSolid.get(k) == true) exit = true;
					      }
					      
					      k++;
					   }
					}
					
					if (exit) return;

					player.posX = (player.posX >= (400 - MazeData.blockSize) ? (400 - MazeData.blockSize)
							: player.posX + MazeData.blockSize);

				}

				isKeyDown = true;

			}

		}

		public void keyReleased(KeyEvent event) {

			isKeyDown = false;

		}

		public void keyTyped(KeyEvent event) {

		}

		// [index] * 40 + [index]
	}

}



package me.kenneth.maze;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;

public class MazeData {
	
	public static final int blockSize = 10;
	public static int[][] data = new int[400 / blockSize][400 / blockSize];
	public static HashMap<Integer, Boolean> isSolid = new HashMap<Integer, Boolean>();
	static {
		for (int y = 0; y < data.length; y++) {
			for (int x = 0; x < data[y].length; x++) {
				data[y][x] = 3;
			}
		}
	}
	public static int[] start = {10, 20};
	
	public static int[][] parseFile(File file) {
		
		if (!file.exists()) {
			System.err.println("File does not exist!");
			return null;
		}
		
		BufferedReader in;
		int[][] returnData = new int[400 / blockSize][400 / blockSize];
		
		try {
		in = new BufferedReader(new FileReader(file));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		for (int j = 0; j < 400 / blockSize; j++) {
		
		String[] line;
		try {
		line = in.readLine().split(",");
		} catch (Exception e) {
			System.err.println("Error parsing file data.");
			return null;
		}
		
		for (int i = 0; i < 400 / blockSize; i++) {
			
			int dat;
			try {
				dat = Integer.parseInt(line[i]);
			} catch (Exception e) {
				System.err.println("Error parsing file data.");
				return null;
			}
			
			returnData[j][i] = dat;
			
		}
		
		}
		
		setUpAL();
		return returnData;
		
	}
	
	private static void setUpAL() {
		
		int k = 0;
		for(int i = 0; i < data.length; ++i) {
		   for(int j = 0; j < data[i].length; ++j) {
		      isSolid.put(k++, (data[i][j] == 1));
		   }
		}
		
	}

}



package me.kenneth.maze;

import java.awt.Rectangle;

public class Player {
	
	public int posX = 0, posY = 0;
	
	public Player() {
		posX = MazeData.start[0];
		posY = MazeData.start[1];
	}
	
	public Rectangle getRect() {
		
		Rectangle rect = new Rectangle(posX, posY, MazeData.blockSize, MazeData.blockSize);
		return rect;
		
	}

}



Example maze file:
Spoiler

Was This Post Helpful? 0
  • +
  • -

#14 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 02 May 2012 - 09:49 AM

I got it! I used MazeData.setUpAL() before I even set the values in the data array! I moved it to later in the code and now it works! Thanks for all of your help!
Was This Post Helpful? 0
  • +
  • -

#15 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Filling a HashMap based off of an array

Posted 02 May 2012 - 10:36 AM

The next thing I'm making is a maze editor because it's really hard changing a bunch of 1's and 0's to make a maze. I already added a winning square so when you step on it, the game will close and pop up another window saying you won.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1