android -- wait for user input - android

I'm creating a spades app with 1 human player and 3 computer players.
The problem that I am having is, the play must happen sequentially (clockwise) and I need my program to wait on the player input. I can't use wait() and notify(). I have tried while loops to check whether the user has selected a card but those stop the program from running. I've tried recursive methods that won't return anything until the player has chosen a card. That too does not work. So what do I do? I'm stuck.
My method goes like this (leaving out the non-pertinent code)
private void game(){
while(there are more tricks to be played)
while(each player has not played){
if(human turn)
get input from player
else
computer plays
}
}

Maybe you should change a little bit your game controller. Instead of waiting for anything, have your program continuously paint the screen. If user inputs nothing, same screen is paint all the time.
Once he presses a key (or clicks a card or whatever events you have), simply modify the paint method's argument (the screen to be painted). Thus you will separate painting the screen and input handling. It's a common technique called MVC model.
Maybe this will help (it's my game creating blog, and the links inside it are also helpful):
http://m3ph1st0s.blogspot.ro/2012/12/create-games-with-libgdx-library-in.html
You don't need to adapt all your game to the game described there, only the technique of separating input from painting. As a general technique, you should NOT have input determine painting.
Hope it helps. Don't hesitate to request further help.

You can try to add Event Handlers. It will try triger a event every time the user selects a card.

Try this.
Create one thread and in that threat call sleep(1000);

Related

Can I use a variable int value inside of another variable function?

I have a pretty basic knowledge of AS3, so I'm not sure if this is actually possible, or if it is, how to do it. I am in the very starts of coding this project, so I don't actually have much code to show, but would like to figure this issue out before I start writing everything around it.
I am making a game similar to Monopoly, so I will speak in terms of that. Basically, I want 4 Players all with variable integers that reflect how much money they have. In my game, I want to be able to click on a player, click "Buy Property", and then click the property they're buying, which would be a button (btnProperty1).
Let's say Property 1 also has a purchase value, which could be "valueProperty1", and let's say the value is 100. My players will start with 1000, so I want the buying of this property to deduct 100 from the active player money. The player money int could be "moneyPlayer1, moneyPlayer2, etc.". So, I would be able to click btnPlayer1, btnBuyProperty, btnProperty1, and then moneyPlayer1 would go from 1000 to 900. To determine the active player, I had the idea of making an "activePlayer" int, and just setting it to 1, 2, 3 or 4 based on which btnPlayer I click.
In a shotty way of putting it, I could put in the btnProperty1 if (activePlayer == 1){moneyPlayer1 -= valueProperty1} and write four statements, one for each player. HOWEVER, I would like to subvert doing that by writing a function that looks like this:
moneyPlayer[activePlayer] -= valueProperty1 (if the activePlayer int is equal to 1, then it would fill in 1 to the end of moneyPlayer, therefor targeting moneyPlayer1)
In theory, it would then deduct money from whichever player is active. IF THIS IS POSSIBLE, I have no idea how to write it.
Additionally, I would like to do something similar if a subsequent player lands on an owned property. So in the same vein, I would want something that looks like this:
moneyPlayer[activePlayer] -= rentProperty1 (the rent value is deducted from the active player)
moneyPlayer[paidPlayer] += rentProperty1 (the rent value is added to the paid player)
I can figure out ways to make the active player and paid player functions work, I just need to know if I can put these variables INSIDE of other variables, so I don't have to write 18,748 if statements.
Lastly, I would love to be able to enter a player name into an input text field, then have it appear in a dynamic text field. I tried looking around and couldn't find an answer... So bonus points for this one :)
Any help would be GREATLY appreciated!! Thank you!
To answer your question, YES you can put variables "inside" another variable, this is called "classes" in AS3, and is a required thing to use whenever you plan something big. Say you want a Player class, then you can do like this:
public class Player {
private var _money:int;
... // whatever else a player has
public function get money:int { return _money;} // a property
// such functions are the way to make someone not directly steal the player's money,
// but are a way to view the money of a player
// rest of property functions goes here
public function Player() // a constructor, required
{
_money=1000; // starting money
... //etc, place default values everywhere
}
public function earnMoney(amount:int) // makes the player able to earn money
{
_money += amount; // negative money may be accepted, learn to check parameters!
}
// everything else goes here
}
Then you add there more functions that can change a player's state, say a function buy(aProperty):Boolean that would return true if the player did buy that property, and will also change the variables "inside" both the property involved and the player (this, or just call variables as if they are local).
You can do way more with classes, please read about object-oriented programming, there's a lot of basics that can help you draw your game's architecture. Learn about "encapsulation" first, to not accidentally break your objects. An example was shown above.

What is the purpose of the command APP_CMD_SAVE_STATE ?

Everytime the application loses focus (whether manually by hitting the menu button, or by going to idle ) an APP_CMD_SAVE_STATE command is sent.
In the example shown from the Android API documentation for native activity (https://developer.android.com/reference/android/app/NativeActivity.html) , when this particular command is sent they are saving some sort of "state" inside their android_app .
// (...)
switch (cmd) {
case APP_CMD_SAVE_STATE:
// The system has asked us to save our current state. Do so.
engine->app->savedState = malloc(sizeof(struct saved_state));
*((struct saved_state*)engine->app->savedState) = engine->state;
engine->app->savedStateSize = sizeof(struct saved_state);
break;
// (...)
If you look in their code, savedState is just a struct holding values. First I thought that we need to save every single value that matters for our app everytime we lose focus, because otherwise the values would all become corrupt or something like that (yeah scary!)
I run a simple test by removing the code snippet above, and fortunately nothing changed, the values of my struct stayed the same after regaining focus even without saving them.
So I was wondering what is the purpose of this command ? Is that something important to consider ?
The APP_CMD_SAVE_STATE command is sent when your app loses focus. The aim is to make it possible to not only suspend your app, but, if the system has to kill the app to get some resources (e.g. free RAM), the app can be restored seamlessly next time the user returns to it.
If you look in their code, savedState is just a struct holding values.
Yes, from the point of view of the Native Activity, it's just a struct. But this struct is passed to Android in ANativeActivity_onCreate() function that's called via JNI (and usually it's implemented in android_native_app_glue.c from the SDK, which you could alter or replace if you need). Thus, Android will take care of the data when managing apps.
I run a simple test by removing the code snippet above, and fortunately nothing changed, the values of my struct stayed the same after regaining focus even without saving them.
Your test was too soft :) Try opening the Recents screen and close your activity from there: tap the × button or Close All command. The effect will be to kill the app, and you should now find that your data have been wiped unless you use the save-restore mechanism.

What's the BEST WAY to check (and do something) for a touch event in libgdx?

I have a newbie question. I just started learning about libgdx and I'm a bit confused. I read the documentation/wiki, I followed some tutorials like the one from gamefromscratch and others and I still have a question.
What's the best way to check and do something for a touch/tap event?
I'm using Scenes and Actors and I found at least 4 ways (till now) of interacting with an Actor, let's say:
1) myActor.addListener(new ClickListener(){...});
2) myActor.setTouchable(Touchable.enabled); and putting the code in the act() method
3) verifying Gdx.input.isTouched() in the render() method
4) overriding touchDown, touchUp methods
Any help with some details and suggestions when to use one over the other, or what's the difference between them would be very appreciated.
Thanks.
I've always been using the first method and I think from an OOP viewpoint, it's the "best" way to do it.
The second approach will not work. Whether you set an Actor to be touchable or not, Actor.act(float) will still be called whenever you do stage.act(float). That means you would execute your code in every frame.
Gdx.input.isTouched() will only tell you that a touch event has happened anywhere on the screen. It would not be a good idea to try to find out which actor has been hit by that touch, as they are already able to determine that themselves (Actor.hit()).
I'm not sure where you'd override touchDown and touchUp. Actors don't have these methods, so I'm assuming you are talking about a standard InputProcessor. In this case you will have the same problem like with your 3rd approach.
So adding a ClickListener to the actors you want to monitor for these kind of events is probably the best way to go.

