Reset Countdown Timer with new Parameters Android - java

I'm trying to reset my Countdown Timer with new variables (a new time), but nothing I do seems to work. Anyone know how to do this?
private long cdTime = 30000;
private long percentageTime = 30;
private void createCDTimer(){
mCountDownTimer = new CountDownTimer(cdTime, 1000) {
public void onTick(long millisUntilFinished) {
score = millisUntilFinished / 1000;
percentage = percentage - (100 / percentageTime);
cdTime = millisUntilFinished;
percentageTime = millisUntilFinished / 1000;
}
public void onFinish() {
score = 0;
percentage = 0;
}
}.start();
}
this code is in another class/void {
mCountDownTimer.cancel();
cdTime = cdTime + 20000;
percentageTime = percentageTime + 20;
mCountDownTimer.start();
}
Thanks in advance.
EDIT:
Here's the rest of my code for those who need it:
public class GameView extends SurfaceView implements Runnable {
Context context;
private Thread gameThread = null;
private SurfaceHolder ourHolder;
private volatile boolean playing;
private boolean paused = true;
private Canvas canvas;
private Paint paint;
private long fps;
private long thisTimeFrame;
private int screenX;
private int screenY;
private int column1;
private int column2;
private int column3;
private float enemyMDrop;
private float enemyMY;
private float enemyLDrop;
private float enemyLY;
private float enemyRDrop;
private float enemyRY;
private Random randomGen = new Random();
private int loadBarAnim;
private float loadBarTimer;
private float gameTimer;
private long percentage = 100;
private CountDownTimer mCountDownTimer;
private long cdTime;
private long percentageTime;
private Compressor compressor;
private loadingBar loadBar;
private loadingBarAnimation loadBarAnimation;
private EnemyMid enemyM;
private EnemyLeft enemyL;
private EnemyLeft enemyR;
private float mTimer;
private float lTimer;
private float rTimer;
private float enemyMWait;
private float enemyLWait;
private float enemyRWait;
private float enemyMTimer;
private float enemyLTimer;
private float enemyRTimer;
private boolean enemyMGo;
private boolean enemyLGo;
private boolean enemyRGo;
private SoundPool soundPool;
private int deathSound = -1;
private int liveSound = -1;
private int shootSound = -1;
private int gameMusic = -1;
private long score;
String scoreText = "Score: ";
//String scoreView = String.format("%.02f", score);
private int lives = 3;
public GameView (Context context, int x, int y){
super(context);
this.context = context;
ourHolder = getHolder();
paint = new Paint();
screenX = x;
screenY = y;
prepeareLevel();
}
private void createCDTimer(){
mCountDownTimer = new CountDownTimer(cdTime, 1000) {
public void onTick(long millisUntilFinished) {
score = millisUntilFinished / 1000;
percentage = percentage - (100 / percentageTime);
cdTime = millisUntilFinished;
percentageTime = millisUntilFinished / 1000;
}
public void onFinish() {
score = 0;
percentage = 0;
}
}.start();
}
private void prepeareLevel (){
cdTime = 30000;
percentageTime = 30;
createCDTimer();
loadBarAnim = 1;
column1 = screenX / 3;
column2 = (screenX / 3 ) * 2;
column3 = (screenX / 3 ) * 3;
compressor = new Compressor(context, screenX, screenY);
loadBar = new loadingBar(context, screenX, screenY);
loadBarAnimation = new loadingBarAnimation(context, screenX, screenY, 2);
enemyM = new EnemyMid(context, screenX, screenY);
enemyL = new EnemyLeft(context, screenX, screenY);
enemyR = new EnemyLeft(context, screenX, screenY);
mTimer = 0;
lTimer = 0;
rTimer = 0;
enemyMTimer = 2;
enemyLTimer = 0;
enemyRTimer = 5;
enemyMGo = false;
enemyLGo = false;
enemyRGo = false;
enemyMDrop = 0;
enemyLDrop = 0;
enemyRDrop = 0;
enemyMWait = randomGen.nextInt((5 - 1) + 1);
enemyLWait = randomGen.nextInt((5 - 1) + 1);
enemyRWait = randomGen.nextInt((5 - 1) + 1);
}
#Override
public void run(){
while (playing){
long startFrameTime = System.currentTimeMillis();
if(!paused){
update();
}
draw();
thisTimeFrame = System.currentTimeMillis() - startFrameTime;
if(thisTimeFrame >= 1){
fps = 1000/thisTimeFrame;
}
}
}
private void update(){
boolean finished = false;
if (finished){
}
}
private void draw(){
if(ourHolder.getSurface().isValid()){
canvas = ourHolder.lockCanvas();
if(rTimer < 30){
rTimer++;
}
else {
rTimer = 0;
if (enemyRTimer >= enemyRWait-1){
enemyRGo = true;
enemyRTimer = 0;
}
else if (!enemyRGo){
enemyRTimer++;
}
}
if(mTimer < 30){
mTimer++;
}
else {
mTimer = 0;
if (enemyMTimer >= enemyMWait-1){
enemyMGo = true;
enemyMTimer = 0;
}
else if (!enemyMGo){
enemyMTimer++;
}
}
if(lTimer < 30){
lTimer++;
}
else {
if (enemyLTimer >= enemyLWait-1){
enemyLGo = true;
enemyLTimer = 0;
}
else if (!enemyLGo){
enemyLTimer++;
}
}
canvas.drawColor(Color.WHITE);
paint.setColor(Color.BLACK);
if (enemyMGo){
enemyMDrop = enemyMDrop - 10;
enemyMY = enemyM.getY() - enemyMDrop;
}
if (enemyMY > 1200) {
enemyMDrop = 0;
enemyMY = 0;
enemyMGo = false;
enemyMTimer = 0;
enemyMWait = randomGen.nextInt((5 - 1) + 1);
mCountDownTimer.cancel();
cdTime = cdTime + 20000;
percentageTime = percentageTime + 20;
mCountDownTimer = new CountDownTimer(cdTime, 1000) {
public void onTick(long millisUntilFinished) {
score = millisUntilFinished / 1000;
percentage = percentage - (100 / percentageTime);
cdTime = millisUntilFinished;
percentageTime = millisUntilFinished / 1000;
}
public void onFinish() {
score = 0;
percentage = 0;
}
};
mCountDownTimer.start();
}
if (enemyLGo){
enemyLDrop = enemyLDrop - 10;
enemyLY = enemyL.getY() - enemyLDrop;
}
if (enemyLY > 1200) {
enemyLDrop = 0;
enemyLY = 0;
enemyLGo = false;
enemyLTimer = 0;
enemyLWait = randomGen.nextInt((5 - 1) + 1);
}
if (enemyRGo){
enemyRDrop = enemyRDrop - 10;
enemyRY = enemyR.getY() - enemyRDrop;
}
if (enemyRY > 1200) {
enemyRDrop = 0;
enemyRY = 0;
enemyRGo = false;
enemyRTimer = 0;
enemyRWait = randomGen.nextInt((5 - 1) + 1);
}
//Draw the invaders
canvas.drawBitmap(enemyL.getBitmap(), (column1 - enemyL.getX()) - (column1 / 4), enemyLY, paint);
canvas.drawBitmap(enemyM.getBitmap(), (column2 - enemyM.getX()) - (column1 / 4), enemyMY, paint);
canvas.drawBitmap(enemyR.getBitmap(), (column3 - enemyL.getX()) - (column1 / 4), enemyRY, paint);
//draw the compressor
canvas.drawBitmap(compressor.getBitmap(), 0, 0, paint);
//draw the animated loading bar
if (loadBarTimer > 2){
loadBarTimer = 0;
if (loadBarAnim == 1){
loadBarAnim = 2;
}
else if (loadBarAnim == 2){
loadBarAnim = 3;
}
else if (loadBarAnim == 3){
loadBarAnim = 4;
}
else {
loadBarAnim = 1;
}
}
else {
loadBarTimer++;
}
if (loadBarAnim == 1) {
canvas.drawBitmap(loadBarAnimation.getBitmap1(), 19, 1300, paint);
}
else if (loadBarAnim == 2){
canvas.drawBitmap(loadBarAnimation.getBitmap2(), 19, 1300, paint);
}
else if (loadBarAnim == 3) {
canvas.drawBitmap(loadBarAnimation.getBitmap3(), 19, 1300, paint);
}
else {
canvas.drawBitmap(loadBarAnimation.getBitmap4(), 19, 1300, paint);
}
//draw the loading bar
canvas.drawBitmap(loadBar.getBitmap(), 20, 1300, paint);
//Draw the Score
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Time: " + score, 100, 1600, paint);
//Draw the Percentage
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Percentage: " + percentage, 725, 1600, paint);
ourHolder.unlockCanvasAndPost(canvas);
}
}
//Paused or Stopped
public void pause(){
playing = false;
try{
gameThread.join();
}
catch (InterruptedException e){
Log.e("Error: ", "Error joining thread");
}
}
//Resume
public void resume(){
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
public boolean onTouchEvent(MotionEvent motionEvent){
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK){
//player touches the screen
case MotionEvent.ACTION_DOWN:
paused = false;
if (motionEvent.getX() > screenX - column1 && enemyRY > 200){
if (motionEvent.getY() < screenY) {
enemyRWait = randomGen.nextInt((5 - 1) + 1);
enemyRY = 0;
enemyRDrop = 0;
enemyRGo = false;
enemyRTimer = 0;
rTimer = 0;
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
paint.setColor(Color.BLACK);
//Draw the invaders
canvas.drawBitmap(enemyL.getBitmap(), (column1 - enemyL.getX()) - (column1 / 4), enemyLY, paint);
canvas.drawBitmap(enemyM.getBitmap(), (column2 - enemyM.getX()) - (column1 / 4), enemyMY, paint);
canvas.drawBitmap(enemyR.getBitmap(), (column3 - enemyL.getX()) - (column1 / 4), enemyRY, paint);
//draw the compressor
canvas.drawBitmap(compressor.getBitmap(), 0, 0, paint);
//draw the animated loading bar
if (loadBarTimer > 2){
loadBarTimer = 0;
if (loadBarAnim == 1){
loadBarAnim = 2;
}
else if (loadBarAnim == 2){
loadBarAnim = 3;
}
else if (loadBarAnim == 3){
loadBarAnim = 4;
}
else {
loadBarAnim = 1;
}
}
else {
loadBarTimer++;
}
if (loadBarAnim == 1) {
canvas.drawBitmap(loadBarAnimation.getBitmap1(), 19, 1300, paint);
}
else if (loadBarAnim == 2){
canvas.drawBitmap(loadBarAnimation.getBitmap2(), 19, 1300, paint);
}
else if (loadBarAnim == 3) {
canvas.drawBitmap(loadBarAnimation.getBitmap3(), 19, 1300, paint);
}
else {
canvas.drawBitmap(loadBarAnimation.getBitmap4(), 19, 1300, paint);
}
//draw the loading bar
canvas.drawBitmap(loadBar.getBitmap(), 20, 1300, paint);
//Draw the Score
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Time: " + score, 100, 1600, paint);
//Draw the Percentage
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Percentage: " + percentage, 725, 1600, paint);
ourHolder.unlockCanvasAndPost(canvas);
}
}
if (motionEvent.getX() > screenX - column2 && motionEvent.getX() < screenX - column1 && enemyMY > 200){
if (motionEvent.getY() < screenY) {
enemyMWait = randomGen.nextInt((5 - 1) + 1);
enemyMY = 0;
enemyMDrop = 0;
enemyMGo = false;
enemyMTimer = 0;
mTimer = 0;
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
paint.setColor(Color.BLACK);
//Draw the invaders
canvas.drawBitmap(enemyL.getBitmap(), (column1 - enemyL.getX()) - (column1 / 4), enemyLY, paint);
canvas.drawBitmap(enemyM.getBitmap(), (column2 - enemyM.getX()) - (column1 / 4), enemyMY, paint);
canvas.drawBitmap(enemyR.getBitmap(), (column3 - enemyL.getX()) - (column1 / 4), enemyRY, paint);
//draw the compressor
canvas.drawBitmap(compressor.getBitmap(), 0, 0, paint);
//draw the animated loading bar
if (loadBarTimer > 2){
loadBarTimer = 0;
if (loadBarAnim == 1){
loadBarAnim = 2;
}
else if (loadBarAnim == 2){
loadBarAnim = 3;
}
else if (loadBarAnim == 3){
loadBarAnim = 4;
}
else {
loadBarAnim = 1;
}
}
else {
loadBarTimer++;
}
if (loadBarAnim == 1) {
canvas.drawBitmap(loadBarAnimation.getBitmap1(), 19, 1300, paint);
}
else if (loadBarAnim == 2){
canvas.drawBitmap(loadBarAnimation.getBitmap2(), 19, 1300, paint);
}
else if (loadBarAnim == 3) {
canvas.drawBitmap(loadBarAnimation.getBitmap3(), 19, 1300, paint);
}
else {
canvas.drawBitmap(loadBarAnimation.getBitmap4(), 19, 1300, paint);
}
//draw the loading bar
canvas.drawBitmap(loadBar.getBitmap(), 20, 1300, paint);
//Draw the Score
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Time: " + score, 100, 1600, paint);
//Draw the Percentage
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Percentage: " + percentage, 725, 1600, paint);
ourHolder.unlockCanvasAndPost(canvas);
}
}
if (motionEvent.getX() > screenX - column3 && motionEvent.getX() < screenX - column2 && enemyLY > 200){
if (motionEvent.getY() < screenY) {
enemyLWait = randomGen.nextInt((5 - 1) + 1);
enemyLY = 0;
enemyLDrop = 0;
enemyLGo = false;
enemyLTimer = 0;
lTimer = 0;
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
paint.setColor(Color.BLACK);
//Draw the invaders
canvas.drawBitmap(enemyL.getBitmap(), (column1 - enemyL.getX()) - (column1 / 4), enemyLY, paint);
canvas.drawBitmap(enemyM.getBitmap(), (column2 - enemyM.getX()) - (column1 / 4), enemyMY, paint);
canvas.drawBitmap(enemyR.getBitmap(), (column3 - enemyL.getX()) - (column1 / 4), enemyRY, paint);
//draw the compressor
canvas.drawBitmap(compressor.getBitmap(), 0, 0, paint);
//draw the animated loading bar
if (loadBarTimer > 2){
loadBarTimer = 0;
if (loadBarAnim == 1){
loadBarAnim = 2;
}
else if (loadBarAnim == 2){
loadBarAnim = 3;
}
else if (loadBarAnim == 3){
loadBarAnim = 4;
}
else {
loadBarAnim = 1;
}
}
else {
loadBarTimer++;
}
if (loadBarAnim == 1) {
canvas.drawBitmap(loadBarAnimation.getBitmap1(), 19, 1300, paint);
}
else if (loadBarAnim == 2){
canvas.drawBitmap(loadBarAnimation.getBitmap2(), 19, 1300, paint);
}
else if (loadBarAnim == 3) {
canvas.drawBitmap(loadBarAnimation.getBitmap3(), 19, 1300, paint);
}
else {
canvas.drawBitmap(loadBarAnimation.getBitmap4(), 19, 1300, paint);
}
//draw the loading bar
canvas.drawBitmap(loadBar.getBitmap(), 20, 1300, paint);
//Draw the Score
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Time: " + score, 100, 1600, paint);
//Draw the Percentage
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Percentage: " + percentage, 725, 1600, paint);
ourHolder.unlockCanvasAndPost(canvas);
}
}
break;
}
return true;
}
}
Error codes:
11-22 06:41:46.164 9091-9146/au.com.webanddesignbros.loadingbarsimulator W/dalvikvm: threadid=12: thread exiting with uncaught exception (group=0xa65f7228)
11-22 06:41:46.174 9091-9146/au.com.webanddesignbros.loadingbarsimulator E/AndroidRuntime: FATAL EXCEPTION: Thread-206
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:121)
at android.os.CountDownTimer$1.(CountDownTimer.java:109)
at android.os.CountDownTimer.(CountDownTimer.java:109)
at au.com.webanddesignbros.loadingbarsimulator.GameView$2.(GameView.java:0)
at au.com.webanddesignbros.loadingbarsimulator.GameView.draw(GameView.java:250)
at au.com.webanddesignbros.loadingbarsimulator.GameView.run(GameView.java:164)
at java.lang.Thread.run(Thread.java:856)

You are canceling the countdown and starting it again without every setting the new time values.
You are in fact only changing your cdTime and percentageTime variables. You should create a new countdown timer with these updated values.
mCountDownTimer.cancel();
cdTime = cdTime + 20000;
percentageTime = percentageTime + 20;
//Create a countdown timer with the updated time
mCountDownTimer = new CounDownTimer(cdTime, anInterval){
/* handle the countdown notifications as you wish, for example like you did in your question */
}
mCountDownTimer.start();
In order to validate that the code above should work a test app has been made. The code and apk are available at this repository : https://github.com/ySiggen/CDTimerTest
After the stack trace has been added to the question, this answer has been edited with the following:
The error you get means that you are calling code (the count down timer) from a background thread while it should be done from the main thread.
You can use a Handler to call the code from another thread like this:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCountDownTimer = new CountDownTimer(cdTime, 1000) {
/* handle the countdown notifications as you wish, for example like you did in your question */
}.start();
}
});

Related

Delay with spawning Zombies?

I'm trying to spawn zombies with a second delay between each spawn but having no luck, There is no delay still even with my timer and it seems to be looping but I'm not sure what I'm doing wrong???
Anyone could help would be appreciated <3
public class Zombie extends GameObject{
Rectangle[] zombies = new Rectangle[60];
Timer timer = new Timer();
public Zombie(float x, float y, ID id, SpriteSheet ss) {
super(x, y, id, ss);
Delay();
}
public void Delay(){
timer.schedule(task, 0, 1000);
}
TimerTask task = new TimerTask(){
public void run(){
for(int i = 0; i < zombies.length; i++){
Random rand = new Random();
int result = rand.nextInt(6);
if(result == 0){
x = 1000;
y = 200;
}
if(result == 1){
x = 100;
y = 200;
}
if(result == 2){
x = 100;
y = 600;
}
if(result == 3){
x = 1000;
y = 600;
}
if(result == 4){
x = 100;
y = 900;
}
if(result == 5){
x = 1000;
y = 900;
}
zombies[i] = new Rectangle((int)x, (int)y, 32, 48);
if(i >= zombies.length){
task.cancel();
}
}
}
};
public void tick() {
}
public void render(Graphics g) {
for(int i = 0; i < zombies.length; i++){
g.setColor(Color.YELLOW);
g.fillRect((int)zombies[i].x, (int)zombies[i].y, 32, 48);
}
}
public Rectangle getBounds() {
return new Rectangle((int)x, (int)y, 32, 48);
}
}
Check out the changes below. I haven't tested this, but I think it will work. I added the spawnedZombies counter and removed your for loop. I also changed the condition that stops the timer task.
I do agree with Michael's comment that this is confusing that you have 60 zombies inside the zombie class but that is another discussion :)
Rectangle[] zombies = new Rectangle[60];
Timer timer = new Timer();
int spawnedZombies = 0;
public Zombie(float x, float y, ID id, SpriteSheet ss) {
super(x, y, id, ss);
Delay();
}
public void Delay(){
timer.schedule(task, 0, 1000);
}
TimerTask task = new TimerTask()
{
public void run()
{
Random rand = new Random();
int result = rand.nextInt(6);
if(result == 0){
x = 1000;
y = 200;
}
if(result == 1){
x = 100;
y = 200;
}
if(result == 2){
x = 100;
y = 600;
}
if(result == 3){
x = 1000;
y = 600;
}
if(result == 4){
x = 100;
y = 900;
}
if(result == 5){
x = 1000;
y = 900;
}
spawnedZombies++;
zombies[spawnedZombies - 1] = new Rectangle((int)x, (int)y, 32, 48);
if(spawnedZombies == zombies.length){
task.cancel();
}
}
};

