Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.myxogame;
- import androidx.appcompat.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ImageButton;
- import android.widget.Toast;
- public class MainActivity extends AppCompatActivity {
- private ImageButton[][] btns;
- private int player = 1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btns = new ImageButton[3][3];
- for (int r = 0; r < 3; r++) {
- for (int c = 0; c < 3; c++) {
- // btns[0][0] = findViewById(R.id.ibtn00);
- String name = "ibtn" + r + c;
- int id = getResources().getIdentifier(name, "id", getPackageName());
- btns[r][c] = findViewById(id);
- btns[r][c].setImageResource(R.drawable.ic_launcher_background);
- btns[r][c].setTag(R.drawable.ic_launcher_background);
- }
- }
- }
- public void btnClicked(View view) {
- if (player == 1) {
- ((ImageButton) view).setImageResource(R.drawable.x);
- view.setTag(R.drawable.x);
- if (win()) {
- Toast.makeText(this, "player " + player + " win", Toast.LENGTH_SHORT).show();
- } else
- player = 2;
- } else {
- ((ImageButton) view).setImageResource(R.drawable.o);
- view.setTag(R.drawable.o);
- if (win()) {
- Toast.makeText(this, "player " + player + " win", Toast.LENGTH_SHORT).show();
- } else
- player = 1;
- }
- }
- public boolean win() {
- if (winRow()) //|| winCol() || diag1() || diag2())
- return true;
- else
- return false;
- }
- private boolean winRow() {
- for (int r = 0; r < 3; r++) {
- boolean same1, same2;
- same1 = (int) (btns[r][0].getTag()) == (int) (btns[r][1].getTag());
- same2 = (int) (btns[r][1].getTag()) == (int) (btns[r][2].getTag());
- if (same1==true && same2==true)
- return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement