开发者

Implement a simple game in Java (Graphics-related)

I am new to game programming in Java, especially on the graphics front, hence I would like to seek some advice on how to implement the following game graphically in Java.

The game is very simple, it displays a square which is further divided into a 2x2 boxes, and the game playing is to put a 开发者_JAVA百科total of 44 chips into these 4 boxes, and the user should be able to drag and drop the chips from one box to another.

That's it! My questions:

  1. is there ready-made library I can use for drawing the square consists of the 4 boxes as well as the chips?
  2. if the answer to 1) is no, then is there any tutorial I can follow to program them myself?
  3. How to implement the drag and drop part graphically?

Many thanks.


Chips can be represented by an Icon added to a JLabel.

Squares can be represented by a JPanel.

Start by reading the section from the Swing tutorial on How to Use Icons. There are other section of interest as well: How to Use Panels, Using Layout Managers, How to Write a MouseListener, The section on drag and drop maybe.


I would use a Canvas and override paint(Graphics g) and draw your various elements using that. Then you can call repaint() with a timer or a game loop.

public class MyCanvas extends Canvas
{
    public void gameLoop()
    {
        //Don't do it this way, this is just a quick example.
        //Instead look up better game loop options.
        while (true)
        {
            repaint(); //automatically calls paintComponent
            Thread.yield();
        }
    }

    //Put all the stuff that gets drawn in here.
    //@Override
    public void paint(Graphics g)
    {
        super.paint(g);

        for (int i = 0; i < chips.size(); i++)
        {
            chips.get(i).draw(g);
        }
    }
}

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

    public void draw(Graphics g)
    {
        g.setColor(Color.BROWN);
        g.fillRect(x, y, 50, 50);
        //etc.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