-1

I am making a side scroller where if the user is hit by a fireball or an enemy the program should -1 from the amounts of lives. This is drawn to the user on the screen like so; 'Lives: 3'.

Although I have succeeded in achieving this, I am instead trying to make it so the number of lives is displayed in the form of hearts. This is so the game will have a more appealing user interface to look forward to. Essentially the idea is When one life is lost then the string drawn will go from this: 'Lives: ❤❤❤' to 'Lives: ❤❤' .

Here is my code that works on doing this:

public class GamePanel extends JPanel 
     private static final int MAX_HITS = 10;
     private int numHits = 0;

     public void sequenceEnded(String imageName) { 
     showExplosion = false;
     explosionPlayer.restartAt(0);

     if (numHits >= MAX_HITS) { 
         gameOver = true; 
         score = (int) ((System.nanoTime() - gameStartTime)/1000000000L);
     }

     private void reportStats(Graphics g) { 
        if (!gameOver)  
            timeSpentInGame = (int) ((System.nanoTime() -gameStartTime)/1000000000L);
        g.setColor(Color.red);
        g.setFont(msgsFont);
        int lives = MAX_HITS - numHits;
        g.drawString("Lives: " + lives + " ❤", 15, 25);
    } 

Anyone have any ideas as to how I can go from this: 'Lives = 10 ❤' to
'Lives = ❤❤❤❤❤❤❤❤❤❤' with a working array which will reduce the number of hearts from the string?

3 Answers3

1

Using the stream API:

String lives = Stream.generate(() -> "❤")
                     .limit(lives)
                     .collect(joining("", "Lives: ", ""));

g.drawString(lives, 15, 25);

or another method available since JDK8 (join):

g.drawString(String.join("", Collections.nCopies(lives, "❤")), 15, 25);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Wouldn't it be faster to use a StringBuilder and a simple loop rather than the Stream method ? – Alice Oualouest Nov 17 '18 at 19:43
  • 1
    @AliceOualouest not having a go at you but why is everyone "soo much" into "time complexity, time complexity...? sometimes go for readability... – Ousmane D. Nov 17 '18 at 19:44
  • well, then I'd say it's more readable to do `String.join("", Collections.nCopies(lives, "❤"));` or in Java 11 `"❤".repeat(lives)` – UninformedUser Nov 17 '18 at 19:47
0

You could use a loop to create a new hearts string, and then use that.

String hearts = "";
for (int i = 0; i < lives; i++) {
    hearts += "❤";
}

g.drawString("Lives: " + hearts, 15, 25);
Benjamin Miller
  • 159
  • 1
  • 11
0

I give you the basic idea.

int lives = 10;
String livesString = "Lives = ";

for (int i = 0; i < lives; i++) {
   livesString += "❤";
}

Put this for loop in the separate method and use it with new arguments every time a live is lost.

Artyom Rebrov
  • 651
  • 6
  • 23