0

I didn't know how to word the title well, but here is my question: I am making a maze game in Java, and I would like to make a class so I can set blocks easily:

addBlock(32, 32)

The first and second numbers are the x and y coordinates of where the block should be placed. I am a beginner at Java, and have come from Python.

3
  • 2
    how would you do this in Python? Commented Dec 16, 2013 at 16:43
  • 3
    Define a class Block and create a constructor that takes the two parameters... Commented Dec 16, 2013 at 16:44
  • I don't understand, do you already have the logic for this addBlock class but don't know how to construct it? Commented Dec 16, 2013 at 16:46

2 Answers 2

2

You can create a basic pojo like this:

    public class Block {
        private int x;
        private int y;

        public Block(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }

    }

You can then create a Maze class for example:

    public class Maze {

        public void addBlock(Block block) {
            // your logic here
        }

    }

The data structure to use for storing Block objects depends of the situation. I recommend a HashMap with a String key based on coordinates (if it has irregular shape) or an array/List.

HashMap version:

private Map<String, Block> blocks; // ...

public void addBlock(Block block) {
    blocks.put(block.getX()+","+block.getY(), block);
}

array version:

private Block[][] blocks; // ...

public void addBlock(Block block) {
    blocks[block.getX()][block.getY()] = block;
}

You can see that the advantage of the HashMap version is that it is dynamic. You have to initialize an array with default values.

Sign up to request clarification or add additional context in comments.

Comments

0

May be you want some high-incapsulation solutions?

public class Maze {
    private class Block {
        private int x;
        private int y;

        public Block(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    private List<Block> blocks = new ArrayList<Block>();

    public Maze addBlock(int x, int y) {
        this.blocks.add(new Block(x, y));
        return this;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.