Saturday, January 22, 2011

Tutorial: A Simple TicTacToe App On Android



I found this code pretty useful for beginners to learn java programming and at the same time coming up with something fun and useful.

main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<!-- Demonstrates using a relative layout to create a form --> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"> 
                  
    <Button android:id="@+id/one" 
            android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_alignParentRight="true" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" /> 
            
    <Button android:id="@+id/two" 
          android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_toLeftOf="@id/one" 
            android:layout_alignTop="@id/one" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" /> 
            
    <Button android:id="@+id/three" 
          android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_toLeftOf="@id/two" 
            android:layout_alignTop="@id/two" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" 
            android:padding="0px"/> 
                        
    <Button android:id="@+id/four" 
            android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_alignParentRight="true" 
            android:layout_marginLeft="5px" 
            android:layout_below="@id/one" 
            android:text=" " 
            android:textSize="70px" /> 
            
     <Button android:id="@+id/five" 
          android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_toLeftOf="@id/four" 
            android:layout_alignTop="@id/four" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" /> 
            
    <Button android:id="@+id/six" 
          android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_toLeftOf="@id/five" 
            android:layout_alignTop="@id/five" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" /> 
            
    <Button android:id="@+id/seven" 
            android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_alignParentRight="true" 
            android:layout_marginLeft="5px" 
            android:layout_below="@id/four" 
            android:text=" " 
            android:textSize="70px" /> 
            
     <Button android:id="@+id/eight" 
          android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_toLeftOf="@id/seven" 
            android:layout_alignTop="@id/seven" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" /> 
            
    <Button android:id="@+id/nine" 
          android:layout_width="100px" 
            android:layout_height="100px" 
            android:layout_toLeftOf="@id/eight" 
            android:layout_alignTop="@id/eight" 
            android:layout_marginLeft="5px" 
            android:text=" " 
            android:textSize="70px" /> 
      
     <TextView android:id="@+id/dialogue" 
          android:layout_width="fill_parent" 
          android:layout_below="@id/nine" 
          android:layout_height="wrap_content" 
          android:text="Click a button to start" 
          android:gravity="center_horizontal" 
          android:layout_marginTop="20px" 
          android:textSize="20px"/> 
      
</RelativeLayout> 









TicTacToe.java:

package com.games.tictactoe;


