Compare Arrays in Dice game - android

* Coded Edited with Fix * I found an open source project that has a few bugs (I have fixed a couple so far) but this one has me stumped. The issue that I am trying to solve... If I have 3 sets of pairs (isThreePair) and it is also a 4 of a Kind (example: 4ea - 3's and 2ea 4's) it always chooses the 4 of a kind (isFourOfAKind), I should be able to pick either. Can someone please tell me what is wrong with the code.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
final class Scorer {
private Scorer() {
}
public final static int calculate(int[] array, boolean ignoreExtraDice,
Context c) {
int length = array.length;
if (length == 0)
return 0;
int[] newArray = count(array);
if (length == 6) {
int straightStatus = isStraight(newArray, c, false);
if (straightStatus > 0) {
return straightStatus;
}
int threePairStatus = isThreePair(newArray, c, false);
if (threePairStatus > 0)
return threePairStatus;
int sixOfAKindStatus = isSixOfAKind(newArray, c);
if (sixOfAKindStatus > 0)
return sixOfAKindStatus;
int doubleTripletStatus = isDoubleTriplet(newArray, c);
if (doubleTripletStatus > 0)
return doubleTripletStatus;
}
int fiveOfAKindStatus = 0;
if (length == 5)
fiveOfAKindStatus = isFiveOfAKind(newArray, c, length)[0];
if (fiveOfAKindStatus > 0)
return fiveOfAKindStatus;
int fourOfAKindStatus = 0;
if (length == 4)
fourOfAKindStatus = isFourOfAKind(newArray, c, length)[0];
if (fourOfAKindStatus > 0)
return fourOfAKindStatus;
int threeOfAKindStatus = 0;
if (length == 3)
threeOfAKindStatus = isThreeOfAKind(newArray, c, length)[0];
if (threeOfAKindStatus > 0)
return threeOfAKindStatus;
int combinationScore = scoreCombinations(newArray, c, length);
if (combinationScore >= 0 && !ignoreExtraDice)
return 0;
else
return Math.abs(combinationScore);
}
private final static int[] count(int[] array) {
int numOf1 = 0;
int numOf2 = 0;
int numOf3 = 0;
int numOf4 = 0;
int numOf5 = 0;
int numOf6 = 0;
for (int j = 0; j < array.length; j++) {
switch (array[j]) {
case (1):
numOf1++;
break;
case (2):
numOf2++;
break;
case (3):
numOf3++;
break;
case (4):
numOf4++;
break;
case (5):
numOf5++;
break;
case (6):
numOf6++;
break;
}
}
int[] newArray = { numOf1, numOf2, numOf3, numOf4, numOf5, numOf6 };
return newArray;
}
public final static int isStraight(int[] array, Context c, boolean calledPublicly) {
if (array.length < 6)
return 0;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
boolean toScoreStraight = prefs.getBoolean("toScoreStraightPref", true);
if (!toScoreStraight)
return 0;
int straightScore = 0;
if (toScoreStraight)
straightScore = Integer.valueOf(prefs.getString("straightPref",
"1500"));
if (calledPublicly)
array = count(array);
boolean isStraight = (array[0] == 1 && array[1] == 1 && array[2] == 1
&& array[3] == 1 && array[4] == 1 && array[5] == 1);
if (isStraight)
return straightScore;
else
return 0;
}
public final static int isThreePair(int[] array, Context c, boolean calledPublicly) {
if (array.length < 6)
return 0;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
int threePairScore = Integer.valueOf(prefs.getString("threePairPref",
"750"));
if (calledPublicly)
array = count(array);
int count = 0;
if (array[0] >= 2)
count += array[0] / 2;
if (array[1] >= 2)
count += array[1] / 2;
if (array[2] >= 2)
count += array[2] / 2;
if (array[3] >= 2)
count += array[3] / 2;
if (array[4] >= 2)
count += array[4] / 2;
if (array[5] >= 2)
count += array[5] / 2;
if (count == 3)
return threePairScore;
else
return 0;
}
private final static int isSixOfAKind(int[] array, Context c) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
String sixKindPref = prefs.getString("sixOfAKindPref",
"4x the 3 Of A Kind Value");
int sixOfAKindMult = (sixKindPref.contains("3000")) ? 3000 : Integer
.valueOf("" + sixKindPref.charAt(0));
int score = 0;
if (array[0] == 6)
score = 10000;
if (array[1] == 6)
score = 200 * sixOfAKindMult;
if (array[2] == 6)
score = 300 * sixOfAKindMult;
if (array[3] == 6)
score = 400 * sixOfAKindMult;
if (array[4] == 6)
score = 500 * sixOfAKindMult;
if (array[5] == 6)
score = 600 * sixOfAKindMult;
if (sixOfAKindMult > 100)
return sixOfAKindMult;
if (score != 0)
return score;
else
return 0;
}
private final static int isDoubleTriplet(int[] array, Context c) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
boolean toVariateTwoTripsScore = prefs.getBoolean(
"toScoreTwoTripsPref", false);
if (!toVariateTwoTripsScore)
return 0;
int twoTripsScore = 0;
if (toVariateTwoTripsScore)
twoTripsScore = Integer.valueOf(prefs.getString(
"twoTripletScorePref", "2500"));
int count = 0;
if (array[0] == 3)
count++;
if (array[1] == 3)
count++;
if (array[2] == 3)
count++;
if (array[3] == 3)
count++;
if (array[4] == 3)
count++;
if (array[5] == 3)
count++;
if (count == 2)
return twoTripsScore;
else
return 0;
}
private final static int scoreCombinations(int[] array, Context c, int length) {
int score = 0;
int[] fiveArray = isFiveOfAKind(array, c, length);
int[] fourArray = isFourOfAKind(array, c, length);
int[] threeArray = isThreeOfAKind(array, c, length);
int[] temp = null;
if (fiveArray[0] != 0)
temp = fiveArray;
else if (fourArray[0] != 0)
temp = fourArray;
else if (threeArray[0] != 0)
temp = threeArray;
if (temp != null) {
for (int i = 1; i <= 6; i++) {
if (temp[i] == 0)
array[i - 1] = 0;
}
}
score += fiveArray[0];
score += fourArray[0];
score += threeArray[0];
int scoreOfRemainders = scoreRemainders(array);
if (scoreOfRemainders > 0)
score *= -1;
score += scoreOfRemainders;
return score;
}
private final static int[] isFiveOfAKind(int[] array, Context c, int length) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
String fiveKindPref = prefs.getString("fiveOfAKindPref",
"3x the 3 Of A Kind Value");
int fiveOfAKindMult = (fiveKindPref.contains("2000")) ? 2000 : Integer
.valueOf("" + fiveKindPref.charAt(0));
int score = 0;
if (array[0] == 5) {
score = 1000 * fiveOfAKindMult;
array[0] = 0;
}
if (array[1] == 5) {
score = 200 * fiveOfAKindMult;
array[1] = 0;
}
if (array[2] == 5) {
score = 300 * fiveOfAKindMult;
array[2] = 0;
}
if (array[3] == 5) {
score = 400 * fiveOfAKindMult;
array[3] = 0;
}
if (array[4] == 5) {
score = 500 * fiveOfAKindMult;
array[4] = 0;
}
if (array[5] == 5) {
score = 600 * fiveOfAKindMult;
array[5] = 0;
}
if (score != 0) {
if (fiveOfAKindMult > 100)
score = fiveOfAKindMult;
else if (length > 5)
score *= -1;
}
int[] returnArray = { score, array[0], array[1], array[2], array[3],
array[4], array[5] };
return returnArray;
}
private final static int[] isFourOfAKind(int[] array, Context c, int length) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
String fourKindPref = prefs.getString("fourOfAKindPref",
"2x the 3 Of A Kind Value");
int fourOfAKindMult = (fourKindPref.contains("1000")) ? 1000 : Integer
.valueOf("" + fourKindPref.charAt(0));
int score = 0;
if (array[0] == 4) {
score = 1000 * fourOfAKindMult;
array[0] = 0;
}
if (array[1] == 4) {
score = 200 * fourOfAKindMult;
array[1] = 0;
}
if (array[2] == 4) {
score = 300 * fourOfAKindMult;
array[2] = 0;
}
if (array[3] == 4) {
score = 400 * fourOfAKindMult;
array[3] = 0;
}
if (array[4] == 4) {
score = 500 * fourOfAKindMult;
array[4] = 0;
}
if (array[5] == 4) {
score = 600 * fourOfAKindMult;
array[5] = 0;
}
if (score != 0) {
if (fourOfAKindMult > 100)
score = fourOfAKindMult;
else if (length > 4)
score *= -1;
}
int[] returnArray = { score, array[0], array[1], array[2], array[3],
array[4], array[5] };
return returnArray;
}
private final static int[] isThreeOfAKind(int[] array, Context c, int length) {
int score = 0;
if (array[0] == 3) {
score += 1000;
array[0] = 0;
}
if (array[1] == 3) {
score += 200;
array[1] = 0;
}
if (array[2] == 3) {
score += 300;
array[2] = 0;
}
if (array[3] == 3) {
score += 400;
array[3] = 0;
}
if (array[4] == 3) {
score += 500;
array[4] = 0;
}
if (array[5] == 3) {
score += 600;
array[5] = 0;
}
if (score != 0 && length > 3) {
score *= -1;
}
int[] returnArray = { score, array[0], array[1], array[2], array[3],
array[4], array[5] };
return returnArray;
}
private final static int scoreRemainders(int[] array) {
boolean thereAreExtra = (array[1] != 0 || array[2] != 0
|| array[3] != 0 || array[5] != 0);
int score = 0;
if (thereAreExtra) {
score += array[0] * 100;
score += array[4] * 50;
} else {
score += array[0] * -100;
score += array[4] * -50;
}
return score;
}
}
My Issue was answered on the Code Review. The Above Code reflects the Working Code. But here is the Section that needed to be modified.
public final static int isThreePair(int[] array, Context c, boolean calledPublicly) {
if (array.length < 6)
return 0;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(c);
int threePairScore = Integer.valueOf(prefs.getString("threePairPref",
"750"));
if (calledPublicly)
array = count(array);
int count = 0;
if (array[0] >= 2)
count += array[0] / 2;
if (array[1] >= 2)
count += array[1] / 2;
if (array[2] >= 2)
count += array[2] / 2;
if (array[3] >= 2)
count += array[3] / 2;
if (array[4] >= 2)
count += array[4] / 2;
if (array[5] >= 2)
count += array[5] / 2;
if (count == 3)
return threePairScore;
else
return 0;
}

