I am trying to set an image based on the enum. I did try to do some research on how to do that using this post : How to match int to enum
but wasn't really sure how to actually use it according to my code.
Here's the enum:
public enum ImageValue{
Image1(1,R.drawable.clubs1),
Image2(2,R.drawable.hearts),
Image3(3,R.drawable.diamonds),
Image4(4,R.drawable.spades);
private int imagevalue;
private int image;
private ImageValue(int value, int drawable){
this.imagevalue = value;
this.image = drawable;
}
public int getImageValue(){
return image;
}
}
This is where I am getting the image values and other values:
public void NewDeck() {
deck = new ArrayList<Card>();
for (int i = 0; i < 13; i++) {
value = CardValue.values()[i];
for (int j = 0; j < 4; j++) {
card = new Card(value, Suit.values()[j], ImageValue.values()[j] );
this.deck.add(card);
}
}
Collections.shuffle(deck);
Iterator<Card> cardIterator = deck.iterator();
System.out.println(deck.size());
while (cardIterator.hasNext()) {
aCard = cardIterator.next();
}
System.out.println("One Card Value" + "--" + aCard.getCardValue()
+ " of " + aCard.getSuit()+"--"+"Image Value" +"----" + aCard.getImagevalue());
}
Here's one solution from the post I mentioned:
**coinView.setImageResource(coinArray[x].getImage());**
Now, On click of a button I want to set that random image that's being generated to one of my image views.
Here:
public void onClick(View v) {
randomImage.setImageResource(**Want to put the image here!**);
}
I am a bit new to Enum concept and not sure how exactly to use it.
A little help will be really appreciated..Thank's in advance.
Related
Im currently working on a little mobile game in which you throw spears at targets, and depending on how many spears you have left at the end of the level you get between one and three Runes (similar to the Star scoring sytem in Angry Birds). The plan is to save the runes and use them to unlock different spear variants in the Main Menu.
At the moment you can see how many runes you got after completeing the level, but the values are not yet being saved.
My question is, how would I go about saving the Runes after each Level? Any ideas? You can see the part of the script Im using for that below. Thanks in advance.
public int totalRunes = 0;
public GameObject rune1;
public GameObject rune2;
public GameObject rune3;
public void RuneCollection()
{
if (currentSpears >= 2)
{
Debug.Log("3 runes collected!");
rune3.SetActive(true);
totalRunes = 3;
}
else if (currentSpears >= 1)
{
Debug.Log("2 runes collected!");
rune2.SetActive(true);
totalRunes = 2;
}
else
{
Debug.Log("1 rune collected!");
rune1.SetActive(true);
totalRunes = 1;
}
}
I would use Unitys PlayerPrefs System.
Example:
Setting Score:
public Text score;
int currentscore = 0;
Increasing Score:
currentscore += 1;
score.text = currentscore.ToString();
Setting HighScore and Loading Menu:
GameManager.SetHighScore(currentscore);
SceneManager.LoadScene("Menu");
Functions to Load/Change PlayerPrefs:
void Start()
{
highscore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
}
public static void SetHighScore(int score)
{
if (score > PlayerPrefs.GetInt("HighScore", 0))
{
PlayerPrefs.SetInt("HighScore", score);
}
}
Your Code adapted to PlayerPrefs:
public int currentSpears = 0;
public GameObject rune1;
public GameObject rune2;
public GameObject rune3;
void Start()
{
currentSpears = PlayerPrefs.GetInt("CurrentSpears", 0).ToString();
}
public static void IncreaseSpears()
{
int spears = PlayerPrefs.GetInt("CurrentSpears", 0);
PlayerPrefs.SetInt("CurrentSpears", spears++);
}
public void RuneCollection()
{
if (currentSpears >= 2)
{
Debug.Log("3 runes collected!");
rune3.SetActive(true);
totalRunes = 3;
}
else if (currentSpears >= 1)
{
Debug.Log("2 runes collected!");
rune2.SetActive(true);
totalRunes = 2;
}
else
{
Debug.Log("1 rune collected!");
rune1.SetActive(true);
totalRunes = 1;
}
}
You can save your data with PlayerPrefs for some single values or PersistentDataPath for some multiple values such as a class. Find out more with this link, and you can use them as below.
PlayerPrefs:
private int score = 0;
//set value
PlayerPrefs.SetInt("Score", score);
//get value
private int savedScore = PlayerPrefs.GetInt("Score");
PersistentDataPath:
private string savedName;
private int savedHealth;
private string loadedName;
private int loadedHealth;
public void Save(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat",
FileMode.Create);
PlayerClass newData = new PlayerClass();
newData.health = savedHealth;
newData.name = savedName;
bf.Serialize(file, newData);
file.Close();
}
public void Load(){
if (File.Exists(Application.persistentDataPath + "/FileName.dat")){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/FileName.dat", FileMode.Open);
ObjData newData = (ObjData)bf.Deserialize(file);
file.Close();
loadedHealth = newData.health;
loadedName = newData.name;
}
}
[Serializable]
class PlayerClass{
public string name;
public int health;
}
i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));
Im new to android dev and using andengine and ive just come across a problem when dealing with a large animation that covers more then 1 sprite sheet. Basically I have a large sprite whose animation runs across 2 sprite sheets. Im trying to find a way to load them successfully. I will show you what I am trying and hopefully some one can either show me the correct way or help me finish it my way.
i start off by creating the 2 texture packs from the xml files.
these are created fine
TexturePackTextureRegionLibrary packer1 = null,packer2 = null;
TexturePack spritesheetTexturePack1 = null,spritesheetTexturePack2 = null;
try {
spritesheetTexturePack1 = new TexturePackLoader(activity.getTextureManager(), "Animation/Jack/")
.loadFromAsset(activity.getAssets(), "Jack_walk1" + ".xml");
spritesheetTexturePack1.loadTexture();
packer1 = spritesheetTexturePack1.getTexturePackTextureRegionLibrary();
} catch (final TexturePackParseException e) {
Debug.e(e);
}
TexturePackerTextureRegion textureRegion = packer1.get(Jack_walk1.LOOP_JACK_WALK_TO_SAFE_AREA_00000_ID);
try {
spritesheetTexturePack2 = new TexturePackLoader(activity.getTextureManager(), "Animation/Jack/")
.loadFromAsset(activity.getAssets(), "Jack_walk2" + ".xml");
spritesheetTexturePack2.loadTexture();
packer2 = spritesheetTexturePack2.getTexturePackTextureRegionLibrary();
} catch (final TexturePackParseException e) {
Debug.e(e);
}
TexturePackerTextureRegion textureRegion2 = packer2.get(Jack_walk1.LOOP_JACK_WALK_TO_SAFE_AREA_00000_ID);
ArrayList<SparseArray> animList = new ArrayList<SparseArray>();
animList.add(packer1.getIDMapping());
animList.add(packer2.getIDMapping());
TiledTextureRegion text1 = TiledTextureRegion.create(textureRegion.getTexture(), (int) textureRegion.getTextureX(), (int) textureRegion.getTextureY(), animList);
I then added this function to the tiledtextureregion to take in a list of arrays that hold the frame information and step through adding them to the itexturregion array
public static TiledTextureRegion create(final ITexture pTexture, final int pTextureX, final int pTextureY, final ArrayList<SparseArray> animList) {
ITextureRegion[] textureRegions = null;
int maxFrame = 0;
for(int i = 0; i < animList.size(); i++){
maxFrame += animList.get(i).size();
}
int currentFrame = 0;
textureRegions = new ITextureRegion[maxFrame];
for(int i = 0 ; i < animList.size(); i++){
SparseArray<? extends ITexturePackTextureRegion> packer = animList.get(i);
for(int j = 0; j < packer.size(); j++) {
if (packer.valueAt(j)!= null){
final int x = (int) packer.valueAt(j).getTextureX();
final int y = (int) packer.valueAt(j).getTextureY();
final int width = packer.valueAt(j).getSourceWidth();
final int height = packer.valueAt(j).getSourceHeight();
final Boolean rotated = packer.valueAt(j).isRotated();
textureRegions[currentFrame] = new TextureRegion(pTexture, x, y, width, height, rotated);
currentFrame++;
}
}
}
return new TiledTextureRegion(pTexture, false, textureRegions);
}
but the line return new TiledTextureRegion(pTexture, false, textureRegions); is expecting 1 texture do retrieve the frames from when creating the tiled region. Any ideas where i should go from here or is there a super easy way to handle this that i have over looked. Thanks for any help
This class is designed to work with a single texture.
If you cannot merge your textures into one (which I think is the case), then you can try to write a new class implementing ITextureRegion that will contain 2 or more TiledTextureRegion objects, and which will have a method to select one of these at will.
You will just have to delegate the remaining methods of ITextureRegion to the selected object.
public class MultipleTextureRegion implements ITextureRegion {
private List<TiledTextureRegion> internal;
private int selected=0;
//...
public void add(TiledTextureRegion region) {
internal.add(region);
}
public void select(int index) {
selected=index;
}
//...
// Delegates all ITextureRegion methods ...
public int getWidth() { return internal.get(selected).getWidth(); }
// And so on...
}
Here is my class it goes in to infinite loop please check where I am going wrong ... I am trying to get id's of image view making it random and then trying to set text view with imageview's description
public class Object {
int ObectIds[];
LinearLayout HUDDisplay;
int HudDisplayText[] = {R.id.HUD_Text_Element1,
R.id.HUD_Text_Element2,
R.id.HUD_Text_Element3,
R.id.HUD_Text_Element4,
R.id.HUD_Text_Element5,
R.id.HUD_Text_Element6,
R.id.HUD_Text_Element7};
TextView[] text;
View v;
Object(Context context,View vs) {
super();
ObectIds = new int[8];
HUDDisplay=(LinearLayout)vs.findViewById(R.id.HUD_Display);
for (int i = 0; i < 8; i++) {
ObectIds[i] = (R.id.imageView1) + i;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
randomize(vs);
setTextView();
}
public void setTextView()
{
for(int i=0;i<8;++i)
{
text[i] =(TextView) HUDDisplay.findViewById(HudDisplayText[i]);
text[i].setText(v.getContentDescription());
}
}
public void randomize(View vs) {
for (int i = 0; i < 8; i++) {
while (true) {
shuffleArray(ObectIds);
v = vs.findViewById(ObectIds[i]);
Log.d("Image", "Image Id's " + v.getId());
if (!v.isClickable()) {
v.setClickable(true);
break;
}
}
}
}
static void shuffleArray(int[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i >= 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Hey man I observed your code & found error in code :
Please compare following code with your code... Constructor
for (int i = 0; i < 8; i++) {
ObectIds[i] = **HudDisplayText[i]**;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
You have a while(true) loop that you break from only if v is not clickable. What happens if v is clickable? Nothing in your code ever sets v to not clickable, and views by default are not clickable.
I notice you're using the Object class. Object is basically the root of which all classes extend. If you call super() in the constructor, it will call the super class constructor, which is Object as well... That might be the problem.
Try looking for tutorials on how to start with Java/Android, since you are also using variables names that are not recommended. E.g. in Java,:
- a Class starts with a Capital
- a variable, starts with lowercase
- a function starts with lowercase:
public class Captial
{
private int anIntegerStartsWithLowerCase;
private void functionsAreLowerCaseAsWell()
{
}
}
Also take a look at your loop... It looks like it is never ending
i am using 9 image view's i want set images to imageview randomly , when I click on refresh button, but I tried like this it's working for random allocation of images but it's repeating the same image in two (or) three imageview's at a time. where is the problem in my code..
final int[] imageViews = {
R.id.imgview11, R.id.imgview12, R.id.imgview13,
R.id.imgview21, R.id.imgview22, R.id.imgview23,
R.id.imgview31, R.id.imgview32, R.id.imgview33 };
final int[] images = {
R.drawable.i1, R.drawable.i2, R.drawable.i3,
R.drawable.i4, R.drawable.i5, R.drawable.i6,
R.drawable.i7, R.drawable.i8, R.drawable.empty };
final ImageButton shuffle = (ImageButton) findViewById(R.id.new_puzzle);
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random generator = new Random();
//int n = 9;
//n = generator.nextInt(n);
//Random random = new Random(System.currentTimeMillis());
for(int v : imageViews) {
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[generator.nextInt(images.length - 1)]);
}
}
});
i don't want repeat, one image for one imageview only..
using the post of blessenm ,i wrote a similar code that you need. check if this helps you.
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 9; i++)
{
while(true)
{
Integer next = rng.nextInt(9) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(images[next]);
break;
}
}
}
}
});
Maybe not the perfect answer, but I would just shuffle the images list and the set the resulting image to the imageview.
This will avoid having to generate random numbers that will of course create duplicate (If you throw a dice 6 times, you won't have the numbers 1,2,3,4,5,6 in random order, you will get multiple time the same number.)
Please check everything including the 'i' as I am not in front of my computer.
List<int> list = Arrays.asList(images);
// Here we just simply used the shuffle method of Collections class
// to shuffle out defined array.
Collections.shuffle(list);
int i=0;
// Run the code again and again, then you'll see how simple we do shuffling
for (int picture: list) {
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(picture);
i++;
}
as an alternative, you may also want to shuffle your list with this code:
public class ShuffleArray {
public static void shuffleArray(int[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(int[] a, int i, int change) {
int helper = a[i];
a[i] = a[change];
a[change] = helper;
}
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7 };
shuffleArray(a);
for (int i : a) {
System.out.println(i);
}
}
}
You might want to refer to this post. It shows a method to generate random numbers without duplicates
Creating random numbers with no duplicates