import java.util.Random;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class TicTacToe extends Activity {


     int c[][];
     int i, j, k = 0;
     Button b[][];
     TextView textView;
     AI ai;


     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);        


          setBoard();
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
          super.onCreateOptionsMenu(menu);
          MenuItem item = menu.add("New Game");
          return true;
     }
    
     public boolean onOptionsItemSelected(MenuItem item) {
          setBoard();
          return true;
     }


     // Set up the game board.
     private void setBoard() {
          ai = new AI();
          b = new Button[4][4];
          c = new int[4][4];


          textView = (TextView) findViewById(R.id.dialogue);


          b[1][3] = (Button) findViewById(R.id.one);
          b[1][2] = (Button) findViewById(R.id.two);
          b[1][1] = (Button) findViewById(R.id.three);


          b[2][3] = (Button) findViewById(R.id.four);
          b[2][2] = (Button) findViewById(R.id.five);
          b[2][1] = (Button) findViewById(R.id.six);


          b[3][3] = (Button) findViewById(R.id.seven);
          b[3][2] = (Button) findViewById(R.id.eight);
          b[3][1] = (Button) findViewById(R.id.nine);
        
          for (i = 1; i <= 3; i++) {
               for (j = 1; j <= 3; j++)
                    c[i][j] = 2;
          }


          textView.setText("Click a button to start.");


          // add the click listeners for each button
          for (i = 1; i <= 3; i++) {
               for (j = 1; j <= 3; j++) {
                    b[i][j].setOnClickListener(new MyClickListener(i, j));
                    if(!b[i][j].isEnabled()) {
                         b[i][j].setText(" ");
                         b[i][j].setEnabled(true);
                    }
               }
          }
     }


     class MyClickListener implements View.OnClickListener {
          int x;
          int y;


          public MyClickListener(int x, int y) {
               this.x = x;
               this.y = y;
          }


          public void onClick(View view) {
               if (b[x][y].isEnabled()) {
                    b[x][y].setEnabled(false);
                    b[x][y].setText("O");
                    c[x][y] = 0;
                    textView.setText("");
                    if (!checkBoard()) {
                         ai.takeTurn();
                    }
               }
          }
     }


     private class AI {
          public void takeTurn() {
          if(c[1][1]==2 &&
                    ((c[1][2]==0 && c[1][3]==0) ||
                     (c[2][2]==0 && c[3][3]==0) ||
                     (c[2][1]==0 && c[3][1]==0))) {
               markSquare(1,1);
          } else if (c[1][2]==2 &&
                    ((c[2][2]==0 && c[3][2]==0) ||
                     (c[1][1]==0 && c[1][3]==0))) {
               markSquare(1,2);
          } else if(c[1][3]==2 &&
                    ((c[1][1]==0 && c[1][2]==0) ||
                     (c[3][1]==0 && c[2][2]==0) ||
                     (c[2][3]==0 && c[3][3]==0))) {
               markSquare(1,3);
          } else if(c[2][1]==2 &&
                    ((c[2][2]==0 && c[2][3]==0) ||
                     (c[1][1]==0 && c[3][1]==0))){
               markSquare(2,1);
          } else if(c[2][2]==2 &&
                    ((c[1][1]==0 && c[3][3]==0) ||
                     (c[1][2]==0 && c[3][2]==0) ||
                     (c[3][1]==0 && c[1][3]==0) ||
                     (c[2][1]==0 && c[2][3]==0))) {
               markSquare(2,2);
          } else if(c[2][3]==2 &&
                    ((c[2][1]==0 && c[2][2]==0) ||
                     (c[1][3]==0 && c[3][3]==0))) {
               markSquare(2,3);
          } else if(c[3][1]==2 &&
                    ((c[1][1]==0 && c[2][1]==0) ||
                     (c[3][2]==0 && c[3][3]==0) ||
                     (c[2][2]==0 && c[1][3]==0))){
               markSquare(3,1);
          } else if(c[3][2]==2 &&
                    ((c[1][2]==0 && c[2][2]==0) ||
                     (c[3][1]==0 && c[3][3]==0))) {
               markSquare(3,2);
          }else if( c[3][3]==2 &&
                    ((c[1][1]==0 && c[2][2]==0) ||
                     (c[1][3]==0 && c[2][3]==0) ||
                     (c[3][1]==0 && c[3][2]==0))) {
               markSquare(3,3);
          } else {
               Random rand = new Random();
              
               int a = rand.nextInt(4);
               int b = rand.nextInt(4);
               while(a==0 || b==0 || c[a][b]!=2) {
                    a = rand.nextInt(4);
                    b = rand.nextInt(4);
               }
               markSquare(a,b);
          }
     }


          private void markSquare(int x, int y) {
               b[x][y].setEnabled(false);
               b[x][y].setText("X");
               c[x][y] = 1;
               checkBoard();
          }
     }


     // check the board to see if someone has won
     private boolean checkBoard() {
          boolean gameOver = false;
          if ((c[1][1] == 0 && c[2][2] == 0 && c[3][3] == 0)
                    || (c[1][3] == 0 && c[2][2] == 0 && c[3][1] == 0)
                    || (c[1][2] == 0 && c[2][2] == 0 && c[3][2] == 0)
                    || (c[1][3] == 0 && c[2][3] == 0 && c[3][3] == 0)
                    || (c[1][1] == 0 && c[1][2] == 0 && c[1][3] == 0)
                    || (c[2][1] == 0 && c[2][2] == 0 && c[2][3] == 0)
                    || (c[3][1] == 0 && c[3][2] == 0 && c[3][3] == 0)
                    || (c[1][1] == 0 && c[2][1] == 0 && c[3][1] == 0)) {
               textView.setText("Game over. You win!");
               gameOver = true;
          } else if ((c[1][1] == 1 && c[2][2] == 1 && c[3][3] == 1)
                    || (c[1][3] == 1 && c[2][2] == 1 && c[3][1] == 1)
                    || (c[1][2] == 1 && c[2][2] == 1 && c[3][2] == 1)
                    || (c[1][3] == 1 && c[2][3] == 1 && c[3][3] == 1)
                    || (c[1][1] == 1 && c[1][2] == 1 && c[1][3] == 1)
                    || (c[2][1] == 1 && c[2][2] == 1 && c[2][3] == 1)
                    || (c[3][1] == 1 && c[3][2] == 1 && c[3][3] == 1)
                    || (c[1][1] == 1 && c[2][1] == 1 && c[3][1] == 1)) {
               textView.setText("Game over. You lost!");
               gameOver = true;
          } else {
               boolean empty = false;
               for(i=1; i<=3; i++) {
                    for(j=1; j<=3; j++) {
                         if(c[i][j]==2) {
                              empty = true;
                              break;
                         }
                    }
               }
               if(!empty) {
                    gameOver = true;
                    textView.setText("Game over. It's a draw!");
               }
          }
          return gameOver;
     }
}