Save currentTime as long (AndroidStudio/libgdx

I am currently coding a game with Android Studio in the style of FlappyBird. I have two Cooldowns that give the user the possibility to use extra abilities.
In the main game view you can see 2 images that are grey and a timer under them. The timer goes from 10 to 0 and when zero is reached the number disappears, the image gets colored and the user knows he is able to activate the ability in the pause screen.
The problem:
When the game is starting the timer starts also and goes down as i wanted. But if the user enters the Pause Menu the Timer should stop and if he leaves it the Timer should run again.
I have a
long startTime = 0;
and a
long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
It all works but I cannot save the current time in a long and can't find any function for it!
I know the code is very long but the important part is in the drawWorld()-method in the if statement GameState.Running.
public class PlaneGame extends ApplicationAdapter{
private static final float PLANE_JUMP_IMPULSE = 350;
private static final float GRAVITY = -20;
private static final float PLANE_VELOCITY_X = 200;
private static final float PLANE_START_Y = 240;
private static final float PLANE_START_X = 50;
private static final int STATE_START = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_OVER = 2;
SpriteBatch batch;
OrthographicCamera camera;
OrthographicCamera uiCamera;
Texture background;
TextureRegion ground;
float groundOffsetX = 0;
TextureRegion ceiling;
TextureRegion rock;
TextureRegion rockDown;
TextureRegion planeSmall;
TextureRegion planeSmallBlack;
Animation plane;
TextureRegion ready;
TextureRegion gameOver;
TextureRegion pause;
BitmapFont font;
Vector2 planePosition = new Vector2();
Vector2 planeVelocity = new Vector2();
float planeStateTime = 0;
Vector2 gravity = new Vector2();
Array<Rock> rocks = new Array<Rock>();
GameState gameState = GameState.Start; /*neeeeeeewwwww*/
int score = 0;
long startTime = 0;
long startTime2;
long elapsedTime;
long savedTime;
boolean wantToSeeTime = true;
boolean wantToSeeTimePause = true;
float timeCdRock = 0;
float timeCdPlane = 0;
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
Music music;
Sound point;
Sound explode;
//this gets called repeatedly to run the game
#Override
public void render () {
//clear the screen so we can draw the next one
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
long saveTime = elapsedTime;
//update the position of the plane and rocks
updateWorld();
elapsedTime = saveTime;
//now draw the updated screen
drawWorld();
}
//initialize objects and load assets when game starts
#Override
public void create () {
startTime = TimeUtils.nanoTime(); /*Neeeewwwwwwwww !!!*/
Gdx.input.setInputProcessor(new GestureDetector(new MyGestureListener()));
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
uiCamera = new OrthographicCamera();
uiCamera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
uiCamera.update();
font = new BitmapFont(Gdx.files.internal("arial.fnt"));
background = new Texture("background.png");
ground = new TextureRegion(new Texture("ground.png"));
ceiling = new TextureRegion(ground);
ceiling.flip(true, true);
rock = new TextureRegion(new Texture("rock.png"));
rockDown = new TextureRegion(rock);
rockDown.flip(false, true);
Texture frame1 = new Texture("plane1.png");
frame1.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture frame2 = new Texture("plane2.png");
Texture frame3 = new Texture("plane3.png");
planeSmall = new TextureRegion(new Texture("planeSmall.png"));
planeSmallBlack = new TextureRegion(new Texture("planeSmallBlack.png"));
ready = new TextureRegion(new Texture("ready.png"));
gameOver = new TextureRegion(new Texture("gameover.png"));
pause = new TextureRegion(new Texture("pause.png"));
plane = new Animation(0.05f, new TextureRegion(frame1), new TextureRegion(frame2), new TextureRegion(frame3), new TextureRegion(frame2));
plane.setPlayMode(PlayMode.LOOP);
music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
music.setLooping(true);
music.play();
point = Gdx.audio.newSound(Gdx.files.internal("point.ogg"));
explode = Gdx.audio.newSound(Gdx.files.internal("explode.wav"));
resetWorld();
}
//reset the state of the game
private void resetWorld() {
score = 0;
startTime = 0;
groundOffsetX = 0;
planePosition.set(PLANE_START_X, PLANE_START_Y);
planeVelocity.set(0, 0);
gravity.set(0, GRAVITY);
camera.position.x = 400;
//randomize the position and direction of the rocks
rocks.clear();
for(int i = 0; i < 5; i++) {
boolean isDown = MathUtils.randomBoolean();
rocks.add(new Rock(700 + i * 200, isDown?480-rock.getRegionHeight(): 0, isDown? rockDown: rock));
}
}
//use the time elapsed since the last call to render() to determine how much to update the game
private void updateWorld() {
float deltaTime = Gdx.graphics.getDeltaTime();
planeStateTime += deltaTime;
/*if(Gdx.input.justTouched()) {
if(gameState == STATE_START) {
gameState = STATE_RUNNING;
}
if(gameState == STATE_RUNNING) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == STATE_OVER) {
gameState = STATE_START;
resetWorld();
}
}*/
if(gameState != GameState.Start) planeVelocity.add(gravity);
planePosition.mulAdd(planeVelocity, deltaTime);
camera.position.x = planePosition.x + 350;
if(camera.position.x - groundOffsetX > ground.getRegionWidth() + 400) {
groundOffsetX += ground.getRegionWidth();
}
rect1.set(planePosition.x + 20, planePosition.y, plane.getKeyFrames()[0].getRegionWidth() - 20, plane.getKeyFrames()[0].getRegionHeight());
for(Rock r: rocks) {
//if the rock is off the screen, give it a new location in front of the plane
if(camera.position.x - r.position.x > 400 + r.image.getRegionWidth()) {
boolean isDown = MathUtils.randomBoolean();
r.position.x += 5 * 200;
r.position.y = isDown?480-rock.getRegionHeight(): 0;
r.image = isDown? rockDown: rock;
r.counted = false;
}
rect2.set(r.position.x + (r.image.getRegionWidth() - 30) / 2 + 20, r.position.y, 20, r.image.getRegionHeight() - 10);
//check if the plane crashed
if(rect1.overlaps(rect2)) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
//award a point for not crashing into a rock
if(r.position.x < planePosition.x && !r.counted) {
score++;
r.counted = true;
point.play();
}
}
//check if the plane crashed
if(planePosition.y < ground.getRegionHeight() - 20 ||
planePosition.y + plane.getKeyFrames()[0].getRegionHeight() > 480 - ground.getRegionHeight() + 20) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
}
//draw the background, rocks, and plane to the screen and possibly some ui text
private void drawWorld() {
elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, camera.position.x - background.getWidth() / 2, 0);
for(Rock rock: rocks) {
batch.draw(rock.image, rock.position.x, rock.position.y);
}
batch.draw(ground, groundOffsetX, 0);
batch.draw(ground, groundOffsetX + ground.getRegionWidth(), 0);
batch.draw(ceiling, groundOffsetX, 480 - ceiling.getRegionHeight());
batch.draw(ceiling, groundOffsetX + ceiling.getRegionWidth(), 480 - ceiling.getRegionHeight());
batch.draw(plane.getKeyFrame(planeStateTime), planePosition.x, planePosition.y);
batch.end();
batch.setProjectionMatrix(uiCamera.combined);
batch.begin();
if(gameState == GameState.Start) {
batch.draw(ready, Gdx.graphics.getWidth() / 2 - ready.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - ready.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver) {
batch.draw(gameOver, Gdx.graphics.getWidth() / 2 - gameOver.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - gameOver.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver || gameState == GameState.Running) {
font.draw(batch, "" + score, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() - 60);
}
if(gameState == GameState.Running || gameState == GameState.Pause) {
//font.draw(batch, "" + (10 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
if(wantToSeeTime){
font.draw(batch, "" + (5 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
if((5 -(elapsedTime) > 0)) {
batch.draw(planeSmallBlack, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
}else {
batch.draw(planeSmall, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
wantToSeeTime = false;
}
}
if(gameState == GameState.Pause){
batch.draw(pause, Gdx.graphics.getWidth() / 2 - pause.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - pause.getRegionHeight() / 2);
if(wantToSeeTimePause){
font.draw(batch, "" + (savedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
}
batch.end();
}
//object to hold all pertinent information for a rock
static class Rock {
Vector2 position = new Vector2();
TextureRegion image;
boolean counted;
public Rock(float x, float y, TextureRegion image) {
this.position.x = x;
this.position.y = y;
this.image = image;
}
}
// Neeeeeeeewwwww
static enum GameState {
Start, Running, GameOver, Pause
}
private class MyGestureListener implements GestureDetector.GestureListener {
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
if(gameState == GameState.Start) {
gameState = GameState.Running;
startTime = System.currentTimeMillis();
}
if(gameState == GameState.Running) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == GameState.GameOver) {
gameState = GameState.Start;
resetWorld();
}
/*if((gameState == GameState.Pause) && (count == 2)) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean longPress(float x, float y) {
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
if(gameState == GameState.Running) {
planePosition.set(planePosition.x, planePosition.y);
planeVelocity.set(0,0);
gravity.set(0, 0);
savedTime = System.currentTimeMillis() / 1000;
wantToSeeTime = false;
wantToSeeTimePause = true;
gameState = GameState.Pause;
} else {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
wantToSeeTime = true;
wantToSeeTimePause = false;
elapsedTime -= savedTime;
gameState = GameState.Running;
}
/*if(gameState == GameState.Pause) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
return false;
}
public void pinchStop() {
}
}
}
Thanks for your help!
You can use joda time for advanced operations
Please check the link for your reference
http://www.joda.org/joda-time/userguide.html
I'm going to assume that your game runs as part of a loop. Ideally what you should have is a starting time when the ability is activated, which counts down during the cooldown based on how much time has elapsed since the last iteration of your loop. For example, for an ability with a 10 second cooldown:
final long abilityLength = 10 * 1000;
long cooldownRemaining = 0;
long lastTimestamp;
boolean isPaused = false;
private void doAbility() {
if (cooldownRemaining <= 0) {
cooldownRemaining = abilityLength;
}
}
public void main(int[] args) {
lastTimestamp = System.currentTimeMillis();
while(true) { // your main game loop
// Time (in ms) elapsed since the last iteration of this loop
long delta = System.currentTimeMillis() - lastTimestamp;
... // Other game code
if (cooldownRemaining > 0 && !isPaused) {
// Subtract the delta from the remaing cooldown time.
cooldownRemaining -= delta;
}
lastTimeStamp = System.currentTimeMillis();
}
}

JFrame won't call paint method?

So I made Pong in a applet for a project in school but I realized that I can't hand in the project without creating an HTML file, so I'm attempting to change all my code from a applet to a JFrame. It all works, but my paint method isn't being called, any help will be great. Thanks for the help but to be honest im new to programming so if someone could make the changes to my code and then explain what you did, that would be great
package pong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Main extends JPanel implements Runnable, KeyListener{//whatever class holds you main method
private static final long serialVersionUID = 1L;
int width = 600;
int height = width *9/16;
int Pwidth = 10, Pheight = 50, Px = 30, Py = height / 2-Pwidth, Pv = 3;
int Ewidth = 10, Eheight = 50, Ex = width - Ewidth - 30, Ey = height / 2-Ewidth - 50;
double Ev = 2.7;
int Bwidth = 10, Bheight = 10, Bx = width / 2 + 50, By = height / 2, Bvx = 3, Bvy = 3;
int TimeD = 0;
int Ms = 0, sec = 0, min = 0;
int Pscore = 0, Escore = 0, Pwinx = 800, Pwiny = height / 2, Ewinx = 800, Ewiny = height / 2;
boolean Bleft = true, Bright = false, Bup = true, Bdown = false;
boolean Pup = false, Pdown = false;
boolean Pa = false;
String string = new String();
public static JFrame frame;//public and static so other classes can access it. Might want to use a getter and setter here
public Main(){
frame=new JFrame("Pong, A game re-made by Camron Warren");// Create new JFrame
frame.setSize(width,height);//Set the size of the window
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
frame.setLocationRelativeTo(null);//Centers window
frame.setVisible(true);//Make the window visible
Thread th = new Thread(this);
addKeyListener(this);
th.start();
}
public static void main(String[] args){
new Main();//instantiate the Main class, this has to happen
}
#Override
public void run() {
while(true){
if(Pscore >= 5){
Pwinx = 100;
Py = height / 2 - Pheight / 2;
Bx = width / 2 - Bwidth;
By = height /2 - Bheight /2;
}
if(Escore >= 5){
Ewinx = 400;
Py = height / 2-Pwidth;
Bx = width / 2 - Bwidth;
By = height /2;
}
if(Escore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Ewinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
if(Pscore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Pwinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
//ball movement class
ballMovement();
//TIME COUNTER
Ms++;
if(Ms >= 60){
sec++;
Ms = 0;
}
if(sec >= 60){
min++;
sec = 0;
}
//BALLMOVEMENT
if(Bleft == true){
Bx-=Bvx;
}
if(Bright == true){
Bx+=Bvx;
}
if(Bup == true){
By-=Bvy;
}
if(Bdown == true){
By+=Bvy;
}
//BALLHITBOX
if(By <= 0){
Bup = false;
Bdown = true;
}
if(By + Bheight >= height){
Bdown = false;
Bup = true;
}
//SCORE SYSTEM
if(Bx <= 0){
Escore++;
Bx = width / 2 - Bwidth;
By = height / 2;
}
if(Bx+Bwidth >= width){
Pscore++;
Bx = width /2 - Bwidth;
By = height / 2;
}
//PHITBOX
if(Bx+Bwidth >= Px && Bx <= Px+Pwidth && By+Bheight >= Py && By <= Py+Pheight){
System.out.println("Phit");
Bleft = false;
Bright = true;
}
//EHITBOX
if(Bx+Bwidth >= Ex && Bx <= Ex + Ewidth && By+Bheight >= Ey && By <= Ey + Eheight){
System.out.println("Ehit");
Bright = false;
Bleft = true;
}
//PMOVEMENT
if(Pup == true){
Py-=Pv;
}
if(Pdown == true){
Py+=Pv;
}
//PHITBOX/APPLETHITBOX
if(Py <= 0){
Py = 0;
}
if(Py + Pheight >= height){
Py = height - Pheight;
}
//EHITBOX/APPLETHITBOX
if(Ey <= 0){
Ey = 0;
}
if(Ey + Eheight >= height){
Ey = height - Eheight;
}
//REPAINT
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public void ballMovement()
{
if(By >= Ey)
{
Ey += Ev;
}
if(By <= Ey)
{
Ey -= Ev;
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = true;
}
if(key == KeyEvent.VK_S){
Pdown = true;
}
if(key == KeyEvent.VK_UP){
Pup = true;
}
if(key == KeyEvent.VK_DOWN){
Pdown = true;
}
if(key == KeyEvent.VK_F1){
Pa = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = false;
}
if(key == KeyEvent.VK_S){
Pdown = false;
}
if(key == KeyEvent.VK_UP){
Pup = false;
}
if(key == KeyEvent.VK_DOWN){
Pdown = false;
}
if(key == KeyEvent.VK_F1){
Pa = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {}
#SuppressWarnings("deprecation")
public void update(Graphics g) {
Graphics offgc;
Image offscreen = null;
Dimension d = size();
offscreen = createImage(d.width, d.height);
offgc = offscreen.getGraphics();
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
paint(offgc);
g.drawImage(offscreen, 0, 0, this);
}
#Override
public void paint(Graphics g){
g.setColor(Color.green);
g.fillRect(Px, Py, Pwidth, Pheight);
g.setColor(Color.RED);
g.fillRect(Ex, Ey, Ewidth, Eheight);
g.setColor(Color.BLACK);
g.fillOval(Bx, By, Bwidth, Bheight);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
g.drawString("Score: " + Pscore, 20, 20);
g.drawString("Score " + Escore , width - 60, 20);
g.drawString("Time played: " + min + ": " + sec, width / 2 - 50, 20);
g.setColor(Color.BLACK);
g.fillRect(width / 2, height, 1, height);
g.setColor(Color.BLACK);
g.drawLine(width / 2, 0, width / 2, height);
g.setColor(Color.BLACK);
g.drawString("Pong: a game re-made by Camron Warren", 10, height - 10);
g.drawString("Congrat's, you win!", Pwinx, Pwiny);
g.drawString("Press F1 to play again!", Pwinx, Pwiny + 10);
g.drawString("Enemy win's", Ewinx, Ewiny);
g.drawString("Press F1 to play again!", Ewinx, Ewiny + 10);
}
}

How to insert a button using Java Based Program in Eclipse

I just want to ask how to create a button using java based program. I want to have a button on my official game like Next button that if the user clicked it, it will allow them to go to the next level of the game. It's like a pause/resume/stop/restart button inside the game.
This is the code of the Game I used. I can't see the declaration of button here but when I played this, it has a exit button(?) above that allows the user to go back to previous form.
public class NewGame extends Activity {
static MediaPlayer mp1;
MediaPlayer jump;
MediaPlayer takecoin;
GameLoopThread gameLoopThread;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for no title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GameView(this));
}
public class GameView extends SurfaceView {
Bitmap bmp;
Bitmap background, taya, note1;
Bitmap run1;
Bitmap run6;
Bitmap jump2;
Bitmap coin;
Bitmap exit;
// MediaPlayer mp1,jump,takecoin;
private SurfaceHolder holder;
// private gameloop gameLoopThread;
private int x = 0, y = 0, z = 0, delay = 0, getx, gety, sound = 1;
int show = 0, sx, sy = 0;
int cspeed = 0, kspeed = 0, gameover = 0;
int score = 0, health = 120, reset = 0;
private int min = 1, sec = 0;
private Handler mHandler = new Handler();
private Runnable mRunnable;
private boolean isStop = false;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public GameView(Context context) {
super(context);
mHandler.postDelayed(mRunnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(sec <= 0){
if(min > 0){
sec = 59;
min--;
isStop = false;
}
else{
//stop timer here
Log.e("TIMER", "timer stop!");
mHandler.removeCallbacks(this);
isStop = true;
}
}
else{
sec--;
isStop = false;
}
Log.i("TIMER", "min: " + min + " sec: " + sec);
if(!isStop){
mHandler.postDelayed(this, 1000);
}
}
}, 1000);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#SuppressWarnings("deprecation")
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// for stoping the game
gameLoopThread.setRunning(false);
gameLoopThread.getThreadGroup().interrupt();
}
#SuppressLint("WrongCall")
#Override
public void surfaceCreated(SurfaceHolder holder) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
// getting the screen size
Display display = getWindowManager().getDefaultDisplay();
sx = display.getWidth();
sy = display.getHeight();
;
cspeed = x / 4;
kspeed = x / 4;
background = BitmapFactory.decodeResource(getResources(),
R.drawable.imgluneta);
run1 = BitmapFactory
.decodeResource(getResources(), R.drawable.run1);
run6 = BitmapFactory
.decodeResource(getResources(), R.drawable.run6);
jump2 = BitmapFactory.decodeResource(getResources(),
R.drawable.run11);
coin = BitmapFactory
.decodeResource(getResources(), R.drawable.coin);
exit = BitmapFactory
.decodeResource(getResources(), R.drawable.exit);
taya = BitmapFactory
.decodeResource(getResources(), R.drawable.taya);
note1 = BitmapFactory.decodeResource(getResources(),
R.drawable.note1);
exit = Bitmap.createScaledBitmap(exit, 25, 25, true);
background = Bitmap
.createScaledBitmap(background, 2 * sx, sy, true);
// health dec
note1 = Bitmap.createScaledBitmap(note1, sx, sy, true);
mp1 = MediaPlayer.create(NewGame.this, R.raw.game);
jump = MediaPlayer.create(NewGame.this, R.raw.jump);
takecoin = MediaPlayer.create(NewGame.this, R.raw.cointake);
}
// on touch method
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
show = 1;
getx = (int) event.getX();
gety = (int) event.getY();
// exit
if (getx < 25 && gety < 25) {
System.exit(0);
}
// sound off
if (getx > 25 && getx < 60) {
if (gety < 25) {
sound = 0;
mp1.stop();
}
}
// sound on
if (getx > 61 && getx < 90) {
if (gety < 25) {
sound = 1;
}
}
// restart game
if (getx > 91 && gety < 25) {
if (health <= 0) {
gameLoopThread.setPause(0);
health = 100;
score = 0;
}
}
}
return true;
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
// background moving
z = z - 10;
if (z == -sx) {
z = 0;
canvas.drawBitmap(background, z, 0, null);
} else {
canvas.drawBitmap(background, z, 0, null);
}
// running player
x += 5;
if (x == 20) {
x = 5;
}
if (show == 0) {
if (x % 2 == 0) {
int height = run1.getHeight();
canvas.drawBitmap(run1, sx / 16, (15 * sy / 18) - height / 2, null);
// kinfe hit
if (kspeed == 20) {
kspeed = sx;
health -= 25;
canvas.drawBitmap(note1, 0, 0, null);
}
} else {
int height = run6.getHeight();
canvas.drawBitmap(run6, sx / 16, (15 * sy / 18) - height / 2, null);
// kinfe hit
if (kspeed == 20) {
kspeed = sx / 2;
health -= 25;
canvas.drawBitmap(note1, 0, 0, null);
}
}
}
// for jump
if (show == 1) {
if (sound == 1) {
jump.start();
}
int height=jump2.getHeight();
canvas.drawBitmap(jump2, sx / 16, (3 * sy / 4)-height, null);
// score
if (cspeed <= (sx / 8)-height/2 && cspeed >= (sx / 16)-height/2) {
if (sound == 1) {
takecoin.start();
}
cspeed = sx / 2;
score += 10;
}
// jump-hold
delay += 1;
if (delay == 3) {
show = 0;
delay = 0;
}
}
// for coins
cspeed = cspeed - 5;
if (cspeed == -sx / 2) {
cspeed = sx / 2;
canvas.drawBitmap(coin, cspeed, 3 * sy / 4, null);
} else {
canvas.drawBitmap(coin, cspeed, 3 * sy / 4, null);
}
// kinfe
kspeed = kspeed - 20;
int height = taya.getHeight();
canvas.drawBitmap(taya, kspeed, (15 * sy / 18) - height / 2, null);
if (kspeed < 0) {
kspeed = sx;
health -= 25;
}
// score
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
paint.setTextSize(15);
paint.setTextAlign(Align.LEFT);
canvas.drawText("Score :" + score, 3 * sx / 4, 20, paint);
// exit
canvas.drawBitmap(exit, 0, 0, null);
if (sound == 1) {
mp1.start();
mp1.setLooping(true);
}
// health
Paint myPaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
canvas.drawText("Health :" + health, 0, (sy / 8) - 5, myPaint);
canvas.drawRect(0, sy / 8, health, sy / 8 + 10, myPaint);
// game over
if (health <= 0) {
gameover = 1;
mp1.stop();
canvas.drawText("GAMEOVER OVER", sx / 2, sy / 2, myPaint);
canvas.drawText("YOUR SCORE : " + score, sx / 2, sy / 4,
myPaint);
canvas.drawText("Restart", 91, 25, myPaint);
gameLoopThread.setPause(1);
}
// restart
if (reset == 1) {
gameLoopThread.setPause(0);
health = 100;
score = 0;
}
// timer
Paint mypaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
mypaint.setTextSize(50);
canvas.drawText("Timer :" + min + sec,min, sec, mypaint);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onResume() {
super.onResume();
NewGame.mp1.isPlaying();
}
#Override
public void onPause() {
super.onPause();
NewGame.mp1.pause();
}
}
You can create a button in Java code-
Button button = new Button(this);
where 'this' is context.

libGDX consult with speed

What i need to do is, when the points its "example 10" the speed of the ball raise, when the points its "example 20" the speed of the ball raises again, etc. I dont know if i do that in the Ball class or in the GameScreen class and i dont know how to do it. Thanks for your help!.
public class Ball {
//THE SPEED OF THE BALL
private static final float SPEED=1100;
//THE POINTS IS
puntuacion =0;
//AND THE METHOD WHEN THE POINTS IS INCREAMENTING
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
}
EDIT:
This is my GameScreen class.
public class GameScreen extends AbstractScreen {
private SpriteBatch batch;
private Texture texture;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont(Gdx.files.internal("pointsfont.tf.fnt"), Gdx.files.internal("pointsfont.tf.png"), false);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if (puntuacion % 10 == 0){
SPEED = 200;
}
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
}
}
I need 50 reputation to comment so instead I'll post an answer and try to make it as helpful as possible.
First of all I'm not too sure of your question, but from what I understand, you want to increase the speed of your ball when puntuacion reaches certain values (10, 20, etc).
The first thing you have to do is remove the final from your SPEED variable, since a final primitive can only be set once, thus denying you from changing it later on.
As for updating the speed, if you want to do it at specific values of punctuacion, then simply do
if(punctuacion == 10 || punctuacion == 17) { // etc
speed += x; // x being the value you want to increase the speed by
}
Alternatively, if you want to update the speed every 10 increments for example, you could do
if (punctuacion % 10 == 0){
speed += x;
}
Do note that for this second example, when punctuacion is 0, the if statement will return true, so work around that if you have to.
As for where to put this code, it really depends on your classes and you definitely didn't post enough code for me to be able to help you with that, but my best guess would be to put it right after you increment punctuacion, since I'm assuming you want the ball's speed update check to be performed immediately after punctuacion updates.
This is my GameScreen class.
public class GameScreen extends AbstractScreen {
private SpriteBatch batch;
private Texture texture;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont(Gdx.files.internal("pointsfont.tf.fnt"), Gdx.files.internal("pointsfont.tf.png"), false);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if (puntuacion % 10 == 0){
SPEED = 200;
}
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
}
}

Categories

Resources