AeroFighter76 AeroFighter76 - 3 months ago 13
Java Question

How to drawString() only once

I have a program where the user is traveling in a grid and has to kill an enemy. When they do so, a message comes up stating that the user has heard a scream.

This message is only supposed to display once when the user fires their weapon. I made the message display if the following method was true:

public boolean deadWumpus()
{
for(int x=0;x<10;x++)
{
for(int y=0;y<10;y++)
{
if(map.grid[x][y].getDeadWumpus()==true)
return true;
}
}
return false;
}


I then have a line in my paint() method which states that if this method is true then display the message. However, this keeps on displaying as there is no regulator to tell it to run only once when the user fires.
I attempted to create an int to ensure it only runs once:

// at beginning of program
int once=0;
//in paint()
if(once==0){
if(deadWumpus()==true)
{
g.drawString("You hear a scream.",300,675);

}
}
once++;


Using this it never displays the message. Is there a way I can get the message to only display once when the user shoots and then disappear once the user makes their next move?
Thanks.

Answer

The paint() method is called every time a frame of your game is drawn on the screen. When you make it drawn "only once," you made it literally draw "only once," as in, for only one frame, since frames are being update really fast, the text flashes and then never shows up again. I recommend having something like this:

long userFired;

// when the user fires -> userFired = System.currentTimeMillis();

paint() { /*the "2000" means that the text will display for 2 seconds*/
    if(System.currentTimeMillis()-userFired < 2000 && deadWumpus()==true) {
        g.drawString("You hear a scream.",300,675);
    }
}