I am making a tic tac toe game, i just created a array buttons. now i want to set a button with O and X then put in into a array but i don't know how to do that. I am new to android studio.
public class MainActivity extends AppCompatActivity {
int turn;
int[]myButton={R.id.button1,R.id.button2,R.id.button3,R.id.button4,
R.id.button5,R.id.button6,R.id.button7,R.id.button8,R.id.button9,};
int[]j= new int[10];
Button button[]=new Button[myButton.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
turn = 1;
for (int i = 0; i < myButton.length; i++) {
final Button button = (Button) findViewById(myButton[i]);
String Btn = String.valueOf(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (button.getText().toString().equals("")) {
if (turn == 1) {
turn = 2;
button.setText("X");
}
else if (turn == 2) {
turn = 1;
button.setText("O");
}
}
endGame();
}
});
}
}
public void endGame() {
}
}
Now the thing is you have nine buttons but you dont know how to assign X or O for the players. I would suggest a solution like this. You have two players (A,B) and if A starts first, for the entire game he's going to go with label 'X' for his turns. For the other it's 'O'. You will have to mark your 9 buttons according to which player clicked it. Ex:- If 'A' clicked 'button5' then the button label should be turned to 'X'. likewise until all the buttons get clicked or someone wins the game continues. I only gave you the guidance. Come up with this implementation and let's resolve any new problems you have.
Related
I am programming a darts counter app and at the moment I am trying to get an user input (which field on the dart board they hit) by pressing on a specific button.
Each button press will return an int which will be used to update list values that are used by my adapter to then update the views.
The method that should happen in looks like this:
private void startRound(MatchActivityPlayerAdapter adapter) {
for (int playerIndex = 0; playerIndex < getMatchParticipants().size(); playerIndex++) {
for (int currentDart = 1; currentDart <= maximumDartsToThrow; currentDart++) {
// Here I want the activity to "wait" until the user presses a button
if (pointsButtonClicked) {
setDartValue(playerIndex, currentDart);
setDartsCombinedValues(playerIndex, currentDart);
setRemainingPointsValues(playerIndex, currentDart);
adapter.notifyDataSetChanged();
}
}
}
setCurrentRound(getCurrentRound() + 1);
}
Since I cant really stop the activity at the point mentioned above until user has made an input I'll propably have to include a while loop. But in order to do this I think I'll have to create a second thread and handle things differently. That actually overwhelmed me, even though I've been reading through this.
Can anyone please explain to me how I have to design my code in order to achieve what i want?
Edit: Actually pointsButtonClicked is a boolean.
I have over 20 buttons in the global OnClick method and whenever one of them is clicked pointsButtonClicked will be set to true.
Button button1 = findViewById(R.id.btn1);
button1.setOnClickListener(v -> {
outputInt = 1;
pointsButtonClicked = true;
});
Button button2 = findViewById(R.id.btn2);
button2.setOnClickListener(v -> {
outputInt = 2;
pointsButtonClicked = true;
});
// [...]
I think that there should be a better way to this without the while-wait loop.
First of all I suppose that you used an android.widget.Button to implement that pointsButtonClicked
Here's what I would do:
//Global in your activity
int playerIndex = 0;
int currentDart = 1;
Then
private void startRound(MatchActivityPlayerAdapter adapter)
{
pointsButtonClicked.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setDartValue(playerIndex, currentDart);
setDartsCombinedValues(playerIndex, currentDart);
setRemainingPointsValues(playerIndex, currentDart);
adapter.notifyDataSetChanged();
nextThrow();
}
});
}
And finally
//Also in your activity
private void nextThrow()
{
if (currentDart == maximumDartsToThrow)
{
currentDart = 1;
if (playerIndex == getMatchParticipants().size()-1)
{
playerIndex = 0;
setCurrentRound(getCurrentRound() + 1);
}
else
{
++playerIndex;
}
}
else
{
++currentDart;
}
}
It can be better
You can use private variables and access them with getter and setter
Explained
Using this approach you do not create a thread that waits for every single button pressed. You simply create a button that listen for every click event that it receives and then you apply the logic to cycle the players and the darts for every players.
I hope this could be helpful.
[EDIT]
In this case I would apply the same OnClickListener to every button you use.
First of all I would create an inner class that implements OnClickListener and allows you to manage outputInt variable.
//Also in Activity (it is an inner class)
public class MyOnClickListener implements View.OnClickListener
{
private int myOutputInt;
public MyOnClickListener (int outputInt)
{
this.myOutputInt = outputInt;
}
#Override
public void onClick(View v)
{
pointsButtonClicked = true;
outputInt = myOutputInt;
setDartValue(playerIndex, currentDart);
setDartsCombinedValues(playerIndex, currentDart);
setRemainingPointsValues(playerIndex, currentDart);
nextThrow();
}
}
And then you create 20 MyOnClickListener passing only the int you want to assign. For example:
button1.setOnClickListener(new MyOnClickListener(1));
button2.setOnClickListener(new MyOnClickListener(2));
button3.setOnClickListener(new MyOnClickListener(3));
etc etc...
I'm a beginner with Android development (and Java). I've a number of ImageView in a layout (2d array of images). What I'm trying to implement is, each time when I click on an ImageView, it should set an image from an array based on some logic with current image being displayed (e.g. next image in array, with each click). I have googled and managed to do this but it looks rather long.
public class GameActivity extends AppCompatActivity {
private int [] inputTiles = {R.drawable.one, R.drawable.two, ...// more images};
Random r = new Random();
int matSize = 5;
int[][] indexMat = new int[matSize][matSize];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
for (int i=0; i<matSize; i++) {
for (int j=0; j<matSize; j++) {
indexMat[i][j] = r.nextInt(10);
}
}
final ImageView tile00 = findViewById(R.id.tile00);
tile00.setImageResource(inputTiles[indexMat[0][0]]);
tile00.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
indexMat[0][0] = (indexMat[0][0]+1)%5;
tile00.setImageResource(inputTiles[indexMat[0][0]]);
}
});
final ImageView tile01 = findViewById(R.id.tile01);
tile01.setImageResource(inputTiles[indexMat[0][1]]);
tile01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
indexMat[0][1] = (indexMat[0][1]+1)%5;
tile01.setImageResource(inputTiles[indexMat[0][1]]);
}
});
...// a lot more ImageViews
}
}
Say I'm displaying 5x5 grid of images. I've the available images in an array inputTiles and a 5x5 array indexMat to store the index of current image at a location i, j. Then, for each ImageView I'm listening for click and choosing another image to display from array. This is working perfectly, but I have to write "clicklisten and action" block 25 times, in this particular example. It'd be really great if there's a way to loop this so that I can have any n x n grid.
I tried looping after a bit googling, by keeping ImageView in a 5x5 array and looping over it, but the loop variables doesn't seem to go inside the setOnClickListener() function. It says I need to make i and j as final but then it becomes constants, so doesn't work. Below code is what I tried, but it doesn't work that way.
final ImageView[][] tiles = {{findViewById(R.id.tile00), findViewById(R.id.tile01), findViewById(R.id.tile02),...},
{findViewById(R.id.tile10), ...,}};
for (int i=0; i<3;i++){
for (int j=0; j<3; j++){
tiles[i][j].setImageResource(inputTiles[indexMat[i][j]]);
tiles[i][j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
indexMat[i][j] = //doesn't work
}
});
}
}
Any ideas?
The simplest way of doing this is to have a RecyclerView with a GridLayoutManager. Here's a nice example about how you can achieve your desired functionality in a RecyclerView.
Once you are setting these images in your RecyclerView, you can easily manage the click listener in your onBindViewHolder function, based on the position you have clicked.
Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}
I'm trying to press the first button just one time. This button usually return a random card but I want it just one time. Then the button should be inactive. How can I do that?
That's my code:
public class GameActivity extends Activity {
Boolean buttonPressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final Button background = (Button) findViewById(R.id.A);
Resources res = getResources();
final TypedArray Deck = res.obtainTypedArray(R.array.Deck);
final Random random = new Random();
if (!buttonPressed){
buttonPressed = true;
background.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Genrate a random index in the range
int randomInt = random.nextInt(Deck.length()-1);
// Generate the drawableID from the randomInt
int drawableID = Deck.getResourceId(randomInt, -1);
background.setBackgroundResource(drawableID);
}
});
you can disable your button with (place it inside your onClick)
background.setEnabled(false);
and you also might initialize your button to true in onCreate method
If the player has an action to do next, the simpler way is to deactivate the button when is pressed first time and after in the next action activated again.
You can do this adding
background.setEnabled(false);
in your anonymous class listener and after add
background.setEnabled(true);
in player's next action.
i make a button to start a game. whenever i click on that button from AVD, unfortunately the program has stopped and i am new to android programming. i try googling my problem and it seems there is something wrong with the code. can anyone help me? i also share a link to my code, visit https://www.dropbox.com/sh/hyitjbgda69rkd4/3Iz8WuM5-5
the main activity
public class MainActivity extends Activity
{
private Game game1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.startbutton);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// Perform action on click
game1 = new Game(this);
setContentView(game1);
}
});
}
}
Game class :
public Game(OnClickListener onClickListener)
{
super((Context) onClickListener);
caneta = new Paint();
this.caneta.setARGB(255, 0, 0, 0);
this.caneta.setAntiAlias(true);
this.caneta.setStyle(Style.STROKE);
this.caneta.setStrokeWidth(5);
l = this.getWidth();
a = this.getHeight();
singlesquare = new Cell[x][y];
int xss = l / x;
int yss = a / y;
for (int z = 0; z < y; z++)
{
for (int i = 0; i < x; i++)
{
singlesquare[z][i] = new Empty(xss * i, z * yss);
}
}
}
You really shouldn't be calling setContentView() more than once. Is that the line that's causing the error? Further, the object type of game1 doesn't appear to be a View.