AndEngine - setText on Text entity causing hiccups in first seconds

Imagine score counter made with Text() entity. Simple.
After I start a game, calling setText() causes launching a GC_EXPLICIT that slows down a game causing freezes, and after a few calls - problem disappears. Firstly I thought it's a problem with Strings and concatenation in Java, so I used a StringBuilder. The problem still exists. If I change setText("$" + score + "M") to simple setText("0") no hiccups are noticed!
The problem is in Font. Creation of Texture doesn't actually load characters to this Texture! All you need to do is after creating Font simply call:
pFont.prepareLetters("0123456789".toCharArray());
with all chars you need.
Occasional hiccups that were caused by GC_EXPLICIT were happening because Font in update() was explicitly calling System.gc(). Removing this line we were back on track below the green line, yeah! 60fps.
However, the author of AndEngine might had reasons for this explicit call. Since the stages are short we granted our app call this gc() when the GameScene is paused, quit or stage complete, anywhere where there is no excessive animation.
Preparing characters upfront did not sooth the hiccups, because the texts were dynamic and we could not prepare all possible characters to keep the System.gc() in this method, but honor it later.
Indeed preparing the letters upfront does not trigger GC_EXPLICIT, as it is described in the answer provided by the OP.
EDIT:
After some research, another thing that caused < 60fps, was the SoundPool, we should have playing a sound with volume 0f,0f and looping, in order to prevent the SoundPool reset to idle state and rearm again.

