Display Score In A Different Way in a Game - android

I am making a game and would like To display the score in such a fashion that if my score is 0 and is increased by 10, then the score should increment through all of the numbers from 0 to 10. After reaching the new score it should stop, for at least a small pause.
If, again, the score is increased by another 10, the scoreboard should increment through every number from 10 to 20 and then stop again.
I have tried using handlers but unsuccessful in getting them a pause or stop, in any way.
The example in this video demonstrates what I am trying to accomplish. If you look at the scoreboard in the top right, you will see the score constantly incrementing. Here is the url in case the above link does not work: http://www.youtube.com/watch?v=NdZ8YupmEmA&feature=fvwrel
This is the code for my Runnable to increment the score.
final Handler mHandler=new Handler();
mRunnable=new Runnable() {
public void run() {
String s = null;
++i;
s= new Integer(i).toString();
tv.setText(s);
mHandler.postDelayed(mRunnable,1000);
}
/*protected void onStop() {
mHandler.removeCallbacks(mRunnable);
}*/
};
mHandler.postDelayed(mRunnable,1000);
What I specifically need is how to get the code to stop counting.

You can simply print all the numbers between 2 end points.
Say:
int counter = 0;
while(counter%10 != 0)
{
textView.setText(counter.toString());
counter++;
}
And then again continue with the loop, just start with 11 this time,not 0.
I'm not sure it'll work as you want, like in your Temple Run example. I would want to add a little sleep() of very small amount, but yesterday I was advised not use sleep() method in Android development.
EDIT:
Ok. This tutorial seems pretty easy to handle. You can apply the same logic to your score display mechanism using Handler(as you probably guessed).

Related

Unity without using Update

I'm developing a small game currently that involves players guessing. The player can additionally use special cards, that, for example, reveal one letter/add time he/she has for guessing and so on. Game is divided into two scenes -> one with shop, inventory, player profile etc the second one is strictly for guessing.
Currently, almost everything runs in the update in the second scene, but I really hate it. I was trying to rewrite everything into coroutines BUT the problem is that it seems impossible to use cards inside IEnumerator (or maybe I'm doing something wrong?).
For example, a simple countdown. If it's in Update I can easily influence the time with using cards(f.e. add 30 seconds). In the case of IEnumetor, I can't (Or maybe better, I don't know how to do it).
int secondsForGuess = 30;
IEnumerator Countdown () {
int counter = secondsForGuess;
while (counter > 0) {
yield return new WaitForSeconds (1);
counter--;
}
}
Any general suggestion how to do it without using Update will be greatly appreciated :D
If I understand your question right, you want to be able to increase the counter from the outside of the routine. So simply make it a field in the class so anyone can increase or decrease it:
const int secondsForGuess = 30;
private int counter;
public void AddToCounter(int seconds)
{
counter += seconds;
}
private IEnumerator Countdown ()
{
counter = secondsForGuess;
while (counter > 0) {
yield return new WaitForSeconds (1);
counter--;
}
// Do something when finsihed
}
Also just in case: Make sure to somewhere start the routine using StartCoroutine.

I can't handle this method: Thread.sleep()

I can't handle this method: Thread.sleep() in Android Studio.
I want to fill a 9x9 size TextView with a number every 0.1 seconds.
And, this is my codes.
public class MainActivity extends AppCompatActivity {
TextView[][] basicCell=new TextView[9][9];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVar();
int cnt=0;
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
basicCell[i][j].setText(j+"");
basicCell[i][j].setTextColor(Color.BLACK);
basicCell[i][j].setTextSize(20);
basicCell[i][j].setGravity(Gravity.CENTER);
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
Log.d("COUNT", ""+cnt++);
}
}
}
TextView[][] basicCell=new TextView[9][9]
All textviews are linked with basicCells.
And, The expected results screen is as follows.
In the middle of the code,
By inserting
try {Thread.sleep (100); }
catch (InterruptedException e) { e.printStackTrace();}
I tried to get the number one every 0.1 seconds ...
When you run the app, it stays on for a few seconds and the numbers come up at once.
I took a look at the log,
Log.d ("COUNT", "" + cnt ++);
In log chat, the logs are working hard,
The screen is in a state of jamming for a few seconds,
Since cnt is 80, the numbers are displayed on the screen at once.
I thought it was an emulator lag, so I ran it on my smartphone, and the result is the same.
I do not know what the problem is.
Is there a way to see the results as intended?
Please, take a look at the official guide for Processes and Threads. Your code is being executed on the main thread, but you can't just make it sleep, because it will freeze your UI. Also, onCreate is executed in order to create your activity, so you won't be able to update your UI just by sleeping the thread in onCreate, because Android will wait until onCreated is executed, then it will show your UI.
You need to create an AsyncTask. Please, read here:
https://developer.android.com/guide/components/processes-and-threads.html
setText(...), setTextColor(...), etc. don't change anything on the screen. They only change values recorded in the TextView objects to which you apply them. The framework will then ask the TextView objects to render themselves to the screen after your function has returned.
I don't know Android, so I don't know the proper names of things, but if you want things on the screen to change over time (i.e., if you want to animate your display), then you'll need to set up some kind of a timer task---a callback function that gets called periodically. Each time it gets called, it should change one thing (e.g., update one cell), and then it should return so that the cell will have a chance to render itself to the screen.