75 comments:

  1. Thats such a useful article and code for newcomers like me. Delighted :) thanks!!

    ReplyDelete
  2. hi, why do i get an error on (R.id.xxx)?
    the error says that R.id cannot be resolved.

    the quickfix doesnt help either.

    could you please help me?
    thanks

    ReplyDelete
    Replies
    1. just type their your own xml file name

      Delete
    2. check the package name of activity and rebuild it automatically it will solve

      Delete
    3. in place of xxx type your xml file name like R.id.activity_main

      Delete
    4. This comment has been removed by the author.

      Delete
    5. How am I supposed to do it? It'd be helpful of you if you'd cite clear examples of doing that.
      Hope that'll help me as well as others too!!

      Delete
    6. BTW I got it fixed thanks...
      I just keyed in naeen sing's response.
      I think it should do :)

      Delete
    7. Where to write my xml file name? Rather it is creating an interface for R. and object layout is set to NULL

      Delete
  3. is there something that needs to be added in the main.xml? do the buttons need to be defined?
    please, any help would be greatly appreciated

    ReplyDelete
  4. Thanks for updating me. I have just posted the code for main.xml file.You need to put it in your layout folder in res folder.

    ReplyDelete
  5. Thank you so much for the quick response maqsood,
    by the way i love your tutorial.
    as a side note, you email on your profile page is deactivated the daemon says :)
    1000 Thanks for the update

    ReplyDelete
  6. hi...
    when i declare the setBoard() in onCreate function the apps encountered an error..

    ReplyDelete
  7. hi man,
    nice to said that you find the code, but it should be cool to give the name of the developer or the url to find the source : Jason Houle @ http://www.intelliproject.net/articles/showArticle/index/Android_TicTacToe#
    @+Mat

    ReplyDelete
  8. A simpler and better UI :-) http://nabinkhadka.hubpages.com/hub/tictactoe

    ReplyDelete
  9. Can you implement the same using min max algorithm plz

    ReplyDelete
  10. This is only for 3x3 game. What if i want to make it generalised like 6x6 or 8x8 then what will you do?

    ReplyDelete
  11. tic tac toe with admob here free
    http://trickileaks.blogspot.com/2016/04/tic-tac-toe-for-android-source-code.html

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. How can I implement the same using Grid Layout? I am making this game as my android project, will it be okay to choose a very simple game?

    ReplyDelete
  14. How to make this a 2 player game where each player take turns ?

    ReplyDelete
  15. How to make this a 2 player game where each player take turns ?

    ReplyDelete
  16. How can i implement this program in android studio ? I mean where to put all the code. In different java activity file or single one ? Please help me out. Thank you.

    ReplyDelete
    Replies
    1. u can put your code in single java file. It will be work

      Delete
  17. best and simple code ever just copy paste and there you go ...thanks

    ReplyDelete
  18. can you please tell me what changes i need to do in case of double player.

    ReplyDelete
  19. this line:
    public class TicTacToe extends Activity {
    is causing an error! Could you possibly tell me why an error might come up?
    android studio suugests that it shoul be declared under TicTacToe.java



    please help!!

    ReplyDelete
    Replies
    1. also refer this link: http://stackoverflow.com/questions/42211119/android-studio-for-a-tic-tac-toe-game

      Delete
    2. Huh? Thanks?? I think you just missed the last query of mine! Please try to solve that problem for me and for others who may probably find the same problem!

      Delete
  20. awesome blog to read.. i gathered more useful information..

    android training and placements

    ReplyDelete
  21. is there any way to restart the game after if any player wins the game

    ReplyDelete
  22. When give the android projects, you can seek for Assistance With Science Homework and have the privilege of having professional assistance. Actually, accessibility to the professional software services has given the developers a chance to have easy development experience. When I continually read such information, I get a lot of motivation.

    ReplyDelete
  23. In my code its showing error on alphabet b and c.. how to resolve it?

    ReplyDelete
  24. Extremely interesting! Much obliged additionally to share the blog. Extremely helpful to comprehend the impact of Android Training & Placement in Ahmedabad.

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Thanks for such a knowledgeable post.We provide Best Android Training in India.
    please visit:

    ReplyDelete
  29. This is very informative blog check it once through Android Online Training Bangalore for more information on android development.

    ReplyDelete
  30. When I try to run it on my cellphone it won't work.. how to fix it?

    ReplyDelete
  31. Thanks for Sharing this information about Android i like this I can share this in with my Friend Circle.
    Android Training

    ReplyDelete
  32. Thank you for sharing this article, it is very easy to understand and informative. Excellent!

    Mobile App Developer

    ReplyDelete
  33. Thanks for sharing this valuable post with us.
    Android Training in Noida

    ReplyDelete
  34. thanks for this code it is nice code for develop the game it is very helpful

    ReplyDelete
  35. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 


    java training in marathahalli | java training in btm layout

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    selenium training in chennai

    ReplyDelete
  36. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  37. I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favourites blog site list and will be checking back soon.
    python training in pune
    python online training
    python training in OMR

    ReplyDelete
  38. This looks absolutely perfect. All these tiny details are made with lot of background knowledge. I like it a lot. 
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ReplyDelete

  39. I just want to say thank you for sharing this post, it was really awesome and very informative. Thank you
    If anyone searching for Android training certification in India. Join u

    ReplyDelete
  40. UiPath Training in Bangalore by myTectra is one the best UiPath Training. myTectra is the market leader in providing Robotic Process Automation on UiPath
    ui path training in bangalore

    ReplyDelete
  41. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    ReplyDelete
  42. This comment has been removed by the author.

    ReplyDelete
  43. I would like to thank you for your nicely written post, its informative and your writing style encouraged me to read it till end. Thanks

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  44. how the takeTurn() methode works? and what is its purpose

    ReplyDelete
  45. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.


    Best PHP Training Institute in Chennai|PHP Course in chennai

    Best .Net Training Institute in Chennai

    Software Testing Training in Chennai
    Blue Prism Training in Chennai
    Angularjs Training in Chennai

    ReplyDelete
  46. Really very happy to say, your post is very interesting to read. I never stop myself to say something about it. You’re doing a great job. Keep it up…

    Learn Best Informatica Training in Bangalore from Experts. Softgen Infotech offers the Best Informatica Training in Bangalore.100% Placement Assistance, Live Classroom Sessions, Only Technical Profiles, 24x7 Lab Infrastructure Support.

    ReplyDelete
  47. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    Artificial Intelligence Certification Training
    Java Certification Training
    AWS Certification Training
    Machine Learning Certification Training
    Data Science Certification Training
    DevOps Certification Training

    ReplyDelete
  48. Get Big Data Certification in Chennai for making your career as a shining sun with Infycle Technologies. Infycle Technologies is the best Big Data training institute in Chennai, providing complete hands-on practical training of professional specialists in the field. In addition to that, it also offers numerous programming language tutors in the software industry such as Oracle, Java, Python, AWS, Hadoop, etc. Once after the training, interviews will be arranged for the candidates, so that, they can set their career without any struggle. Of all that, 200% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.Big Data Training Institute in Chennai | Infycle Technologies

    ReplyDelete
  49. PYTHON COURSE IN CHENNAI | INFYCLE TECHNOLOGIES:

    Infycle Technologies is the best Python training in Chennai organization in Chennai and is widely known for its outstanding performance in providing the best software training in Chennai. It is the ultimate goal of Infycle Technologies to provide high-quality software programming training in a 100% safe location and to build a solid career for every individual and young professional in the IT industry. Most importantly, students like 100% hands-on training, which is the specialty of Infycle Technologies. To continue your career on a solid foundation, please contact Infycle Technologies at 7502633633.


    Python course with job placements

    ReplyDelete
  50. If Java Development is a field that you're dreaming of, then we, Infycle, are with you to make your dream into reality. Infycle Technologies offers the best Java Training in Chennai, with various highly demanded software courses such as Big Data, AWS, Python, Hadoop, AWS, etc., in 100% practical training with specialized tutors in the field. Along with that, the pre-interviews will be given for the candidates to face the interviews with complete knowledge. To know more, dial 7502633633 for more.

    Best software training in chennai

    ReplyDelete
  51. Infycle Technologies, the best software training institute in Chennai offers the No.1 Python Certification in Chennai for tech professionals. Apart from the Python Course, other courses such as Oracle, Java, Hadoop, Selenium, Android, and iOS Development, Big Data will also be trained with 100% hands-on training. After the completion of training, the students will be sent for placement interviews in the core MNC's. Dial 7502633633 to get more info and a free demo.

    ReplyDelete