Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class MainActivity extends AppCompatActivity
implements BoardEventAdapter {
private FrameLayout mBoardFrame;
private BoardLayout mBoardUI:
private TTTBoardGame mGame;
// called when new game is initialized
@Override
public void onPlayerWire(Event e) {
if (mBoardUI != null) {
mBoardFrame.removeAllViews();
mBoardUI = null;
}
mBoardUI = new BoardLayout();
mBoardUI.setRows(3);
mBoardUI.setColumns(3);
mBoardUI.setDefaultCellParams(new BoardLayout.CellParams((float) 0));
// mBoardUI.setBackground(R.drawable.tttbackground); // uncomment this line when you add a tic tac toe background
// the background should show grid lines - grab one from the internet
mBoardUI.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mBoardFrame.addView(mBoardUI);
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
final TextView cellDisplay = new TextView(getContext());
cellDisplay.setText("");
cellDisplay.setLayoutParams(new BoardLayout.LayoutParams(r, c));
final int row = r;
final int col = c;
cellDisplay.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent e) {
final int turnof = TTTBoardGame.extractCtl(mGame).getCurrentId();
final TTTHumanPlayer player = (TTTHumanPlayer) mGame.getPlayer(turnof);
player.deliverTurn(row, col);
// if move passes update the text in onMove
}
};
}
}
}
@Override
public void onMove(Event e) {
final MoveEvent me = (MoveEvent) e;
final int row = me.destRow;
final int col = me.destCol;
final Piece p = mGame.pieceAt(row, col);
final int player = p.playerId();
if (player == 0) { // O
((TextView) mBoardUI.findViewAt(row, col)).setText("O");
else
((TextView) mBoardUI.findViewAt(row, col)).setText("X");
}
@Override
public void onFinish(Event e) {
new AlertDialog.Builder(getContext())
.setMessage("Game over, try adding the feature of renewing the game now!!!")
.show();
}
@Override
public void onTimerTick(Event e) {
}
@Override
public void onElimination(Event e) {
}
@Override
public void onOther(Event e) {
}
private InjectedBoardEventAdapter mThisListener;
@Override
public void onStart() {
super.onStart();
mBoardFrame = findViewById(R.id.boardFrame);
mThisListener = new InjectedBoardEventAdapter(this);// as we implemented BoardEventAdapter
mGame = new TTTBoardGame();
TTTBoardGame.newTwoHumanPlayerGame();
// now the magic occurs => onPlayerWire is called
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.