load level dynamically using andengine in android

I am developing a game using andEngine in android, I've developed animated sprites background, platforms and scores. for loading level, I've made a
.lvl
extension file in which I've defined platforms, player and obstacles at fixed positions. I want to know is there anything provided by andEngine so that I can dynamically load obstacles, platforms, coins and other objects rather than loading any file, my aim is to keep my game-world going as long as my player is alive.
I think I am clear.
Thanks!!!
I would like to point you to investigate "TimerHandler" as your dynamic time handler (Defining how often to attach another object/entity.
With a time handler in place, you can assign nearly any int/double/float value of an object/entity with MathUtils.random(min, max).
Example:
TimerHandler objectTimerHandler = new TimerHandler(1f, true, new ITimerCallback() {
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
int timerSeconds = 0;
timerSeconds++;
final Sprite object1 = new Sprite(0, 0, resourcesManager.object1_region, vbom);
if (timerSeconds == MathUtils.random(1, 4))
{
attachChild(object1);
object1.setX(MathUtils.random(0, 480));
}
});
registerUpdateHandler(objectTimerHandler);
So, the TimeHandler "objectHandler" is called every 1 seconds defined by the 1f variable.
An integer counter "timerSeconds" is setup as a base.
The Sprite object/entity is initialized.
Now the "magic": the if boolean is in place to set a sense of true randomness. So here's the math... Every second passed, add a "timerSecond". Then, IF "timerSecond" is EQUAL to a random number between 1-4, then attach the sprite "object1" and set it's X position, also on a random range 0-480.
In reality, this means for every 1 second passed, there is a 1/4 chance that this sprite will be created/attached. (this can be altered to any desired chance range by changing that random range max value. EG: MathUtils.random(1, 100) <-- this would state a 1 in 100 chance to spawn the sprite each second.)
The 2nd to last line closes the Timehandler code, and the last line registers the Timehandler to the class/scene/entity/engine (ect..).

How to get value from timer that already start before touch event?

I'm want to make a countdown timer that return value(seconds left) when a touch performed in android. Problem is I use andengine so that the touch event cannot be used inside the method(correct me if I'm wrong).
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
public boolean onSceneTouchEvent(Scene scene, TouchEvent arg1) {
int counterInt = 60;
Timer timer = new Timer();
counterText.setText(""+counterInt);
timer.wait(1000);
counterText.setText(""+(counterInt-1));
timer.wait(1000);
counterText.setText(""+(counterInt-1));
timer.wait(1000);
counterText.setText(""+(counterInt-1));
}
}
let say default number of counterInt is 60 and its decrease by seconds. When it shows 50 user touch the screen which means activate the touchevent arg1, how I can get the value of counterInt that has '50'? Thank you...
If you are looking for something like that you want the remaining seconds than its better to use CountDownTimer. Its onTick() gives you the exact time left in the timer started and also you can do any stuff when the countdown finishes inside the onFinish().
Theres a way easier solution using AndEngine's framework. I've created this simple class for you: here. Create an instance of it, and register it in your scene:
TimeCounter tc = new TimeCounter();
scene.registerUpdateHandler(tc);
It will start counting from that moment. Then, you can freely call tc.getSeconds() to find out how many seconds passed, and subtract them from any constant value to simulate a countdown.
You can also call reset to reset the seconds.

Android: Touch seriously slowing my application

