Advertisement
mmayoub

XO, ver 1.0 - java

Nov 18th, 2022 (edited)
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | Software | 0 0
  1. package com.example.myxogame;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4.  
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.ImageButton;
  8. import android.widget.Toast;
  9.  
  10. public class MainActivity extends AppCompatActivity {
  11.     private ImageButton[][] btns;
  12.     private int player = 1;
  13.  
  14.     @Override
  15.     protected void onCreate(Bundle savedInstanceState) {
  16.         super.onCreate(savedInstanceState);
  17.         setContentView(R.layout.activity_main);
  18.  
  19.         btns = new ImageButton[3][3];
  20.         for (int r = 0; r < 3; r++) {
  21.             for (int c = 0; c < 3; c++) {
  22.                 // btns[0][0] = findViewById(R.id.ibtn00);
  23.                 String name = "ibtn" + r + c;
  24.                 int id = getResources().getIdentifier(name, "id", getPackageName());
  25.                 btns[r][c] = findViewById(id);
  26.                 btns[r][c].setImageResource(R.drawable.ic_launcher_background);
  27.                 btns[r][c].setTag(R.drawable.ic_launcher_background);
  28.             }
  29.         }
  30.     }
  31.  
  32.     public void btnClicked(View view) {
  33.         if (player == 1) {
  34.             ((ImageButton) view).setImageResource(R.drawable.x);
  35.             view.setTag(R.drawable.x);
  36.             if (win()) {
  37.                 Toast.makeText(this, "player " + player + " win", Toast.LENGTH_SHORT).show();
  38.             } else
  39.                 player = 2;
  40.         } else {
  41.             ((ImageButton) view).setImageResource(R.drawable.o);
  42.             view.setTag(R.drawable.o);
  43.             if (win()) {
  44.                 Toast.makeText(this, "player " + player + " win", Toast.LENGTH_SHORT).show();
  45.             } else
  46.                 player = 1;
  47.         }
  48.     }
  49.  
  50.     public boolean win() {
  51.         if (winRow()) //|| winCol() || diag1() || diag2())
  52.             return true;
  53.         else
  54.             return false;
  55.     }
  56.  
  57.     private boolean winRow() {
  58.         for (int r = 0; r < 3; r++) {
  59.             boolean same1, same2;
  60.             same1 = (int) (btns[r][0].getTag()) == (int) (btns[r][1].getTag());
  61.             same2 = (int) (btns[r][1].getTag()) == (int) (btns[r][2].getTag());
  62.             if (same1==true && same2==true)
  63.                 return true;
  64.         }
  65.  
  66.         return false;
  67.     }
  68.  
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement