Points changing rapidly - android

I like to make a game, but I get trouble with collecting points.
The purpose is to increase/decrease character point (charhop +1 or -1) whenever object 'face' is collided with injekBox, but the point just increase or decrease once then it return to the previous value.
The log also still print the value even if the object stop
I want to make the point change once if the 'face' collided with certain box, and will change again after collided with another box
char1.setHops(0);
public void onUpdate(final float pSecondsElapsed) {
if (char1.isJump()){
int rockPoint = char1.getPoints();
int maxBox = listBox.size();
int charHop = char1.getHops();
for (int j = 0; j < maxBox ; j++){
if (j == rockPoint){
j++;
}
Box injekBox = listBox.get(j);
if(injekBox.getRectangle().collidesWith(face)){
if(char1.isTurn()){
charHop++;
if (charHop == (maxBox - 1)){
char1.setTurn(false);
}
} else {
charHop--;
}
Log.i(this.toString(),"charHop: "+charHop);
injekBox.getRectangle().setColor(1, 0, 0);
} else {
injekBox.getRectangle().setColor(1, 1, 1);
}
}
}
}
Sorry for bad writing...
Thank you for attention :)

The scope of charHop is only within onUpdate. Once you leave that method, the contents of that variable is gone. You need the counterpart to char1.getHops()--something like char1.setHops(charHop);.

Related

Android Studio - App crash when using intent parameter

I have a function that 'crafts' products using two String parameters.
This is working fine when I put in hard coded strings like 'Wheel' & 'Car'.
But it makes my application crash if I try to put in the exact same strings but then provided by an intent.
I already tried to give in variable into the intent instead of a hard coded string. That did not work either.
Here is some part of the code. EDIT: Error log now included
productLeft = getIntent().getStringExtra("PRODUCT LEFT");
productRight = getIntent().getStringExtra("PRODUCT RIGHT");
public void craft(String product1, String product2) {
String[][] Products = factory.getProductList();
int i = 0;
while (finalProduct == "") {
int j;
for(j = 0; j < 3; j++){
if (product1 == Products[i][0] || product2 == Products[i][0]) {
if (product1 == Products[i][1] || product2 == Products[i][1]){
finalProduct = Products[i][2];
}
}
i++;
}
}
}
Problem is with the array index obviously. The array has only four elements and you are fetching index 4, probably in for loop with i variable. But then again I also do not see the role of j in that loop, can't tell without other parts of code.

Number of occurrence of a face between an interval of [40 cm; 80cm]

I tried to increase++ a number (i) each time the distance between the camera and my face is between 40 cm and 80 cm. Unfortunately when it happen the textview shows (The number of occurrence is: 50). Help me please
public void update(final Messsage msg) {
for(int i = 0; i < 50; ++i) {
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
}
}
}
you should probably add a break after you set the text, the way you coded it will set a text for all the iteration of i but you will only see the last one (50)
If you only want to increase the number when the face is a certain length away, shouldn't you do something more on the lines of this?
public void update(final Messsage msg) {
int i = 0;
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
i++;
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
}
}
Maybe you'll need to have that i a global variable or an argument to the function, not sure without having more of the code.
If you don't want the i to increase really fast (because it increments each time the update function is called and the phone is close to the face), a simple code to do that would be something like
public void update(final Messsage msg) {
boolean isCloseToFace = false;
int i = 0;
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
if (!isCloseToFace) {
i++;
isCloseToFace = true;
}
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
} else {
isCloseToFace = false;
}
}

Using an arraylist for multiple if conditions

I changed my mind about using swipemotions: As it is rather complicated to use swipemotions, I decided to just use simple buttons with 'bigger' and 'smaller'
I'm currently working on a school project in Android Studio and so far I've written a code which generates a random equation.
Here is the code which gereates the random equation:
String[] operationSet = new String[]{"+", "-", "/", "*"};
String stringResultOfEquation;
String equation;
double doubleAnswer1;
public void start1() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation);
String stringResultOfEquation = String.valueOf(equation);
double doubleAnswer1 = eval(stringResultOfEquation);
String stringAnswer = Double.toString(doubleAnswer1);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
}
Now the app displays two equations on the screen and the user then has to dicide wether the second equation has a bigger or smaller result than the first one. If the second equation is bigger, the user has to do a swipemotion UP and if the second equation is smaller, the user has to do a swipemotion DOWN.
However I don't know how to write the code for this. I tried this:
if((doubleAnswer1 > doubleAnswer2) && (MotionEvent.ACTION_DOWN = true)){
//create new equation
}
but that didn't work. It told me that "Operator && can't be applied to boolean, int"
Now I'm curious if I could use an arraylist like this:
if(doubleAnswer1 > doubleAnswer2){
// put "smaller" to arraylist
} else {
// put "bigger" to arraylist
}
if(MotionEvent.ACTION_DOWN = true){
// put "smaller" to arraylist
}
if(MotionEvent.ACTION_UP = true){
// put "bigger" to arraylist
}
Then the code would check the arraylist if the elemnts of the arraylist are the same. If so, the next equation will be generated. If the elemnts of the arraylist are different, the process will be stopped.
I really don't know if that would work, so could someone maybe tell me if?
Or is there an other way to solve my problem?
If anything is unclear in my question, feel free to ask and I will try to clarify the problem :)
Thank you already in advance for your help!
When you write such statement editor will tell you (Android studio hope so) that you can't compare int with boolean. as it is tendency that zero means false and 1 means true but in java you can't do like that.
you can try like this
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
return false;
}
return false;
}
Hope will help in understanding...
"=" is an assignment,
for comparing a value use "==".
regarding recognizing gesture, check out https://developer.android.com/training/gestures/detector.html#detect and https://developer.android.com/reference/android/view/GestureDetector.html
You need something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
...
mDetector = new GestureDetectorCompat(this,this);
...
}
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
Log.d(TAG, "fling! - direction is " + (velocityY > 0 ? "down" : "up"));
return true;
}

