Pergunta

I'm trying to use GridWorld (from the AP computer science curriculum) for making a game, and I'm having problems with using multiple grids. World's setGrid method doesn't seem to work. I was under the impression that you could have multiple grid objects co-existing, and that the current one pointed to by the World is the one that gets drawn in the GUI. But that's not what happens... when I call the World's setGrid and pass it a grid, the grid seems to only LOGICALLY be set, and System.out.printing it gives the correct results of its actors and their current positions, but the GUI doesn't update and you can't actually see the grid.

I wrote a simple ActorWorld to illustrate this:

public static void main(String[] args) throws Exception
{
            ActorWorld x = new ActorWorld()
            {
                    Grid<Actor> gr1 = new BoundedGrid<Actor>(10,10);
                    Grid<Actor> gr2 = new BoundedGrid<Actor>(10,10);


                    public void step()
                    {
                            new Actor().putSelfInGrid(gr1, new Location(1,1));
                            new Actor().putSelfInGrid(gr2, new Location(9,9));
                            if (getGrid() == gr2)
                                    setGrid(gr1);
                            else
                                    setGrid(gr2);
                            System.out.println(getGrid());
                    }
            };
            x.show();
}

Every step it's supposed to change to the other grid and display it, so basically what SHOULD be happening is one Actor in the grid changing location from (1,1) to (9,9). But in fact, it just displays an empty grid (because it's using the original grid it made in the default constructor, since I didn't provide one). What's going on? How do I get it to paint the current grid?

Foi útil?

Solução

Okay, I found the problem. Upon e-mailing gridworld's creator, he revealed that this is a bug.

I found the source code and added the line

display.setGrid(world.getGrid());

to the beginning of WorldFrame's repaint() method. The problem was that WorldFrame itself updates its current Grid, so logically it's on the right one, but the WorldFrame's GridPanel object, display, which is actually the JPanel that the grid is drawn in, does not get told to update its grid prior to the repaint. With this, the complete method is

public void repaint()
{
    display.setGrid(world.getGrid());
    String message = getWorld().getMessage();
    if (message == null)
        message = resources.getString("message.default");
    messageArea.setText(message);
    messageArea.repaint();
    display.repaint(); // for applet
    super.repaint();
}

and all is well. :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top