Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libGDX: Create grid for board game

I am trying to create a simple board game using libGDX. Just that you have a rough idea of what I'm trying to do, imagine Bejeweled (though mine of course is not as complex).

The game involves a board with cells as squares. Depending on the level, this grid has a different number of cells, like 6x6 or 8x8. I also want to include some nice animation for switching the position of two neighboring cells (like in Bejeweled). Of course there also need to be some buttons on the screen.

My question is: What is the best way to do this? Shall I use a stage and then tables for the grid? Can I then still easily make an animation (using the Universal Tween Engine)? Or is it better to draw the Sprites individually? Or is there another completely different way of approaching this?

Thank you for your answers,

Cheers,

Tony

like image 354
tomet Avatar asked Jan 29 '14 22:01

tomet


1 Answers

Sprite square = new Sprite(new Texture("texture"));

Render

float squareWidth = camera.viewportWidth / squaresOnWidth;
float squareHeight = camera.viewportHeight / squaresOnHeight;
square.setWidth(squareWidth);
square.setHeight(squareHeight);
batch.begin(); `
for(int y = 0; y < squaresOnHeight; y++){
    for(int x = 0; x < squaresOnWidth; x++){
        square.setX(x * squareWidth);
        square.setY(y * squareHeight);
        square.draw(batch);
     }
 }
 batch.end();

This should output a grid of textures, not tested.

If you want to create smooth animation you should definitely look into UniveralTweenEngine, here's a demo of what it can do : http://www.aurelienribon.com/universal-tween-engine/gwt/demo.html

If you want the grid in buttons instead.

OrthoGraphicCamera camera = new OrthoGraphicCamera();
camera.setToOrtho(false, yourViewportWidth, yourViewportHeight);
camera.translate(xPos, yPos);
Stage stage = new Stage(your wanted stage width, your wanted stage height, false, batch);
stage.setCamera(camera); 
for(int y = 0; y < buttonsOnHeight; y++){
    for(int x = 0; x < buttonsOnWidth; x++){
       stage.addActor(new TextButton("" + x + y * buttonsOnWidth, textButtonStyle); 
    }
 }

The render

float buttonWidth = camera.viewportWidth / buttonsOnWidth;
float buttonHeight = camera.viewportHeight / buttonsOnHeight;
for(int y = 0; y < buttonsOnHeight; y++){
    for(int x = 0; x < buttonsOnWidth; x++){
        TextButton button = stage.getActors().get(x + y * buttonsOnWidth);
        button.setX(x * buttonWidth);
        button.setY(y * buttonHeight);
        button.setWidth(buttonWidth);
        button.setHeight(buttonHeight);
     }
 }

Then draw the stage, note that you should stop any batch that's currently running because stage has it's own batch.begin() and batch.end(). You could start your batch again after stage.draw();

 stage.act(delta);
 stage.draw();
like image 113
thetheodor Avatar answered Oct 02 '22 14:10

thetheodor