Walk through the code and think what would happen if it was four of a kind.
int fourOfAKindStatus = 0;
if (length == 4)
fourOfAKindStatus = isFourOfAKind(newArray, c, length)[0];
if (fourOfAKindStatus > 0)
return fourOfAKindStatus;
int threeOfAKindStatus = 0;
if (length == 3)
threeOfAKindStatus = isThreeOfAKind(newArray, c, length)[0];
if (threeOfAKindStatus > 0)
return threeOfAKindStatus;
If the result is four of a kind, you are returning from the method before checking for 3 of a kind. Therefore, the three of a kind check never gets performed.
You could have calculate() return a HashMap instead of an int, and instead of immediately returning the status when you find a match, you could add an entry to the map and keep checking, returning it at the end.

Related

RangeError (index): Invalid value: Not in inclusive range 0..13: 14 Flutter

Someone to help me? I'm a beginner. I'm trying to get the controller numbers from a textfield. For this I tried to convert the characters to int. Note: in the textfield the user will enter numbers up to three digits
This error appears: RangeError (index): Invalid value: Not in inclusive range 0..13: 14
validate(textController)
{
List textCode = List();
List messageInCode = List();
int validateRepeticions;
var stringText = textController;
for (var b = 0; b < stringText.length; b++)
{
textCode.insert(b, stringText[b]);
}
validateRepeticions = textCode.length;
print(validateRepeticions);
int g = 0;
int k = 0;
do
{
bool comma = true;
List tryToParseInt = List();
int d = 0;// 'd' is responsible for identifying the positional value of a digit
int a = 1;// 'a' increment values to k
int c = 0;// 'c' defines the positions used in tryToParseInt
int completeNumber;
tryToParseInt.insert(c, int.tryParse(textCode[k]));
if (tryToParseInt[c] == null)
{
validateRepeticions--;
}
else
{
d++;
c++;
do
{
tryToParseInt.insert(c, int.tryParse(textCode[k+a]));
if (tryToParseInt[c] == null)
{
completeNumber = tryToParseInt[0];
messageInCode.insert(g, completeNumber);
g++;
comma = false;
validateRepeticions -= 2;
}
else
{
d++;
a++;
c++;
tryToParseInt.insert(c, int.tryParse(textCode[k+a]));
if (tryToParseInt[c] == null)
{
completeNumber = tryToParseInt[0]*10 + tryToParseInt[1];
messageInCode.add(completeNumber);
g++;
comma = false;
validateRepeticions -= 3;
d++;
}
else
{
d++;
completeNumber = tryToParseInt[0]*100 + tryToParseInt[1]*10 + tryToParseInt[2];
messageInCode.add(completeNumber);
g++;
comma = false;
validateRepeticions -= 3;
}
}
} while (comma);
}
d++;
k += d;
} while (validateRepeticions >= 0);
}
Updated code
validate(textEditingController) {
int validateRepeticions = textEditingController.text.length;
List textString = textEditingController.text.split('');
List messageInCode = List();
int k = 0;
do {
bool comma = true;
List tryToParseInt = List();
int d = 0; // 'd' is responsible for identifying the value of a number that has already been verified
int a = 1; // 'a' increment values to k
int c = 0; // 'c' defines the positions used in tryToParseInt
int completeNumber;
tryToParseInt.insert(c, int.tryParse(textString[k]));
if (tryToParseInt[c] == null) {
validateRepeticions--;
} else {
d++; //1
c++; //1
do {
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 2;
} else {
d++; //2
a++; //2
c++; //2
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0] * 10 + tryToParseInt[1];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
d++;
} else {
d++;
completeNumber = tryToParseInt[0] * 100 + tryToParseInt[1] * 10 + tryToParseInt[2];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
}
}
} while (comma);
}
d++;
k += d;
} while (validateRepeticions > 0);
}
Now it's almost working, although an error still appears:
The method '_addFromInteger' was called on null.
Receiver: null
Tried calling: _addFromInteger(0)
validate(textEditingController) {
int validateRepeticions = textEditingController.text.length;
List textString = textEditingController.text.split('');
List messageInCode = List();
int k = 0;
messageInCode.clear();
do {
bool comma = true;
List tryToParseInt = List();
int d = 0; // 'd' is responsible for identifying the positional value of a digit
int a = 0; // 'a' increment values to k
int c = 0; // 'c' defines the positions used in tryToParseInt
int completeNumber;
if (k < textEditingController.text.length) {
tryToParseInt.insert(c, int.tryParse(textString[k]));
if (tryToParseInt[c] == null) {
validateRepeticions--;
} else {
d++; //1 these comments are examples
c++; //1
a++; //1
do {
if ((k + a) < textEditingController.text.length) {
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 2;
} else {
d++; //2
a++; //2
c++; //2
if ((k + a) < textEditingController.text.length) {
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0] * 10 + tryToParseInt[1];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
d++;
} else {
d++;
completeNumber = tryToParseInt[0] * 100 + tryToParseInt[1] * 10 + tryToParseInt[2];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
}
} else {
completeNumber = tryToParseInt[0] * 10 + tryToParseInt[1];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
d++;
}
}
} else {
completeNumber = tryToParseInt[0];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 2;
}
} while (comma);
}
} else {
validateRepeticions--;
}
d++;
k += d;
} while (validateRepeticions > 0 && k < textEditingController.text.length);
}
In your function, I'm assuming the param textController is the TextEditingController. In that case you need to check the length with textController.text.length
To create a list of characters from the string, you just need to use split() instead of creating a new list and loop through the string. For example: textController.text.split('')
Replace textCode.insert(b, stringText[b]); with textCode.add(stringText[b]);

how to check what Path was clicked in canvas android studio?

I'm doing a Canvas to draw a squares on a board in Canvas in Android Studio,
I need to know what path was clicked in my onTouchEvent
but all i can take out from there is an event.x and event.y,
because I have a pretty complicated shape it will be very hard to calculate only based on x and y what path was clicked.
Is there another way I can check the clicked path on the screen ?
Here is my canvas:
public class PianoKeysWidget extends View {
public class ChessSlice extends Path {
public ChessSlice() {
key = "C";
octave = 0;
isKeyBlack = false;
}
public String key;
public int octave;
public boolean isKeyBlack;
}
Paint WhiteKeyPaint, BlackKeyPaint, OuterRimPaint;
Boolean isTouching = false;
float touchY, touchX;
int globalKeyWidth = 20;
PianoKeysInterface mainInterface;
ChessSlice framePath;
ArrayList<ChessSlice> pianoPathsArray = new ArrayList<ChessSlice>();
int width = 340; // default numbers until the screen will change it when it gets the actuall view
int height = 1200; // default numbers until the screen will change it when it gets the actuall view
String TAG = "alignmentWidget";
/**
* construuctor
*
* #param context
*/
public PianoKeysWidget(Context context) {
super(context);
this.postInvalidate();
init();
}
/**
* constructor
*
* #param context
* #param attrs
*/
public PianoKeysWidget(Context context, AttributeSet attrs) {
super(context, attrs);
this.postInvalidate();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = getWidth();
height = getHeight();
init();
}
/**
* constructor
*
* #param context
* #param attrs
* #param defStyleAttr
*/
public PianoKeysWidget(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.postInvalidate();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
private static Bitmap getBitmap(Context context, int drawableId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return BitmapFactory.decodeResource(context.getResources(), drawableId);
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
//////////////////////////////////
//////////////On Draw//////////////
//////////////////////////////////
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap bitmap = getBitmap(getContext(), R.drawable.ic_accessibility_black_24dp);
if (pianoPathsArray.size() == 0) { // initlizes the init
init();
}
// draws the first circle
////////////////////////////////////////////
//go through the array and paints the corisponding cells
///////////////////////////////////////////
for (int i = 0; i < pianoPathsArray.size(); i++) {
canvas.drawPath(pianoPathsArray.get(i), WhiteKeyPaint);
if (pianoPathsArray.get(i).isKeyBlack) {
canvas.drawPath(pianoPathsArray.get(i), BlackKeyPaint);
}
canvas.drawPath(pianoPathsArray.get(i), OuterRimPaint);
// if (pianoPathsArray.get(i).color.equals("white")) {
// canvas.drawPath(pianoPathsArray.get(i), WhiteKeyPaint);
// } else {
// canvas.drawPath(pianoPathsArray.get(i), BlackKeyPaint);
// }
//
//
//
// //draw the queens
// if (pianoPathsArray.get(i).isOcupied) {
// canvas.drawBitmap(bitmap, pianoPathsArray.get(i).centerX - 40, pianoPathsArray.get(i).centerY - 45, BlackKeyPaint);
// }
}
//draw the frame
canvas.drawPath(framePath, OuterRimPaint);
}
private void activateErrorAnimationTimer(final ChessSlice chessSlice) {
}
private void init() {
if (pianoPathsArray.size() > 0) { // initlizes the init
return;
}
//gets teh width and height, initlized only after ondraw happend so it wouldn't be 0 0
width = getWidth();
height = getHeight();
//defining paints
///////////////////////////////////////////
WhiteKeyPaint = new Paint();
WhiteKeyPaint.setColor(getResources().getColor(R.color.lightKeyColor));
WhiteKeyPaint.setStyle(Paint.Style.FILL_AND_STROKE);
BlackKeyPaint = new Paint();
BlackKeyPaint.setColor(getResources().getColor(R.color.darkKeyColor));
BlackKeyPaint.setStyle(Paint.Style.FILL_AND_STROKE);
OuterRimPaint = new Paint();
OuterRimPaint.setStrokeWidth(10f);
OuterRimPaint.setColor(getResources().getColor(R.color.colorAccent));
OuterRimPaint.setStyle(Paint.Style.STROKE);
// applyes hardware Acceleration
///////////////////////////////////////////
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(LAYER_TYPE_SOFTWARE, BlackKeyPaint);
}
int overAllKeys = Globals.getInstance().numberOfPianoKeys;
int numberWhiteKeys = getWhiteKeysCount(overAllKeys)-1;
int numberBlackKeys = getBlackKeysCount(overAllKeys);
Log.d ("testings", "whitekeys: "+numberWhiteKeys);
Log.d ("testings", "blackKeys: "+numberBlackKeys);
// gets the main slices paths
///////////////////////////////////////////
for (int i = 0; i <= numberWhiteKeys; i++) {
pianoPathsArray.add(getSlicesPathsWhite(i, numberWhiteKeys));
}
for (int i = 0; i <= numberBlackKeys; i++) {
pianoPathsArray.add(getSlicesPathsBlack(i, numberBlackKeys, numberWhiteKeys));
}
//draw frame
framePath = new ChessSlice();
framePath.moveTo(0, 0);
framePath.lineTo(width, 0);
framePath.lineTo(width, height);
framePath.lineTo(0, height);
framePath.lineTo(0, 0);
}
private int getBlackKeysCount(int overAllKeys) {
int allKeys = overAllKeys;
int blackKeys = 0;
while (allKeys > 12) {
blackKeys = blackKeys + 5;
allKeys = allKeys - 12;
}
if (allKeys == 12) {
blackKeys = blackKeys + 5;
} else if (allKeys == 11) {
blackKeys = blackKeys + 5;
} else if (allKeys == 10) {
blackKeys = blackKeys + 4;
}else if (allKeys == 9) {
blackKeys = blackKeys + 4;
}else if (allKeys == 8) {
blackKeys = blackKeys + 3;
}else if (allKeys == 7) {
blackKeys = blackKeys + 3;
}else if (allKeys == 6) {
blackKeys = blackKeys + 2;
}else if (allKeys == 5) {
blackKeys = blackKeys + 2;
}else if (allKeys == 4) {
blackKeys = blackKeys + 2;
}else if (allKeys == 3) {
blackKeys = blackKeys + 1;
}else if (allKeys == 2) {
blackKeys = blackKeys + 1;
}else if (allKeys == 1) {
blackKeys = blackKeys + 0;
}
return blackKeys;
}
private int getWhiteKeysCount(int overAllKeys) {
int allKeys = overAllKeys;
int whiteKeys = 0;
while (allKeys > 12) {
whiteKeys = whiteKeys + 7;
allKeys = allKeys - 12;
}
if (allKeys == 12) {
whiteKeys = whiteKeys + 8;
} else if (allKeys == 11) {
whiteKeys = whiteKeys + 7;
} else if (allKeys == 10) {
whiteKeys = whiteKeys + 6;
}else if (allKeys == 9) {
whiteKeys = whiteKeys + 6;
}else if (allKeys == 8) {
whiteKeys = whiteKeys + 5;
}else if (allKeys == 7) {
whiteKeys = whiteKeys + 5;
}else if (allKeys == 6) {
whiteKeys = whiteKeys + 4;
}else if (allKeys == 5) {
whiteKeys = whiteKeys + 3;
}else if (allKeys == 4) {
whiteKeys = whiteKeys + 2;
}else if (allKeys == 3) {
whiteKeys = whiteKeys + 2;
}else if (allKeys == 2) {
whiteKeys = whiteKeys + 1;
}else if (allKeys == 1) {
whiteKeys = whiteKeys + 1;
}
return whiteKeys;
}
public ChessSlice getSlicesPathsWhite(int i, int numberWhiteKeys) {
int KeyWidth = width / numberWhiteKeys;
int rowHeight = height;
int startX = 0+(i*KeyWidth);
int startY = 0;
ChessSlice segmentPath = new ChessSlice();
segmentPath.moveTo(startX, startY);
segmentPath.lineTo(startX+KeyWidth, startY);
segmentPath.lineTo(startX+KeyWidth, startY+rowHeight);
segmentPath.lineTo(startX, startY+rowHeight);
segmentPath.lineTo(startX, startY);
segmentPath.key = getCorrectKeyForNumber(i);
segmentPath.octave = getCorrectOctavForNumber(i);
segmentPath.isKeyBlack = false;
return segmentPath;
}
public ChessSlice getSlicesPathsBlack(int i, int numberBlackeys, int numberWhiteKeys) {
int KeyWidth = width / numberWhiteKeys;
int rowHeight = height/2;
int modifierForBlackKeys = getBlackKeyModifier(i);
int startX = (KeyWidth/2)+(i*KeyWidth)+(modifierForBlackKeys*KeyWidth);
int startY = 0;
ChessSlice segmentPath = new ChessSlice();
segmentPath.moveTo(startX, startY);
segmentPath.lineTo(startX+KeyWidth, startY);
segmentPath.lineTo(startX+KeyWidth, startY+rowHeight);
segmentPath.lineTo(startX, startY+rowHeight);
segmentPath.lineTo(startX, startY);
segmentPath.key = getCorrectBlackKeyForNumber(i);
segmentPath.octave = getCorrectBlackOctavForNumber(i);
segmentPath.isKeyBlack = true;
return segmentPath;
}
private int getBlackKeyModifier(int i) {
int modifier = 0;
if (i >= 10) {
modifier = 4;
}else if (i >= 7) {
modifier = 3;
} else if (i >= 5) {
modifier = 2;
} else if (i >= 2) {
modifier = 1;
}
return modifier;
}
private String getCorrectKeyForNumber (int number) {
int functionNum = number;
String key = "C";
while (functionNum > 6) {
functionNum = functionNum - 7;
}
if (functionNum == 0) {
key = "C";
}else if (functionNum == 1) {
key = "D";
}else if (functionNum == 2) {
key = "E";
}else if (functionNum == 3) {
key = "F";
}else if (functionNum == 4) {
key = "G";
}else if (functionNum == 5) {
key = "A";
}else if (functionNum == 6) {
key = "B";
}
return key;
}
private String getCorrectBlackKeyForNumber (int number) {
int functionNum = number;
String key = "C#";
while (functionNum > 4) {
functionNum = functionNum - 5;
}
if (functionNum == 0) {
key = "C#";
}else if (functionNum == 1) {
key = "D#";
}else if (functionNum == 2) {
key = "F#";
}else if (functionNum == 3) {
key = "G#";
}else if (functionNum == 4) {
key = "A#";
}
return key;
}
private int getCorrectOctavForNumber (int number) {
int functionNum = number;
int octave = 0;
while (functionNum > 6) {
octave = octave + 1;
functionNum = functionNum - 7;
}
return octave;
}
private int getCorrectBlackOctavForNumber (int number) {
int functionNum = number;
int octave = 0;
while (functionNum > 4) {
octave = octave + 1;
functionNum = functionNum - 5;
}
return octave;
}
// private TouchModel calculateTouchKey (Float touchX, Float touchY) {
//
// int columWidth = width/COLUMS_COUNT;
// int rowHeight = height/ROWS_COUNT;
//
// int selectectColum = (int) Math.floor(touchX/columWidth)+1;
// int selectectRow = (int) Math.floor(touchY/rowHeight)+1;
//
// TouchModel touchModel = new TouchModel(selectectColum, selectectRow);
//
//
// mainInterface.widgetTouched(selectectColum, selectectRow);
//
// return touchModel;
// }
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
isTouching = true;
// Log.d ("Testings", "Touch Event: "+event);
// calculateTouchKey(touchX, touchY);
// Log.d (TAG, "touched: "+touchX+" and: "+touchY);
// Log.d (TAG, "x: "+selectedCells.touchX+" y: "+selectedCells.touchY);
break;
default:
isTouching = false;
}
invalidate();
return true;
}
public void initlizeWidgetVars (PianoKeysInterface chessBoardInterface) {
mainInterface = chessBoardInterface;
mainInterface.setChessArray(pianoPathsArray);
}
public void updateChessArray(ArrayList<ChessSlice> localChessArray) {
pianoPathsArray = localChessArray;
this.postInvalidate();
}
}
fixed it by :
for (int i = 0; i < pianoPathsArray.size(); i++) {
RectF boundrySlice=new RectF();
pianoPathsArray.get(i).computeBounds(boundrySlice, true);
if(boundrySlice.contains(touchX,touchY)){
selectedPath= pianoPathsArray.get(i);// where selectedPath is declared Globally.
}
}

Images based on Array Values

I have a dice game and I am trying to change the image of the Die that is selected after the dice are rolled to a "Dead Die" image. I have tried everything I can think of and I always end up finding the Value "0" in the Index or something else but never the correct Die.
When the dice is selected it sets it's value to a Negative Number. Example I select 6 it changes the value to -6 and changes the die to the -6 die image
How can I get it to display AND KEEP the "DEAD" image I want.
Here is the area where it gets the Images
//Get the Dice Images
public Integer getImage(int index) {
if (diceValues[index] == 0) {
return letterImages.get(index);
} else {
return diceImages.get((diceValues[index]));
}
}
I have tried changing
return letterImages.get(index);
to every possible combination of everything and when I do get it to change the image it always ends up at "0" or the the current number of dice selected or the some other number that I'm just not sure how it came up with.
Here is the entire DieManager class
package com.mygames.dice;
import java.util.HashMap;
import android.util.Log;
public class DieManager {
// Will return the Indexes of the dice when this is used
public static final int INDEX_FLAG = 1;
// Will return the values of the dice when this is used
public static final int VALUE_FLAG = 2;
// Will return the absolute values of the dice when this is used
public static final int ABS_VALUE_FLAG = 3;
// The array that holds the dice
private int[] diceValues = { 0, 0, 0, 0, 0, 0 };
private HashMap<Integer, Integer> diceImages = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> deadImages = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> letterImages = new HashMap<Integer, Integer>();
// Sets #newValue to dieValues[#index]
public void setValue(int index, int newValue) {
Log.w(getClass().getName(), "Index = " + index + " Value = " + newValue);
diceValues[index] = newValue;
}
public DieManager() {
super();
initializeMaps();
}
private void initializeMaps() {
diceImages.put(-6, R.drawable.die6_select);
diceImages.put(-5, R.drawable.die5_select);
diceImages.put(-4, R.drawable.die4_select);
diceImages.put(-3, R.drawable.die3_select);
diceImages.put(-2, R.drawable.die2_select);
diceImages.put(-1, R.drawable.die1_select);
diceImages.put(1, R.drawable.die1_roll);
diceImages.put(2, R.drawable.die2_roll);
diceImages.put(3, R.drawable.die3_roll);
diceImages.put(4, R.drawable.die4_roll);
diceImages.put(5, R.drawable.die5_roll);
diceImages.put(6, R.drawable.die6_roll);
deadImages.put(-1, R.drawable.die1_dead);
deadImages.put(-2, R.drawable.die2_dead);
deadImages.put(-3, R.drawable.die3_dead);
deadImages.put(-4, R.drawable.die4_dead);
deadImages.put(-5, R.drawable.die5_dead);
deadImages.put(-6, R.drawable.die6_dead);
letterImages.put(0, R.drawable.die_no);
letterImages.put(1, R.drawable.die_no);
letterImages.put(2, R.drawable.die_no);
letterImages.put(3, R.drawable.die_no);
letterImages.put(4, R.drawable.die_no);
letterImages.put(5, R.drawable.die_no);
}
public void rollDice() {
boolean isNewRound = (numOnTable() == 0);
for (int j = 0; j < 6; j++) {
// If its a new round then the dice value can be changed from 0.
// Else it can't
if (isNewRound || diceValues[j] != 0)
diceValues[j] = (int) ((Math.random() * 6) + 1);
}
}
// Returns the value or absolute value
public int getValue(int index, int flag) {
if (flag == ABS_VALUE_FLAG)
return Math.abs(diceValues[index]);
return diceValues[index];
}
// If a dice value is 0 then its a letter
public int numOnTable() {
int count = 6;
for (int i : diceValues) {
if (i == 0)
count--;
}
return count;
}
// Picking up makes the dice value 0
public void pickUp(int[] highlighted) {
for (int i = 0; i < highlighted.length; i++)
diceValues[highlighted[i]] = 0;
}
// A negative value means a die is highlighted
public void toggleHighlight(int index) {
diceValues[index] *= -1;
}
public void clearTable() {
diceValues[0] = 0;
diceValues[1] = 0;
diceValues[2] = 0;
diceValues[3] = 0;
diceValues[4] = 0;
diceValues[5] = 0;
}
// Return the dice that aren't 0
public int[] diceOnTable(int flag) {
if (flag == ABS_VALUE_FLAG) {
int[] array = new int[diceValues.length];
for (int i = 0; i < diceValues.length; i++)
array[i] = Math.abs(diceValues[i]);
return array;
}
return diceValues;
}
//Returns dice that are negative
public int[] getHighlighted(int flag) {
int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
int count = 0;
for (int j = 0; j < 6; j++) {
if (diceValues[j] < 0) {
if (flag == INDEX_FLAG)
dirtyArray[count++] = j;
if (flag == VALUE_FLAG)
dirtyArray[count++] = diceValues[j];
if (flag == ABS_VALUE_FLAG)
dirtyArray[count++] = Math.abs(diceValues[j]);
}
}
int[] cleanArray = new int[count];
//Returns an array of length 0
if (count == 0)
return cleanArray;
System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
return cleanArray;
}
// Finds in dieValues same #value and excludes #index
public int[] findPairs(int index, int flag) {
int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
int count = 0;
for (int j = 0; j < 6; j++) {
if (j != index
&& Math.abs(diceValues[j]) == Math.abs(diceValues[index])) {
if (flag == INDEX_FLAG)
dirtyArray[count++] = j;
if (flag == VALUE_FLAG)
dirtyArray[count++] = diceValues[j];
if (flag == ABS_VALUE_FLAG)
dirtyArray[count++] = Math.abs(diceValues[j]);
}
}
int[] cleanArray = new int[count];
if (count == 0)
return cleanArray;
System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
return cleanArray;
}
//Get the Dice Images
public Integer getImage(int index) {
if (diceValues[index] == 0) {
return letterImages.get(index);
} else {
return diceImages.get((diceValues[index]));
}
}
//Get the Number of dice remaining that are not 0
public int numDiceRemain() {
int counter = 0;
for (int j = 0; j < diceValues.length; j++) {
if (diceValues[j] > 0)
counter++;
}
return counter;
}
}
The dice value can never be zero on a roll because of the following line in your rollDice() method:
diceValues[j] = (int) ((Math.random() * 6) + 1);
And this seems logical to me. Why would the value on a die ever be zero?

