BittahDreamer
BittahDreamer

Reputation: 113

Libgdx Draw multiple random spites from an array at different positions

I recently found out how to draw a random sprite and I wonder if I could draw multiple sprites that are completely chosen at random from my array (com.badlogic.gdx.utils.Array) at different positions and my sprites can't repeat each other (can't have more than one of the same card).

The card class

public class Spades extends CardTypes {

    public Array<Sprite> spades = new Array<Sprite>(5);

    public void cards() {
        spades.add(ace = new Sprite(new Texture("spades/AS.png")));
        spades.add(two = new Sprite(new Texture("spades/2S.png")));
        spades.add(three = new Sprite(new Texture("spades/3S.png")));
        spades.add(four = new Sprite(new Texture("spades/4S.png")));
        spades.add(five = new Sprite(new Texture("spades/5S.png")));
    }
}

The render method

public class GameScreen implements Screen {

    Sprite card;
    private Spades spading = new Spades();

    private Main game;

    //create method
    public GameScreen(Main game) {
        this.game = game;
        spading.cards();
        card = spading.spades.random();
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        Gdx.graphics.getDeltaTime();
        game.getBatch().begin();
        game.getBatch().draw(card,100,0);
        game.getBatch().end();
    }
}

Upvotes: 1

Views: 486

Answers (2)

Sebastian
Sebastian

Reputation: 6057

I have no ready-to-paste code sample for you, instead I can give you some hints to think about:

  • com.badlogic.gdx.utils.Array has a shuffle method
  • You have sprites, so use them to store the card's postion: ace.setPosition(0, 100)
  • You have sprites, so use them for drawing: ace.draw(game.getBatch())

Using these methods you should be able to draw random cards in a way that they don't change their position in every render call.

Further reading: https://github.com/libgdx/libgdx/wiki/Spritebatch,-Textureregions,-and-Sprites

Upvotes: 2

Jack Jhonsen
Jack Jhonsen

Reputation: 119

Create a loop with some Math.random values to grab a random card from your array. To ensure no card can be drawn twice you could use another array to store all previously chosen cards and for each new card first check if it isn't in that array.

For example:

Array<Sprite> drawnCards = new Array<Sprite>();
int randomCardNr = (int) Math.random() * 52;

for (int i = 0; i < amountOfCardsToBeDrawn; i++) {
    if (!drawnCards.contains(yourCardArray.get(randomCardNr)) { // Check if it hasn't been drawn before

        drawCard(yourCardArray.get(randomCardNr)); // This is your method to draw a card
        drawnCards.add(yourCardArray.get(randomCardNr)); // Add to drawnCards array
    }
}

Go wild with the random numbers to draw from different arrays if you want to.

Upvotes: 3

Related Questions