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();
Related
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;
}
actually I'm using this part of code but nothing shown in screen
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, elativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
And this is the activity codes
public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate {
private boolean finished;
private String videoPath;
private String sendingText;
private ArrayList<Uri> photoPathsArray;
private ArrayList<String> documentsPathsArray;
private ArrayList<Uri> documentsUrisArray;
private String documentsMimeType;
private ArrayList<String> documentsOriginalPathsArray;
private ArrayList<TLRPC.User> contactsToSend;
private int currentConnectionState;
private static ArrayList<BaseFragment> mainFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> layerFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> rightFragmentsStack = new ArrayList<>();
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
private ActionBarLayout actionBarLayout;
private ActionBarLayout layersActionBarLayout;
private ActionBarLayout rightActionBarLayout;
private FrameLayout shadowTablet;
private FrameLayout shadowTabletSide;
private View backgroundTablet;
protected DrawerLayoutContainer drawerLayoutContainer;
private DrawerLayoutAdapter drawerLayoutAdapter;
private PasscodeView passcodeView;
private AlertDialog visibleDialog;
private RecyclerListView sideMenu;
private AlertDialog localeDialog;
private boolean loadingLocaleDialog;
private HashMap<String, String> systemLocaleStrings;
private HashMap<String, String> englishLocaleStrings;
private Intent passcodeSaveIntent;
private boolean passcodeSaveIntentIsNew;
private boolean passcodeSaveIntentIsRestore;
private boolean tabletFullSize;
private Runnable lockRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationLoader.postInitApplication();
NativeCrashManager.handleDumpFiles(this);
AndroidUtilities.checkDisplaySize(this, getResources().getConfiguration());
Log.i(this.getClass().getName(), "onCreate: ");
if (!UserConfig.isClientActivated()) {
Intent intent = getIntent();
if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
super.onCreate(savedInstanceState);
finish();
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
long crashed_time = preferences.getLong("intro_crashed_time", 0);
boolean fromIntro = intent.getBooleanExtra("fromIntro", false);
if (fromIntro) {
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
if (Math.abs(crashed_time - System.currentTimeMillis()) >= 60 * 2 * 1000 && intent != null && !fromIntro) {
preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
Map<String, ?> state = preferences.getAll();
if (state.isEmpty()) {
Intent intent2 = new Intent(this, IntroActivity.class);
intent2.setData(intent.getData());
startActivity(intent2);
super.onCreate(savedInstanceState);
finish();
return;
}
}
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(R.style.Theme_TMessages);
getWindow().setBackgroundDrawableResource(R.drawable.transparent);
if (UserConfig.passcodeHash.length() > 0 && !UserConfig.allowScreenCapture) {
try {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
}
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 24) {
AndroidUtilities.isInMultiwindow = isInMultiWindowMode();
}
Theme.createChatResources(this, false);
if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
actionBarLayout = new ActionBarLayout(this);
drawerLayoutContainer = new DrawerLayoutContainer(this);
setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (AndroidUtilities.isTablet()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
RelativeLayout launchLayout = new RelativeLayout(this) {
private boolean inLayout;
#Override
public void requestLayout() {
if (inLayout) {
return;
}
super.requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
inLayout = true;
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
tabletFullSize = false;
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTabletSide.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
rightActionBarLayout.measure(MeasureSpec.makeMeasureSpec(width - leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else {
tabletFullSize = true;
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
backgroundTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
layersActionBarLayout.measure(MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(530), width), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(528), height), MeasureSpec.EXACTLY));
inLayout = false;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
shadowTabletSide.layout(leftWidth, 0, leftWidth + shadowTabletSide.getMeasuredWidth(), shadowTabletSide.getMeasuredHeight());
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
rightActionBarLayout.layout(leftWidth, 0, leftWidth + rightActionBarLayout.getMeasuredWidth(), rightActionBarLayout.getMeasuredHeight());
} else {
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
}
int x = (width - layersActionBarLayout.getMeasuredWidth()) / 2;
int y = (height - layersActionBarLayout.getMeasuredHeight()) / 2;
layersActionBarLayout.layout(x, y, x + layersActionBarLayout.getMeasuredWidth(), y + layersActionBarLayout.getMeasuredHeight());
backgroundTablet.layout(0, 0, backgroundTablet.getMeasuredWidth(), backgroundTablet.getMeasuredHeight());
shadowTablet.layout(0, 0, shadowTablet.getMeasuredWidth(), shadowTablet.getMeasuredHeight());
}
};
drawerLayoutContainer.addView(launchLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
backgroundTablet = new View(this);
//BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.catstile);
//drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
backgroundTablet.setBackgroundResource(R.drawable.catstile);
launchLayout.addView(backgroundTablet, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
launchLayout.addView(actionBarLayout);
rightActionBarLayout = new ActionBarLayout(this);
rightActionBarLayout.init(rightFragmentsStack);
rightActionBarLayout.setDelegate(this);
launchLayout.addView(rightActionBarLayout);
shadowTabletSide = new FrameLayout(this);
shadowTabletSide.setBackgroundColor(0x40295274);
launchLayout.addView(shadowTabletSide);
shadowTablet = new FrameLayout(this);
shadowTablet.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
shadowTablet.setBackgroundColor(0x7f000000);
launchLayout.addView(shadowTablet);
shadowTablet.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
int location[] = new int[2];
layersActionBarLayout.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
if (layersActionBarLayout.checkTransitionAnimation() || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) {
return false;
} else {
if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
a--;
}
layersActionBarLayout.closeLastFragment(true);
}
return true;
}
}
return false;
}
});
shadowTablet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layersActionBarLayout = new ActionBarLayout(this);
layersActionBarLayout.setRemoveActionBarExtraHeight(true);
layersActionBarLayout.setBackgroundView(shadowTablet);
layersActionBarLayout.setUseAlphaAnimations(true);
layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
layersActionBarLayout.init(layerFragmentsStack);
layersActionBarLayout.setDelegate(this);
layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
layersActionBarLayout.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
launchLayout.addView(layersActionBarLayout);
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
} else {
drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
sideMenu = new RecyclerListView(this);
sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
sideMenu.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
drawerLayoutContainer.setDrawerLayout(sideMenu);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) sideMenu.getLayoutParams();
Point screenSize = AndroidUtilities.getRealScreenSize();
layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320) : Math.min(AndroidUtilities.dp(320), Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56));
layoutParams.height = LayoutHelper.MATCH_PARENT;
sideMenu.setLayoutParams(layoutParams);
sideMenu.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
#Override
public void onItemClick(final View view, int position) {
int id = drawerLayoutAdapter.getId(position);
if (position == 0) {
Bundle args = new Bundle();
args.putInt("user_id", UserConfig.getClientUserId());
presentFragment(new ChatActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 2) {
if (!MessagesController.isFeatureEnabled("chat_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
presentFragment(new GroupCreateActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 3) {
Bundle args = new Bundle();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("createSecretChat", true);
args.putBoolean("allowBots", false);
presentFragment(new ContactsActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 4) {
if (!MessagesController.isFeatureEnabled("broadcast_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (!BuildVars.DEBUG_VERSION && preferences.getBoolean("channel_intro", false)) {
Bundle args = new Bundle();
args.putInt("step", 0);
presentFragment(new ChannelCreateActivity(args));
} else {
presentFragment(new ChannelIntroActivity());
preferences.edit().putBoolean("channel_intro", true).commit();
}
drawerLayoutContainer.closeDrawer(false);
} else if (id == 6) {
presentFragment(new ContactsActivity(null));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 7) {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
/*AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTopImage(R.drawable.permissions_contacts, 0xff35a8e0);
builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("ContactsPermissionAlert", R.string.ContactsPermissionAlert)));
builder.setPositiveButton(LocaleController.getString("ContactsPermissionAlertContinue", R.string.ContactsPermissionAlertContinue), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(LocaleController.getString("ContactsPermissionAlertNotNow", R.string.ContactsPermissionAlertNotNow), null);
showAlertDialog(builder);*/
showLanguageAlert(true);
} else {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText());
startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500);
} catch (Exception e) {
FileLog.e(e);
}
drawerLayoutContainer.closeDrawer(false);
}
} else if (id == 8) {
presentFragment(new SettingsActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 9) {
Browser.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 10) {
presentFragment(new CallLogActivity());
drawerLayoutContainer.closeDrawer(false);
}
}
});
drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
actionBarLayout.init(mainFragmentsStack);
actionBarLayout.setDelegate(this);
Theme.loadWallpaper();
passcodeView = new PasscodeView(this);
drawerLayoutContainer.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetNewWallpapper);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInterface);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.suggestedLangpack);
if (actionBarLayout.fragmentsStack.isEmpty()) {
if (!UserConfig.isClientActivated()) {
actionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
try {
if (savedInstanceState != null) {
String fragmentName = savedInstanceState.getString("fragment");
if (fragmentName != null) {
Bundle args = savedInstanceState.getBundle("args");
switch (fragmentName) {
case "chat":
if (args != null) {
ChatActivity chat = new ChatActivity(args);
if (actionBarLayout.addFragmentToStack(chat)) {
chat.restoreSelfArgs(savedInstanceState);
}
}
break;
case "settings": {
SettingsActivity settings = new SettingsActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
case "group":
if (args != null) {
GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
if (actionBarLayout.addFragmentToStack(group)) {
group.restoreSelfArgs(savedInstanceState);
}
}
break;
case "channel":
if (args != null) {
ChannelCreateActivity channel = new ChannelCreateActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "edit":
if (args != null) {
ChannelEditActivity channel = new ChannelEditActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "chat_profile":
if (args != null) {
ProfileActivity profile = new ProfileActivity(args);
if (actionBarLayout.addFragmentToStack(profile)) {
profile.restoreSelfArgs(savedInstanceState);
}
}
break;
case "wallpapers": {
WallpapersActivity settings = new WallpapersActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
if (fragment instanceof DialogsActivity) {
((DialogsActivity) fragment).setSideMenu(sideMenu);
}
boolean allowOpen = true;
if (AndroidUtilities.isTablet()) {
allowOpen = actionBarLayout.fragmentsStack.size() <= 1 && layersActionBarLayout.fragmentsStack.isEmpty();
if (layersActionBarLayout.fragmentsStack.size() == 1 && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
}
if (actionBarLayout.fragmentsStack.size() == 1 && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
}
checkLayout();
handleIntent(getIntent(), false, savedInstanceState != null, false);
try {
String os1 = Build.DISPLAY;
String os2 = Build.USER;
if (os1 != null) {
os1 = os1.toLowerCase();
} else {
os1 = "";
}
if (os2 != null) {
os2 = os1.toLowerCase();
} else {
os2 = "";
}
if (os1.contains("flyme") || os2.contains("flyme")) {
AndroidUtilities.incorrectDisplaySizeFix = true;
final View view = getWindow().getDecorView().getRootView();
view.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if (Build.VERSION.SDK_INT >= 21) {
height -= AndroidUtilities.statusBarHeight;
}
if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
AndroidUtilities.displaySize.y = height;
FileLog.e("fix display size y to " + AndroidUtilities.displaySize.y);
}
}
});
}
} catch (Exception e) {
FileLog.e(e);
}
MediaController.getInstance().setBaseActivity(this, true);
}
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];