Android Renderscript String Functions?

Are there any string functions in Renderscript? Like vsprintf, for example?
Specifically, I'd like to convert a float to a string. Do I have to write that from scratch?
Thanks!
Sorry, here's a better one. It'll work for integers as well but they have ".000" added on.
char stringBuffer[50];
static const int MAX_STRING_LENGTH = sizeof(stringBuffer) - 1;
void drawFloat(float value, int x, int y) {
int index = 0;
int scaledValue = (int)(value * 1000);
index = MAX_STRING_LENGTH;
stringBuffer[index] = 0;
while(scaledValue > 0 || index > MAX_STRING_LENGTH - 4) {
index--;
if(index == MAX_STRING_LENGTH - 4) {
stringBuffer[index--] = '.';
}
int digitValue = scaledValue % 10;
stringBuffer[index] = '0' + digitValue;
scaledValue /= 10;
}
if(value < 0) {
stringBuffer[index--] = '-';
}
rsgDrawText(&stringBuffer[index], x - 10, y + 5);
}
Couldn't find a simple way so...
void drawInteger(int value, int x, int y) {
char text[50] = "0";
int index = 0;
if(value != 0) {
index = 49;
text[index] = 0;
while(value > 0) {
index--;
int digitValue = value % 10;
text[index] = '0' + digitValue;
value /= 10;
}
if(value < 0) {
text[index--] = '-';
}
}
rsgDrawText(&text[index], x - 10, y + 5);
}
void drawFloat(float value, int x, int y) {
char text[50] = "0.000";
int index = 0;
if(value != 0) {
int integerPart = (int)(value * 1000);
index = 49;
text[index] = 0;
while(integerPart > 0) {
index--;
if(index == 45) {
text[index--] = '.';
}
int digitValue = integerPart % 10;
text[index] = '0' + digitValue;
integerPart /= 10;
}
if(value < 0) {
text[index--] = '-';
}
}
rsgDrawText(&text[index], x - 10, y + 5);
}