How to perform Redo Undo operation in EditText

I want to know is there any method or any link or tutorial to perform redo undo operation in Android edittext. If any one knows than please let me know.
Quick note on the Antti-Brax/Divers(Kidinov) solution. It works great, except if you try to use it with a TextView post-API 23, you'll run into problems, because guess-what, Google actually added a hidden UndoManager (android.content.UndoManager) and didn't document it or make it obvious it was there. But if you have a hard/bluetooth keyboard in Marshmallow or Nougat and hit ^Z or SHIFT-^Z, you'll get undo/redo.
The problem comes if you're already using Antti-Brax's class with an EditText, and you also hook it to ^Z and shift-^Z, you'll run into problems with anyone using a hard keyboard. Namely the ^Z will trigger BOTH the native and Antti-Brax's undo, leading to two undos simultaneously, which isn't good. And after a few of them, you'll probably get a Spannable out of bounds crash.
A possible solution I found is to subclass the TextView/TextEdit/whatever and intercept the undo/redo calls from the TextView so they don't run as follows:
#Override
public boolean onTextContextMenuItem(int id) {
int ID_UNDO, ID_REDO;
try {
ID_UNDO = android.R.id.undo;
ID_REDO = android.R.id.redo;
} catch (Resources.NotFoundException e) {
ID_UNDO = 16908338; // 0x1020032
ID_REDO = 16908339; // 0x1020033
}
return !((id == ID_UNDO) || (id == ID_REDO)) && super.onTextContextMenuItem(id);
}
Those magic id numbers were found here, and are used only as a backup if the android.R.id.undo values aren't found. (it also might be reasonable to assume that if the values aren't there the feature isn't there, but anyway...)
This is not the best solution because both undo trackers are still there and both are running in the background. But at least you won't trigger both of them simultaneously with ^Z. It's the best I could think to do until this gets officially documented and the getUndoManager() methods of TextView is no longer hidden...
Why they made a feature you can't turn off (or even know if it was there or not) "live" in released Android I can't say.
I just opened an issue on Android's issue tracker if anyone wants to follow this.
There is an implementation of undo/redo for Android EditText in
http://credentiality-android-scripting.googlecode.com/hg/android/ScriptingLayerForAndroid/src/com/googlecode/android_scripting/activity/ScriptEditor.java
The code works but does not handle configuration changes properly. I am working on a fix and will post here when it is complete.
My Google search was :-
android edittext onTextChanged undo
I know this is an old question, but as there is no accepted answer, and this is an issue I've tackled myself from many angles, I'd like to add my solution in case it helps anyone. My answer is probably most relevant to large (1,000words+) volumes of text editing apps that require this feature.
The simplest way to resolve this problem is to make periodic copies of all text on screen, save it to an array and call setText() every time the Undo method is called. This makes for a reliable system, but it isn't ideal for large (i.e. 1,000words+) text editing apps. This is because it:
Is wasteful. It could be that only one word changes in a two thousand word document, so that's one thousand, nine hundred and ninety nine words needlessly committed to memory.
Can lead to performance issues, as some low-tier hardware struggles with rendering large amounts of text. On some of my test devices, this method can lead to freezes of a few seconds whenever Undo is called.
The solution I currently use is comparatively complex, but I've published the results in a library here.
Essentially, this library saves a copy of text as soon as a user begins typing, and then another copy of text once they've stopped typing for a set amount of time (in my case, two seconds). The two text strings are then compared, and the altered section of text returned, the indexes where the alterations occured, and details on whether or not the change was an addition of new text, a deletion, or a replacement of old text with new text.
The net result is that only the necessary text is saved, and when Undo is called, there is only a local delete(), replace() or insert() call, which makes for much faster operations on large text fields.
Here is the undo/redo implementation that was linked to from Gary Phillips' answer extracted into a reusable and universal undo/redo plugin for any widget that descends from a TextView. I added some code for persisting the undo history.
http://code.google.com/p/android/issues/detail?id=6458#c123
Hope this helps.
To preserve EditText Styling with regards to undo:
You can create an ArrayList<EditText> or ArrayList<String> (String containing html text) to store your last 10 (for example) actions. So ArrayList [0] would contain html text from your first action and ArrayList [9] would contain html text from your very last action. Each time the user taps "undo" in your app, you would apply ArrayList [size()-1] to your EditText and then remove ArrayList [size()-1] from your Array.

Categories

Resources