I've been raking my brains on this one for a while.
when I'm running my application (opengl game) eveyrthing goes fine but when I touch the screen my application slows down quite seriously (not noticeable on powerful phones like the nexus one, but on the htc magic it gets quite annoying).
I did a trace and found out that the touch events seem to be handled in a different thread and even if it doesn't take so much processing time I think androids ability to switch between threads is not so good...
What is the best way to handle touch when speed is an issue ?
Currently I'm using :
in the GLSurfaceView
#Override
public boolean onTouchEvent(MotionEvent event) {
GameHandler.onTouchEvent(event);
return true;
}
Any ideas are welcome
I have a feeling the bug report below may be relevant. Sadly in seems its only going to be fixed in gingerbread.
Bug report
Have just seen that SO prefers details in the answers in case links vanish etc. the above refers to a google accepted bug in Adnroid 2.1 targetted for a fix in the gingerbread release.
Issue 7836: system_server consumes excessive CPU processing touch events
I can't vouch for this myself, but my research has shown that touching the screen fires so many events that it floods the events queue and therefore lags the CPU taking your resources.
Try putting: -
try {
Thread.sleep(16);
} catch (InterruptedException e) {} //ignore
before any returns that you have in the onTouch method (usually there's only the one at the end - but just making sure). I know sleep is usually a very bad thing to do, but its not in the UI thread so it should be ok. Sleep 16 should cap the FPS to 60.
Don't put heavy computation to your onTouchEvent(). The OnTouchEvent can be fired tens or hundred of times per second per finger, you should defer the heavy computation to the other part of your game (e.g. the physics engine or the graphic engine). In particular avoid drawing in your onTouchEvent.
You should preferrably use onClickEvent or other less intensive mouse event and only use onTouchEvent when you really need to track the motion of the touch.
#Jason:
This was going to be a comment, but it grew too big and it is a different [better] answer to the one I just gave.
I have changed my implementation using this method as described here
http://obviam.net/index.php/the-android-game-loop/
By employing the method described above means you should not need to sleep the OnTouch events.
Also don't forget to protect your game loop thread as mentioned here http://wonton-games.blogspot.com/2010/06/lunar-lander-resume-game-workaround.html
Also also keep in mind that Chris Pruett when writing Replica Island said he used 2 threads, one for the update() and the other for render() - both will have to be protected.
Chris does sleep his OnTouch with 16 milliseconds (60 fps) to cut back the events - so I would say its best to experiment if you still need to cut the events down - you need only touch the screen whilst stuff is happening to see if it lags and thus subsequently speeds up when let go.
For my needs currently I am using the same thread as I haven't progressed into OpenGL, I still use the canvas. But when I go OpenGL, it will be 2 threads, and each will be a complete class of its own.
Finally, I don't time my sprites by counting frames, I've wrapped them with a timer. I'll share my Class and show you how I call it. Bear in mind I am still new to Java so apologies for poor code.
package com.yourname.yourapplication;
//Used for doing something after a set time
public class TimeDo {
private int mRepeat = 0; //Stores the last wait period for the reset() later
private long mTime = 0; //The goal time of when its due
private boolean mFlagged = false; //Stop them getting a second true on a subsequent check
public TimeDo(int milliseconds) {
reset(milliseconds);
}
public TimeDo() {
this(0);
}
public void reset(int milliseconds) {
mRepeat = milliseconds;
mTime = System.currentTimeMillis() + milliseconds;
mFlagged = mRepeat==0; //ignore if zero
}
public void reset() { //Set it back to the delay used last time
reset(mRepeat);
}
public boolean check() {
if (mFlagged) //Assert: shouldn't really happen
return false;
mFlagged = System.currentTimeMillis() > mTime;
return mFlagged;
}
public boolean checkAndReset() {
if (check()) {
reset();
return true;
}
return false; //note mFlagged could be true here, so don't use it
}
}
And it is implemented thusly: -
public class Gem {
private TimeDo mMoveGem = new TimeDo(100); //move 10 times a second, 100ms
private int mX = 0;
private int mY = 0;
private int mMoveX = 3;
private int mMoveY = 4;
.
.
.
public void update() {
if (mMoveGem.checkAndReset()) {
mX += mMoveX;
mY += mMoveY;
.
.
}
}
public void render(Canvas canvas) {
//etc etc
.
.
}
}
Hope any of that helps!
Sorry if you have to rewrite lots of your application - I did.
Edit: That TimeDo class is not a postDelayed runnable, like an automatic alarm. If you don't check it no "event" will fire. You could get excited and have it create a runnable and pass it a callback method that resides within your class (think of an OnClick method) - but defeats the purpose of running an exclusive time-able update() thread that updates all your components.

Categories

Resources