TiledLayer equivalent in Android [duplicate]

This question already has answers here:
Android Tile Bitmap
(8 answers)
Closed 8 years ago.
To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?
You can use this class as a equivalent "TiledLayer class of jme":
package net.obviam.walking;
import java.util.ArrayList;
import com.kilobolt.framework.Graphics;
import com.kilobolt.framework.Image;
import com.kilobolt.framework.implementation.AndroidImage;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Rect;
public class TiledLayer {
public static final int DIR_LEFT = 0;
public static final int DIR_RIGHT = 1;
public static final int DIR_UP = 2;
public static final int DIR_DOWN = 3;
private int cellWidth;
private int cellHeight;
private int yPosition = 0, xPosition = 0;
private int[][] grid;
private Image image;
private Bitmap tileArray[];
private int[] tileXPositions;
private int[] tileYPositions;
private ArrayList animatedTiles;
private int numberOfTiles;
private int numberOfColumns;
private int numberOfRows;
private int gridColumns;
private int gridRows, width, height;
int tileCounter;
public TiledLayer(Image image, int columns, int rows, int tileWidth,
int tileHeight, int width, int height) {
this.grid = new int[columns][rows];
this.gridColumns = columns;
this.gridRows = rows;
this.width = columns * tileWidth;
this.height = rows * tileHeight;
this.animatedTiles = new ArrayList();
this.cellWidth = tileWidth;
this.cellHeight = tileHeight;
int r = image.getHeight() / tileHeight;
int c = image.getWidth() / tileWidth;
tileArray = new Bitmap[(r * c) + 1];
setStaticTileSet(image, tileWidth, tileHeight);
}
public TiledLayer(Bitmap image, int columns, int rows, int tileWidth,
int tileHeight, int width, int height) {
this.grid = new int[columns][rows];
this.gridColumns = columns;
this.gridRows = rows;
this.width = columns * tileWidth;
this.height = rows * tileHeight;
this.animatedTiles = new ArrayList();
this.cellWidth = tileWidth;
this.cellHeight = tileHeight;
int r = image.getHeight() / tileHeight;
int c = image.getWidth() / tileWidth;
tileArray = new Bitmap[(r * c) + 1];
setStaticTileSet(image, tileWidth, tileHeight);
}
public void setStaticTileSet(Image image, int tileWidth, int tileHeight) {
tileArray[0] = Bitmap.createBitmap(tileWidth, tileHeight,
Config.ARGB_4444);
int rows = image.getHeight() / tileHeight;
int columns = image.getWidth() / tileWidth;
numberOfTiles = rows * columns;
for (int i = 0; i < rows; i++) {
yPosition = i * tileHeight;
for (int j = 0; j < columns; j++) {
xPosition = j * tileWidth;
tileCounter++;
tileArray[tileCounter] = Bitmap.createBitmap(
((AndroidImage) image).bitmap, xPosition, yPosition,
tileWidth, tileHeight);
}
}
if (gridColumns * gridRows < this.numberOfTiles) {
// clear the grid, when there are not as many tiles as in the
// previous set:
for (int i = 0; i < this.grid.length; i++) {
for (int j = 0; j < this.grid[i].length; j++) {
this.grid[i][j] = 0;
}
}
}
}
public void setStaticTileSet(Bitmap image, int tileWidth, int tileHeight) {
tileArray[0] = Bitmap.createBitmap(tileWidth, tileHeight,
Config.ARGB_4444);
int rows = image.getHeight() / tileHeight;
int columns = image.getWidth() / tileWidth;
numberOfTiles = rows * columns;
for (int i = 0; i < rows; i++) {
yPosition = i * tileHeight;
for (int j = 0; j < columns; j++) {
xPosition = j * tileWidth;
tileCounter++;
tileArray[tileCounter] = Bitmap.createBitmap(image, xPosition,
yPosition, tileWidth, tileHeight);
}
}
if (gridColumns * gridRows < this.numberOfTiles) {
// clear the grid, when there are not as many tiles as in the
// previous set:
for (int i = 0; i < this.grid.length; i++) {
for (int j = 0; j < this.grid[i].length; j++) {
this.grid[i][j] = 0;
}
}
}
}
public int createAnimatedTile(int staticTileIndex) {
if (staticTileIndex >= this.numberOfTiles) {
throw new IllegalArgumentException("invalid static tile index: "
+ staticTileIndex + " (there are only ["
+ this.numberOfTiles + "] tiles available.");
}
this.animatedTiles.add(new Integer(staticTileIndex));
return -1 * (this.animatedTiles.size() - 1);
}
public void setAnimatedTile(int animatedTileIndex, int staticTileIndex) {
if (staticTileIndex >= this.numberOfTiles) {
}
int animatedIndex = (-1 * animatedTileIndex) - 1;
this.animatedTiles.set(animatedIndex, new Integer(staticTileIndex));
}
public int getAnimatedTile(int animatedTileIndex) {
int animatedIndex = (-1 * animatedTileIndex) - 1;
Integer animatedTile = (Integer) this.animatedTiles.get(animatedIndex);
return animatedTile.intValue();
}
public void setCell(int col, int row, int tileIndex) {
if (tileIndex >= this.numberOfTiles) {
throw new IllegalArgumentException("invalid static tile index: "
+ tileIndex + " (there are only [" + this.numberOfTiles
+ "] tiles available.");
}
this.grid[col][row] = tileIndex;
}
public int getCell(int col, int row) {
return this.grid[col][row];
}
public boolean checkTileCollision(Sprite sp, int dir, int speed) {
int curRow, curCollumn;
int leftTile = 0, rightTile = 0, upTile = 0, downTile = 0;
curRow = sp.getY() / cellHeight;
curCollumn = sp.getX() / cellWidth;
leftTile = grid[curCollumn - 1][curRow];
rightTile = grid[curCollumn + 1][curRow];
upTile = grid[curCollumn][curRow - 1];
downTile = grid[curCollumn][curRow + 1];
if (dir == DIR_RIGHT
&& (sp.getX() + sp.getWidth() + speed) <= (curCollumn + 1)
* cellWidth)
return false;
else if (dir == DIR_RIGHT
&& ((sp.getX() + sp.getWidth() + speed)) > (curCollumn + 1)
* cellWidth && rightTile != 1)
return true;
else if (dir == DIR_LEFT
&& (sp.getX() - speed) >= (curCollumn) * cellWidth)
return false;
else if (dir == DIR_LEFT
&& (sp.getX() - speed) < (curCollumn) * cellWidth
&& leftTile != 1)
return true;
else if (dir == DIR_UP && (sp.getY() - speed) >= (curRow) * cellHeight)
return false;
else if (dir == DIR_UP && (sp.getY() - speed) < (curRow) * cellHeight
&& upTile != 1)
return true;
else if (dir == DIR_DOWN
&& (sp.getY() + sp.getHeight() + speed) <= (curRow + 1)
* cellHeight)
return false;
else if (dir == DIR_DOWN
&& (sp.getY() + sp.getHeight() + speed) > (curRow + 1)
* cellHeight && downTile != 1)
return true;
else
return false;
}
public void fillCells(int col, int row, int numCols, int numRows,
int tileIndex) {
if (tileIndex >= this.numberOfTiles) {
throw new IllegalArgumentException("invalid static tile index: "
+ tileIndex + " (there are only [" + this.numberOfTiles
+ "] tiles available.");
}
int endCols = col + numCols;
int endRows = row + numRows;
for (int i = col; i < endCols; i++) {
for (int j = row; j < endRows; j++) {
this.grid[i][j] = tileIndex;
}
}
}
public final int getCellWidth() {
return this.cellWidth;
}
public final int getCellHeight() {
return this.cellHeight;
}
public final int getColumns() {
return this.gridColumns;
}
public final int getRows() {
return this.gridRows;
}
public final void paint(Graphics g) {
for (int i = 0; i < this.gridRows; i++) {
for (int j = 0; j < this.gridColumns; j++) {
Bitmap bmp = tileArray[grid[j][i]];
g.drawImage(bmp, j * cellWidth, i * cellHeight);
}
}
}
public final void paint(Canvas c) {
for (int i = 0; i < this.gridRows; i++) {
for (int j = 0; j < this.gridColumns; j++) {
Bitmap bmp = tileArray[grid[j][i]];
c.drawBitmap(bmp, j * cellWidth, i * cellHeight, null);
// g.drawImage(bmp, j*cellWidth,i*cellHeight);
}
}
}
}

Categories

Resources