Android ArrayIndexOutOfBoundsException class View

The error:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at WeekView.getMoreEvents(WeekView.java:614)
In a class that extends View, I get a list of the id in this way:
public void setElencoIdOperatori(int[] id_nome_op){
this.id_nome_op = id_nome_op;
}
Then, with this method, I must compare id_nome_op with eventRect.event.getIdOperatore(). When are the same, I want to add the event to the array eventRects. Thanks for your help
private void getMoreEvents(Calendar day){
// Get more events if the month is changed.
if(mEventRects ==null)
mEventRects =newArrayList<EventRect>();
if(mMonthChangeListener ==null&&!isInEditMode())
thrownewIllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if(mRefreshEvents){
mEventRects.clear();
mFetchedMonths =newint[3];
}
...
// Get events of this month.
if(mFetchedMonths[1]<1||mFetchedMonths[1]!= day.get(Calendar.MONTH)+1||mRefreshEvents){
if(!containsValue(lastFetchedMonth,day.get(Calendar.MONTH)+1)&&!isInEditMode()){
List<WeekViewEvent> events =mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR),day.get(Calendar.MONTH)+1);
sortEvents(events);
for(WeekViewEventevent: events){
cacheEvent(event);
}
}
mFetchedMonths[1]= day.get(Calendar.MONTH)+1;
}
...
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents =newArrayList<EventRect>(mEventRects);
mEventRects =newArrayList<EventRect>();
for(intj =1;j <=id_nome_op.length;){
ArrayList<EventRect> eventRects =newArrayList<EventRect>();
for(EventRect eventRect : tempEvents){
if(eventRect.event.getIdOperatore() == id_nome_op[j])
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
j++;
}
}
It's a bit hard understanding your code, but I think you might have a problem here:
for(int j =1;j <=id_nome_op.length;) {
ArrayList<EventRect> eventRects =newArrayList<EventRect>();
for(EventRect eventRect : tempEvents){
if(eventRect.event.getIdOperatore() == id_nome_op[j])
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
j++;
}
When you access id_nome_op[j].
Try changing the loop to:
j < id_nome_op.length
As #Mike M pointed out, you also need initalizing your outer loop to 0, as you want to get all the items in your array:
for(int j = 0; j < id_nome_op.length;)

Array Integer Logic

I have a game with progress chart and an array. I want to have a chart which the player can see its score in its last 5 games.
here's my code in my array
int[] Addition = { score1, score2, score3, score4, score5 };
if (score1 == 0) {
score1 = Game.score;
} else if (score1 != 0 && score2 == 0) {
score2 = 21;
} else if (score2 != 0 && score3 == 0) {
score3 = Game.score;
} else if (score3 != 0 && score4 == 0) {
score4 = Game.score;
} else if (score4 != 0 && score5 == 0) {
score5 = Game.score;
}
What is the problem on my logic? when it runs my first game score seems to be right. but when i play one more its just that the 1st element of the array is changing? where Am I wrong? btw please apologize my english. and I appreciate any suggestions and comments. thanks guys
:::UPDATE:::
here's my code now. Can someone check if my initialization is correct:
public class ProgressGraph extends Activity {
int[] Addition = { 0, 0, 0, 0, 0 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openChart();
}
public void openChart() {
for (int i = 0; i < 5; i++) {
if (Addition[i] == 0) {
Addition[i] = Game.score;
break;
}
}
I would do something like this:
for(int i = Addition.length-1; i > 0; i--){
Addition[i] = Addition[i-1];
}
Addition[0] = Game.score;
This will mean that the most recent game will always be in position 0. If the user plays more than 5 games the oldest score gets replaced.
It also allows the user to be able to score 0.
This part of code seems to be good.
I think your score array is reset when you start the second game.
Did you try to print the scores array before the end of the second game ? Does the first score remain stored ?
Then I suggest you to use a loop like that (not tested):
for (int i = 0; i < 5; i++) {
if (score[i] == 0) {
score[i] = Game.score;
break;
}
}
Are you trying to move each old score down the list?
for (int i = 4; i > 0; i--) {
Addition[i] = Addition[i-1];
}
Addition[0] = Game.score;
In these code samples we've provided, the array values should be initialized to zero:
int[] Addition = { 0, 0, 0, 0, 0};
Taking into account your update.
- When you declare the array. The variable has a capital letter so it may have a conflict with a class. Replace Addition by addition.
With this code, if you start another activity, scores will be reset. You have to use Application extended class or SharedPreferences to save scores.

Categories

Resources