I have a functionality for tic tac toe where basically when the player clicks a button to place their X, the computer's O is placed at the same time within the first empty button available.
However what I prefer is after the player places an X, the computer places their O on the first empty button available, not the same time. Is there a way to get the computer to click on an empty button by itself?
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
computerMove();
}
}
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j] == "") {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
UPDATE
Whole code snippet:
public class MainActivityPlayer1 extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean playerOneMove = true;
private int turnsCount;
private int playerOnePoints;
private int playerTwoPoints;
private TextView textViewPlayerOne;
private TextView textViewPlayerTwo;
private TextView textViewPlayerOneTurn;
private TextView textViewPlayerTwoTurn;
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player2);
textViewPlayerOne = findViewById(R.id.textView_player1);
textViewPlayerTwo = findViewById(R.id.textView_player2);
textViewPlayerOneTurn = findViewById(R.id.textView_player1Turn);
textViewPlayerTwoTurn = findViewById(R.id.textView_player2Turn);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID).toString();
if (btnState.equals("X")) {
buttons[i][j].setTextColor(playerX);
} else {
buttons[i][j].setTextColor(playerO);
}
}
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
Button buttonExit = findViewById(R.id.button_exit);
buttonExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backToMainActivity();
}
});
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
playerOneMove = false;
computerMove();
}
turnsCount++;
if (checkGameIsWon()) {
if (playerOneMove) {
player1Wins();
} else {
player2Wins();
}
} else if (turnsCount == 9) {
draw();
} else {
playerOneMove = !playerOneMove;
switchPlayerTurn();
}
}
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j] == "") {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
private boolean checkGameIsWon() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
playerOnePoints++;
Toast.makeText(this, "Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
playerTwoPoints++;
Toast.makeText(this, "Computer wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
}
#SuppressLint("SetTextI18n")
private void updatePointsText() {
textViewPlayerOne.setText("Player 1: " + playerOnePoints + " ");
textViewPlayerTwo.setText("Computer: " + playerTwoPoints + " ");
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
turnsCount = 0;
switchPlayerTurn();
}
private void resetGame() {
playerOnePoints = 0;
playerTwoPoints = 0;
turnsCount = 0;
playerOneMove = true;
updatePointsText();
resetBoard();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("turnsCount", turnsCount);
outState.putInt("playerOnePoints", playerOnePoints);
outState.putInt("playerTwoPoints", playerTwoPoints);
outState.putBoolean("playerOneMove", playerOneMove);
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
turnsCount = savedInstanceState.getInt("turnsCount");
playerOnePoints = savedInstanceState.getInt("playerOnePoints");
playerTwoPoints = savedInstanceState.getInt("playerTwoPoints");
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
savedInstanceState.putCharSequence(buttonID, btn.getText());
}
}
}
private void switchPlayerTurn(){
if (playerOneMove){
textViewPlayerOneTurn.setVisibility(View.VISIBLE);
textViewPlayerTwoTurn.setVisibility(View.INVISIBLE);
}
else{
textViewPlayerOneTurn.setVisibility(View.INVISIBLE);
textViewPlayerTwoTurn.setVisibility(View.VISIBLE);
}
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
}
Try this
button.performClick();
UPDATE after going through op's code:
Your code was perfectly fine but had one small bug. In your computerMove() function, you had compared strings using == which is prone to cause problems in Java. I replaced it with String.equals(String) and played a game. Works fine.
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
Related
i make some checkbox and radiobutton programically in my recyclerview and when i use notifydatasetchanged all of them are replaced with items in mylist
what should i do?
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
public MyRecyclerViewAdapter(Context context, ArrayList<HashMap<String, Object>> hash_all) {
}
#Override
public int getItemCount() {
return hash_all.size();
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
hash_all.size();
hash_get = hash_all.get(position);
Log.d("_hdev",hash_all.get(position) + " ::::::::: " + hash_get+"");
LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(
LinearLayoutCompat.LayoutParams.MATCH_PARENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 0, 0, 0);
String s = hash_get.get("ModelShowOption").toString();
String toggle = "";
String direc = "";
String type = "";
String model = "";
String rows = "";
String resize = "";
String[] split = s.split("\\|");
// = new String[0];
String[] split2 = new String[0];
for (int i = 0; i < split.length; i++) {
String s2 = split[i];
split2 = s2.split(":");
if (split2[0].equals("isToggleButton")){
toggle=split2[1];
}else if (split2[0].equals("type")){
type=split2[1];
}else if (split2[0].equals("direction")){
direc=split2[1];
}else if (split2[0].equals("model")){
model=split2[1];
}else if (split2[0].equals("rows")){
rows=split2[1];
}else if (split2[0].equals("resize")){
resize=split2[1];
}
}
String title = hash_get.get("title").toString();
String myValue =hash_get.get("MyValue").toString();
String[] splitValue = myValue.split("\\|");
RadioGroup[] rg;
RadioButton[] rb;
if (toggle.equals("true") && holder.row_list_title.getText().equals("")){
holder.row_list_placeholder.setVisibility(View.GONE);
String multiValue = hash_get.get("MultiValue").toString();
String[] splitMultiValue = multiValue.split(":");
if (splitMultiValue[1].equals("1")){
int p = 0;
rg = new RadioGroup[1];
rb = new RadioButton[splitValue.length];
rg[0] = new RadioGroup(holder.row_list_placeholder.getContext());
rg[0].setOrientation(RadioGroup.VERTICAL);
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
rb[j] = new RadioButton(getApplicationContext());
rg[p].addView(rb[j]);
rb[j].setId(j);
rb[j].setText(splitValue2[0]);
}
holder.linearLayoutCheckBox.addView(rg[p]);
p++;
holder.row_list_title.setText(title);
if (rg[0].getCheckedRadioButtonId() == -1) {
Log.d("RadioString", "Nothing selected");
} else {
for (int r = 0; r < splitValue.length; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
Log.d("RadioString", radioText);
} else {
Log.d("RadioString", "nothing");
}
}
}
}else{
//splitMultiValue[1]
holder.row_list_title.setText(title);
CheckBox[] ch;
final int[] checkd = {0};
ch = new CheckBox[splitValue.length];
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
ch[j] = new CheckBox(getApplicationContext());
holder.linearLayoutCheckBox.addView(ch[j]);
ch[j].setId(j);
ch[j].setText(splitValue2[0]);
}
for (int r = 0; r < splitValue.length; r++) {
int finalR = r;
ch[r].setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Log.d("_hdev", checkd[0] +"");
Log.d("_hdev",Integer.parseInt(splitMultiValue[1])+"");
if (checkd[0] < Integer.parseInt(splitMultiValue[1])){
//CheckBox id = findViewById(ch[finalR].getId());
//String CheckBoxText = id.getText().toString();
//Log.e("CheckBoxString", CheckBoxText);
checkd[0] = checkd[0] +1;
Log.d("_hdevn", "1");
}else{
//CheckBox id = (CheckBox) findViewById(ch[finalR].getId());
ch[finalR].setChecked(false);
//checkd[0] = checkd[0] -1 ;
Log.d("_hdevn", "2");
}
} else {
ch[finalR].setChecked(false);
checkd[0] = checkd[0] -1;
Log.d("_hdevn", "3");
}
});
}
}
}else{
if (myValue.equals("NULL")){
holder.row_list_title.setText(title);
holder.row_list_placeholder.setVisibility(View.VISIBLE);
holder.row_list_placeholder.setHint(hash_get.get("placeholder").toString());
if (type.equals("Text")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_TEXT);
}else if(type.equals("Int")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER);
}else if(type.equals("Float")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}else {
holder.row_list_placeholder.setVisibility(View.GONE);
/*
TextView[] tv;
final int[] checkd = {0};
tv = new TextView[splitValue.length];
for (int j = 0; j < hash_all2.size(); j++) {
Log.d("_hdev", hash_all2.get(j).get("selected"));
if (hash_all2.get(j).get("selected").equals("true")) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
tv[j] = new TextView(getApplicationContext());
holder.linearLayoutCheckBox.addView(tv[j]);
tv[j].setId(j);
tv[j].setText(hash_all2.get(j).get("name"));
}
}*/
//list popup
holder.row_list_title.setText(title);
holder.row_list_title.setOnClickListener(v -> {
profileadapter.notifyDataSetChanged();
//get_profiles();
/*if (hash_all2.size() == 0) {
for (int j = 0; j < splitValue.length; j++) {
HashMap<String, String> hash_add2 = new HashMap<>();
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
hash_add2.put("Id", String.valueOf(j));
hash_add2.put("name", String.valueOf(splitValue2[0]));
hash_add2.put("value", String.valueOf(splitValue2[1]));
hash_add2.put("selected", "false");
hash_all2.add(hash_add2);
}
adapt.notifyDataSetChanged();
}
alertDialogSelect();*/
});
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.row_form, parent, false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView row_list_title;
EditText row_list_placeholder;
LinearLayout linearLayoutCheckBox;
CardView cardrow;
ViewHolder(View itemView) {
super(itemView);
row_list_title = itemView.findViewById(R.id.row_list_title);
row_list_placeholder = itemView.findViewById(R.id.row_list_placeholder);
linearLayoutCheckBox = itemView.findViewById(R.id.mainrow);
}
}
}
this is what i tryed in many days.
You have to update your hash_all Arraylist before calling notifydatasatChanged()
you can put a boolean in your model to retain the checked and unchecked state of radio button and update the boolean and store the object in ur hash_all.
Note: notifydatasatChanged() is a heavy operation, it will refresh your complete list. try using notifyitemChanged(position) it will refresh only the clicked item.
I have a tic tac toe application which is only one little step away from being perfect. Basically the game works perfect during game play, the play makes a move by placing an X, then the computer makes a move a couple of seconds earlier placing their O and then it's back to the players move and then after their move a couple of seconds later the computer moves and etc.
The only issue I have which I cannot seem to figure out is when the game board resets. Basically when the winning move is made, we do not see the winning move, the board is reset, toast message is displayed stating who has won and if it is computers move first then their first move is made and this all happens at the same time. For the user they will be like what is going on how was the game won as it all happened in a flash.
I need to make a slight adjust so that the following happens:
1: Player sees the winning move either if it's their move or computers
2:
After seeing the winning move then the game board resets and the toast message appears stating who won or a draw
I don't mind the computer already making the first move already after the game board has reset, but the other two points I believe needs to be addressed.
Below is my code but I cannot seem to figure out how to ensure the above two points are reached when trying to manipulate the code:
public class MainActivityPlayer1 extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean playerOneMove = true;
private int turnsCount;
private int playerOnePoints;
private int playerTwoPoints;
private TextView textViewPlayerOne;
private TextView textViewPlayerTwo;
private TextView textViewPlayerOneTurn;
private TextView textViewPlayerTwoTurn;
private TextView textViewFooterTitle;
Button selectButton;
Random random = new Random();
boolean firstComputerMove = false;
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player1);
Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/ConcertOne-Regular.ttf");
textViewPlayerOne = findViewById(R.id.textView_player1);
textViewPlayerTwo = findViewById(R.id.textView_player2);
textViewPlayerOneTurn = findViewById(R.id.textView_player1Turn);
textViewPlayerTwoTurn = findViewById(R.id.textView_player2Turn);
textViewFooterTitle = findViewById(R.id.footer_title);
textViewPlayerOne.setTypeface(customFont);
textViewPlayerTwo.setTypeface(customFont);
textViewFooterTitle.setTypeface(customFont);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID).toString();
if (btnState.equals("X")) {
buttons[i][j].setTextColor(playerX);
} else {
buttons[i][j].setTextColor(playerO);
}
}
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setTypeface(customFont);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
Button buttonExit = findViewById(R.id.button_exit);
buttonExit.setTypeface(customFont);
buttonExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backToMainActivity();
}
});
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
turnsCount++;
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
isGameOver();
}
}
public void isGameOver() {
if (checkGameIsWon()) {
if (playerOneMove) {
player1Wins();
} else {
player2Wins();
}
} else if (turnsCount == 9) {
draw();
} else {
playerOneMove = !playerOneMove;
if (!playerOneMove) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
computerMove();
}
}, 1000);
}
}
}
private void computerMove() {
String[][] field = new String[3][3];
List<Button> emptyButtons = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.add(buttons[i][j]);
}
}
}
//IS COMPUTER GOING FIRST
if (firstComputerMove == true){
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
else {
//TAKE MIDDLE SQUARE IF NOT TAKEN
if (field[1][1].equals("")) {
selectButton = buttons[1][1];
}
//FIRST ROW ACROSS
else if (field[0][0] != "" && field[0][0].equals(field[0][1])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
} else if (field[0][0] != "" && field[0][0].equals(field[0][2])
&& field[0][1].equals("")) {
selectButton = buttons[0][1];
} else if (field[0][1] != "" && field[0][1].equals(field[0][2])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
}
//SECOND ROW ACROSS
else if (field[1][0] != "" && field[1][0].equals(field[1][1])
&& field[1][2].equals("")) {
selectButton = buttons[1][2];
} else if (field[1][0] != "" && field[1][0].equals(field[1][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[1][1] != "" && field[1][1].equals(field[1][2])
&& field[1][0].equals("")) {
selectButton = buttons[1][0];
}
//THIRD ROW ACROSS
else if (field[2][0] != "" && field[2][0].equals(field[2][1])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[2][0] != "" && field[2][0].equals(field[2][2])
&& field[2][1].equals("")) {
selectButton = buttons[2][1];
} else if (field[2][1] != "" && field[2][1].equals(field[2][2])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
}
//FIRST COLUMN DOWN
else if (field[0][2] != "" && field[0][2].equals(field[1][2])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[0][2] != "" && field[0][2].equals(field[2][2])
&& field[1][2].equals("")) {
selectButton = buttons[1][2];
} else if (field[1][2] != "" && field[1][2].equals(field[2][2])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
}
//SECOND COLUMN DOWN
else if (field[0][1] != "" && field[0][1].equals(field[1][1])
&& field[2][1].equals("")) {
selectButton = buttons[2][1];
} else if (field[0][1] != "" && field[0][1].equals(field[2][1])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[1][1] != "" && field[1][1].equals(field[2][1])
&& field[0][1].equals("")) {
selectButton = buttons[0][1];
}
//THIRD COLUMN DOWN
else if (field[0][0] != "" && field[0][0].equals(field[1][0])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
} else if (field[0][0] != "" && field[0][0].equals(field[2][0])
&& field[1][0].equals("")) {
selectButton = buttons[1][0];
} else if (field[2][0] != "" && field[2][0].equals(field[1][0])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
}
//DIAGAONAL TOP RIGHT BOTTOM LEFT
else if (field[2][0] != "" && field[2][0].equals(field[0][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[2][0] != "" && field[2][0].equals(field[1][1])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
} else if (field[1][1] != "" && field[1][1].equals(field[0][2])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
}
//DIAGAONAL TOP LEFT BOTTOM RIGHT
else if (field[0][0] != "" && field[0][0].equals(field[2][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[0][0] != "" && field[0][0].equals(field[1][1])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[1][1] != "" && field[1][1].equals(field[2][2])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
} else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
firstComputerMove = false;
turnsCount++;
isGameOver();
}
private boolean checkGameIsWon() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
playerOnePoints++;
Toast.makeText(this, "Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
playerTwoPoints++;
Toast.makeText(this, "Computer wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
firstComputerMove = true;
computerMove();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
playerOneMove = !playerOneMove;
switchPlayerTurn();
if (!playerOneMove){
firstComputerMove = true;
computerMove();
}
}
#SuppressLint("SetTextI18n")
private void updatePointsText() {
textViewPlayerOne.setText("PLAYER 1: " + playerOnePoints + " ");
textViewPlayerTwo.setText("COMPUTER: " + playerTwoPoints + " ");
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
turnsCount = 0;
switchPlayerTurn();
}
private void resetGame() {
playerOnePoints = 0;
playerTwoPoints = 0;
turnsCount = 0;
playerOneMove = true;
updatePointsText();
resetBoard();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("turnsCount", turnsCount);
outState.putInt("playerOnePoints", playerOnePoints);
outState.putInt("playerTwoPoints", playerTwoPoints);
outState.putBoolean("playerOneMove", playerOneMove);
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
turnsCount = savedInstanceState.getInt("turnsCount");
playerOnePoints = savedInstanceState.getInt("playerOnePoints");
playerTwoPoints = savedInstanceState.getInt("playerTwoPoints");
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
savedInstanceState.putCharSequence(buttonID, btn.getText());
}
}
}
private void switchPlayerTurn(){
if (playerOneMove){
textViewPlayerOneTurn.setVisibility(View.VISIBLE);
textViewPlayerTwoTurn.setVisibility(View.INVISIBLE);
}
else{
textViewPlayerOneTurn.setVisibility(View.INVISIBLE);
textViewPlayerTwoTurn.setVisibility(View.VISIBLE);
}
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
}
I would recommend that you use Thread.sleep if a player wins to give time to show the final move.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resetBoard();
firstComputerMove = true;
computerMove();
You could also incorporate an AlertDialog to ask the user to play again after pause and the final move
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Play again?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Play Again
resetBoard();
firstComputerMove = true;
computerMove();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Exit Game
}
})
.show();
This is how I am trying to execute my code.
private final class BoxSelect implements View.OnTouchListener
{
public boolean onTouch(View view, MotionEvent motionEvent)
{
setView(view);
setMotionEvent(motionEvent);
if (t1.getState() == Thread.State.NEW)
{
t1.start();
if (getHit() == false) {
t2.start();
}
}
return false;
}
}
I have two thread created called t1 and t2 which take the two runnable methods r1 and r1 as parameters:
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
R1 is defined as:
Runnable r1 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t1");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
View view1 = getView();
MotionEvent motionEvent1 = getMotionEvent();
public void whenCreate()
{
System.out.println("HERE t1");
hit = false;
boolean goToElse = true;
boolean hit2 = false;
boolean goToElse2 = true;
if (motionEvent1.getAction() == MotionEvent.ACTION_DOWN) {
for (int i = 0; i < ids.length; i++) {
for (int j = 0; j < ids.length; j++) {
String coord = b.getBoard()[i][j];
if (view == ids[i][j]) {
System.out.println("ATTACKING " + b.getCompTempBoard()[i][j]);
player.basicAttack(b.getBoard(), coord, ai);
}
if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("HIT")) {
System.out.println("Hit GUI");
if (ids[i][j].getBackground().equals(hitTarget)) {
hit = true;
goToElse = false;
} else {
ids[i][j].setBackgroundDrawable(hitTarget);
System.out.println("ert 1 " + b.getCompTempBoard()[i][j]);
playerCount++;
if (playerCount == 10) {
player.endGame();
b.incrementPlayerCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU WIN :)\nScore is:\nPlayer: " + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
hit = true;
goToElse = false;
}
} else if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("MISS")) {
System.out.println("MISS GUI 1");
if (ids[i][j].getBackground().equals(missTarget)) {
hit = true;
goToElse = false;
} else {
System.out.println("MISS GUI");
ids[i][j].setBackgroundDrawable(missTarget);
System.out.println("ert 2 " + b.getCompTempBoard()[i][j]);
hit = true;
goToElse = true;
}
}
if (goToElse == true) {
hit = false;
System.out.println("MISS PLAYER GUI");
view.setBackgroundDrawable(missTarget);
}
}
}
}
}
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
}
}
};
and R2 is:
Runnable r2 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t2");
try {
TimeUnit.NANOSECONDS.sleep(1);
System.out.println("HERE 2");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
public boolean onTouch(View view, MotionEvent motionEvent) {
System.out.println("HERE t2");
if (hit == false) {
System.out.println("SLEEPING 2");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("COMPUTERS TURN");
ai.advancedAttack(b.getBoard(), ai.getRandomCoordinate_For_Attacking_6x6(), player);
System.out.println("First attack: " + ai.getFirstCoord());
boolean goAgain = true;
while (goAgain == true) {
for (int w = 0; w < ids2.length; w++) {
for (int y = 0; y < ids2.length; y++) {
if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("HIT")) {
System.out.println("DR 1");
ids2[w][y].setBackgroundDrawable(hitTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
System.out.println("Next: " + ai.getFirstCoord());
ai.advancedAttack(b.getBoard(), ai.getFirstCoord(), player);
System.out.println("After attack in loop");
goAgain = true;
CompCount++;
if (CompCount == 10) {
b.incrementCompCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU LOSE :(\n" + "Score is:\n" + "Player: \n" + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
} else if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("MISS")) {
System.out.println("DR 2");
ids2[w][y].setBackgroundDrawable(missTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
goAgain = false;
}
}
}
}
}
return hit;
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
System.out.println("IN CATCH");
}
System.out.println("END");
}
};`
I originally had these two together as one block, but separated it as I wish to pause thread 2 from occurring for one second after thread 2.
The problem I am having is that the BoxSelect class is not getting executed inside the R1 and R2 and so none of the code is executing. Any help on this matter would be appreciated!
How to animate Cards in android Card Game Like "Spades Free". My game is quite the same as crazy 8.i used android game development for dummies as a reference.but, i want to animate cards how can i do that.
public class GameView extends View {
private int screenW;
private int screenH;
private Context myContext;
private List<Card> deck = new ArrayList<Card>();
private int scaledCardW;
private int scaledCardH;
private Paint whitePaint;
private List<Card> myHand = new ArrayList<Card>();
private List<Card> oppHand = new ArrayList<Card>();
private int myScore = 0;
private int oppScore = 0;
private float scale;
private Bitmap cardBack;
private List<Card> discardPile = new ArrayList<Card>();
private boolean myTurn;
private ComputerPlayer computerPlayer = new ComputerPlayer();
private int movingCardIdx = -1;
private int movingX;
private int movingY;
private int validRank = 8;
private int validSuit = 0;
private Bitmap nextCardButton;
private int scoreThisHand = 0;
public GameView(Context context) {
super(context);
myContext = context;
scale = myContext.getResources().getDisplayMetrics().density;
whitePaint = new Paint();
whitePaint.setAntiAlias(true);
whitePaint.setColor(Color.WHITE);
whitePaint.setStyle(Paint.Style.STROKE);
whitePaint.setTextAlign(Paint.Align.LEFT);
whitePaint.setTextSize(scale*15);
}
#Override
public void onSizeChanged (int w, int h, int oldw, int oldh){
super.onSizeChanged(w, h, oldw, oldh);
screenW = w;
screenH = h;
Bitmap tempBitmap = BitmapFactory.decodeResource(myContext.getResources(), R.drawable.card_back);
scaledCardW = (int) (screenW/8);
scaledCardH = (int) (scaledCardW*1.28);
cardBack = Bitmap.createScaledBitmap(tempBitmap, scaledCardW, scaledCardH, false);
nextCardButton = BitmapFactory.decodeResource(getResources(), R.drawable.arrow_next);
initCards();
dealCards();
drawCard(discardPile);
validSuit = discardPile.get(0).getSuit();
validRank = discardPile.get(0).getRank();
myTurn = new Random().nextBoolean();
if (!myTurn) {
makeComputerPlay();
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawText("Computer Score: " + Integer.toString(oppScore), 10, whitePaint.getTextSize()+10, whitePaint);
canvas.drawText("My Score: " + Integer.toString(myScore), 10, screenH-whitePaint.getTextSize()-10, whitePaint);
for (int i = 0; i < oppHand.size(); i++) {
canvas.drawBitmap(cardBack,
i*(scale*5),
whitePaint.getTextSize()+(50*scale),
null);
}
canvas.drawBitmap(cardBack, (screenW/2)-cardBack.getWidth()-10, (screenH/2)-(cardBack.getHeight()/2), null);
if (!discardPile.isEmpty()) {
canvas.drawBitmap(discardPile.get(0).getBitmap(),
(screenW/2)+10,
(screenH/2)-(cardBack.getHeight()/2),
null);
}
if (myHand.size() > 7) {
canvas.drawBitmap(nextCardButton,
screenW-nextCardButton.getWidth()-(30*scale),
screenH-nextCardButton.getHeight()-scaledCardH-(90*scale),
null);
}
for (int i = 0; i < myHand.size(); i++) {
if (i == movingCardIdx) {
canvas.drawBitmap(myHand.get(i).getBitmap(),
movingX,
movingY,
null);
} else {
if (i < 7) {
canvas.drawBitmap(myHand.get(i).getBitmap(),
i*(scaledCardW+5),
screenH-scaledCardH-whitePaint.getTextSize()-(50*scale),
null);
}
}
}
invalidate();
}
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
int X = (int)event.getX();
int Y = (int)event.getY();
switch (eventaction ) {
case MotionEvent.ACTION_DOWN:
if (myTurn) {
for (int i = 0; i < 7; i++) {
if (X > i*(scaledCardW+5) && X < i*(scaledCardW+5) + scaledCardW &&
Y > screenH-scaledCardH-whitePaint.getTextSize()-(50*scale)) {
movingCardIdx = i;
movingX = X-(int)(30*scale);
movingY = Y-(int)(70*scale);
}
}
}
break;
case MotionEvent.ACTION_MOVE:
movingX = X-(int)(30*scale);
movingY = Y-(int)(70*scale);
break;
case MotionEvent.ACTION_UP:
if (movingCardIdx > -1 &&
X > (screenW/2)-(100*scale) &&
X < (screenW/2)+(100*scale) &&
Y > (screenH/2)-(100*scale) &&
Y < (screenH/2)+(100*scale) &&
(myHand.get(movingCardIdx).getRank() == 8 ||
myHand.get(movingCardIdx).getRank() == validRank ||
myHand.get(movingCardIdx).getSuit() == validSuit)) {
validRank = myHand.get(movingCardIdx).getRank();
validSuit = myHand.get(movingCardIdx).getSuit();
discardPile.add(0, myHand.get(movingCardIdx));
myHand.remove(movingCardIdx);
if (myHand.isEmpty()) {
endHand();
} else {
if (validRank == 8) {
showChooseSuitDialog();
} else {
myTurn = false;
makeComputerPlay();
}
}
}
if (movingCardIdx == -1 && myTurn &&
X > (screenW/2)-(100*scale) &&
X < (screenW/2)+(100*scale) &&
Y > (screenH/2)-(100*scale) &&
Y < (screenH/2)+(100*scale)) {
if (checkForValidDraw()) {
drawCard(myHand);
} else {
Toast.makeText(myContext, "You have a valid play.", Toast.LENGTH_SHORT).show();
}
}
if (myHand.size() > 7 &&
X > screenW-nextCardButton.getWidth()-(30*scale) &&
Y > screenH-nextCardButton.getHeight()-scaledCardH-(90*scale) &&
Y < screenH-nextCardButton.getHeight()-scaledCardH-(60*scale)) {
Collections.rotate(myHand, 1);
}
movingCardIdx = -1;
break;
}
invalidate();
return true;
}
private void showChooseSuitDialog() {
final Dialog chooseSuitDialog = new Dialog(myContext);
chooseSuitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
chooseSuitDialog.setContentView(R.layout.choose_suit_dialog);
final Spinner suitSpinner = (Spinner) chooseSuitDialog.findViewById(R.id.suitSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
myContext, R.array.suits, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
suitSpinner.setAdapter(adapter);
Button okButton = (Button) chooseSuitDialog.findViewById(R.id.okButton);
okButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
validSuit = (suitSpinner.getSelectedItemPosition()+1)*100;
String suitText = "";
if (validSuit == 100) {
suitText = "Diamonds";
} else if (validSuit == 200) {
suitText = "Clubs";
} else if (validSuit == 300) {
suitText = "Hearts";
} else if (validSuit == 400) {
suitText = "Spades";
}
chooseSuitDialog.dismiss();
Toast.makeText(myContext, "You chose " + suitText, Toast.LENGTH_SHORT).show();
myTurn = false;
makeComputerPlay();
}
});
chooseSuitDialog.show();
}
private void initCards() {
for (int i = 0; i < 4; i++) {
for (int j = 102; j < 115; j++) {
int tempId = j + (i*100);
Card tempCard = new Card(tempId);
int resourceId = getResources().getIdentifier("card" + tempId, "drawable", myContext.getPackageName());
Bitmap tempBitmap = BitmapFactory.decodeResource(myContext.getResources(), resourceId);
scaledCardW = (int) (screenW/8);
scaledCardH = (int) (scaledCardW*1.28);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(tempBitmap, scaledCardW, scaledCardH, false);
tempCard.setBitmap(scaledBitmap);
deck.add(tempCard);
}
}
}
private void drawCard(List<Card> handToDraw) {
handToDraw.add(0, deck.get(0));
deck.remove(0);
if (deck.isEmpty()) {
for (int i = discardPile.size()-1; i > 0 ; i--) {
deck.add(discardPile.get(i));
discardPile.remove(i);
Collections.shuffle(deck,new Random());
}
}
}
private void dealCards() {
Collections.shuffle(deck,new Random());
for (int i = 0; i < 7; i++) {
drawCard(myHand);
drawCard(oppHand);
}
}
private boolean checkForValidDraw() {
boolean canDraw = true;
for (int i = 0; i < myHand.size(); i++) {
int tempId = myHand.get(i).getId();
int tempRank = myHand.get(i).getRank();
int tempSuit = myHand.get(i).getSuit();
if (validSuit == tempSuit || validRank == tempRank ||
tempId == 108 || tempId == 208 || tempId == 308 || tempId == 408) {
canDraw = false;
}
}
return canDraw;
}
private void makeComputerPlay() {
int tempPlay = 0;
while (tempPlay == 0) {
tempPlay = computerPlayer.makePlay(oppHand, validSuit, validRank);
if (tempPlay == 0) {
drawCard(oppHand);
}
}
if (tempPlay == 108 || tempPlay == 208 || tempPlay == 308 || tempPlay == 408) {
validRank = 8;
validSuit = computerPlayer.chooseSuit(oppHand);
String suitText = "";
if (validSuit == 100) {
suitText = "Diamonds";
} else if (validSuit == 200) {
suitText = "Clubs";
} else if (validSuit == 300) {
suitText = "Hearts";
} else if (validSuit == 400) {
suitText = "Spades";
}
Toast.makeText(myContext, "Computer chose " + suitText, Toast.LENGTH_SHORT).show();
} else {
validSuit = Math.round((tempPlay/100) * 100);
validRank = tempPlay - validSuit;
}
for (int i = 0; i < oppHand.size(); i++) {
Card tempCard = oppHand.get(i);
if (tempPlay == tempCard.getId()) {
discardPile.add(0, oppHand.get(i));
oppHand.remove(i);
}
}
if (oppHand.isEmpty()) {
endHand();
}
myTurn = true;
}
}
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_center"
android:state_pressed="true" />
<item android:drawable="#drawable/unpressed_center" />
You should make draweble in same layout file for pres or not press version
I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];