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>
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;
}
}
Thats such a useful article and code for newcomers like me. Delighted :) thanks!!
ReplyDeleteI significantly appreciate this!
ReplyDeletehi, why do i get an error on (R.id.xxx)?
ReplyDeletethe error says that R.id cannot be resolved.
the quickfix doesnt help either.
could you please help me?
thanks
just type their your own xml file name
Deletecheck the package name of activity and rebuild it automatically it will solve
Deletein place of xxx type your xml file name like R.id.activity_main
DeleteThis comment has been removed by the author.
DeleteHow am I supposed to do it? It'd be helpful of you if you'd cite clear examples of doing that.
DeleteHope that'll help me as well as others too!!
BTW I got it fixed thanks...
DeleteI just keyed in naeen sing's response.
I think it should do :)
Where to write my xml file name? Rather it is creating an interface for R. and object layout is set to NULL
Deleteis there something that needs to be added in the main.xml? do the buttons need to be defined?
ReplyDeleteplease, any help would be greatly appreciated
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.
ReplyDeleteThank you so much for the quick response maqsood,
ReplyDeleteby 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
hi...
ReplyDeletewhen i declare the setBoard() in onCreate function the apps encountered an error..
hi man,
ReplyDeletenice 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
A simpler and better UI :-) http://nabinkhadka.hubpages.com/hub/tictactoe
ReplyDeleteCan you implement the same using min max algorithm plz
ReplyDeleteThis is only for 3x3 game. What if i want to make it generalised like 6x6 or 8x8 then what will you do?
ReplyDeletetic tac toe with admob here free
ReplyDeletehttp://trickileaks.blogspot.com/2016/04/tic-tac-toe-for-android-source-code.html
This comment has been removed by the author.
ReplyDeleteHow 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?
ReplyDeleteHow to make this a 2 player game where each player take turns ?
ReplyDeleteHow to make this a 2 player game where each player take turns ?
ReplyDeleteHow 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.
ReplyDeleteu can put your code in single java file. It will be work
Deletebest and simple code ever just copy paste and there you go ...thanks
ReplyDeletecan you please tell me what changes i need to do in case of double player.
ReplyDeletethis line:
ReplyDeletepublic 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!!
also refer this link: http://stackoverflow.com/questions/42211119/android-studio-for-a-tic-tac-toe-game
DeleteThanks Raj.
DeleteHuh? 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!
Deleteawesome blog to read.. i gathered more useful information..
ReplyDeleteandroid training and placements
is there any way to restart the game after if any player wins the game
ReplyDeleteWhen 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.
ReplyDeleteIn my code its showing error on alphabet b and c.. how to resolve it?
ReplyDeleteExtremely interesting! Much obliged additionally to share the blog. Extremely helpful to comprehend the impact of Android Training & Placement in Ahmedabad.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThanks for such a knowledgeable post.We provide Best Android Training in India.
ReplyDeleteplease visit:
This is very informative blog check it once through Android Online Training Bangalore for more information on android development.
ReplyDeleteWhen I try to run it on my cellphone it won't work.. how to fix it?
ReplyDeleteThanks for Sharing this information about Android i like this I can share this in with my Friend Circle.
ReplyDeleteAndroid Training
Thank you for sharing this article, it is very easy to understand and informative. Excellent!
ReplyDeleteMobile App Developer
Nice Bog! Thank you for sharing the valuable information.
ReplyDeleteapple ios training institutes in Hyderabad
iphone app training course
Thanks for sharing this valuable post with us.
ReplyDeleteAndroid Training in Noida
thanks for this code it is nice code for develop the game it is very helpful
ReplyDeleteThis blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
ReplyDeleterpa Training in annanagar
blue prism Training in annanagar
automation anywhere Training in annanagar
iot Training in annanagar
rpa Training in marathahalli
blue prism Training in marathahalli
automation anywhere Training in marathahalli
blue prism training in jayanagar
automation anywhere training in jayanagar
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeleteData Science training in marathahalli
Data Science training in btm
Data Science training in rajaji nagar
Data Science training in chennai
Data Science training in kalyan nagar
Data Science training in electronic city
Data Science training in USA
Data science training in pune
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.
ReplyDeletejava 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
Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
ReplyDeletejava training in tambaram | java training in velachery
java training in omr | oracle training in chennai
java training in annanagar | java training in chennai
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.
ReplyDeletepython training in pune
python online training
python training in OMR
This looks absolutely perfect. All these tiny details are made with lot of background knowledge. I like it a lot.
ReplyDeleteBlueprism training in tambaram
Blueprism training in annanagar
Blueprism training in velachery
ReplyDeleteI 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
UiPath Training in Bangalore by myTectra is one the best UiPath Training. myTectra is the market leader in providing Robotic Process Automation on UiPath
ReplyDeleteui path training in bangalore
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.
ReplyDeleteangularjs Training in bangalore
angularjs Training in btm
angularjs Training in electronic-city
angularjs online Training
angularjs Training in marathahalli
This comment has been removed by the author.
ReplyDeleteI would like to thank you for your nicely written post, its informative and your writing style encouraged me to read it till end. Thanks
ReplyDeletedevops online training
aws online training
data science with python online training
data science online training
rpa online training
Well researched article and I appreciate this. The blog is subscribed and will see new topics soon.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Python online training
uipath online training
I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
ReplyDeleteLinux Training in Chennai
Python Training in Chennai
Data Science Training in Chennai
RPA Training in Chennai
Devops Training in Chennai
how the takeTurn() methode works? and what is its purpose
ReplyDeleteYour 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.
ReplyDeleteBest 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
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…
ReplyDeleteLearn 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.
I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article.
ReplyDeleteSalesforce Training | Online Course | Certification in chennai | Salesforce Training | Online Course | Certification in bangalore | Salesforce Training | Online Course | Certification in hyderabad | Salesforce Training | Online Course | Certification in pune
A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.keep it up.
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
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.
ReplyDeleteArtificial Intelligence Certification Training
Java Certification Training
AWS Certification Training
Machine Learning Certification Training
Data Science Certification Training
DevOps Certification Training
Wow!! it is interesting and coding is really cool. Java training in Chennai | Certification | Online Course Training | Java training in Bangalore | Certification | Online Course Training | Java training in Hyderabad | Certification | Online Course Training | Java training in Coimbatore | Certification | Online Course Training | Java training in Online | Certification | Online Course Training
ReplyDeleteGreat post. Thank you for sharing such useful information. Please keep sharing
ReplyDeleteClick Now
Click Now
Click Now
Click Now
Click Now
Click Now
Click Now
Click Now
Click Now
Click Now
ReplyDeleteThanks for sharing
full stack training in delhi
AI training course in Delhi
Power BI Institute in Delhi
tableau training in delhi
SASVBA
GMB
For more information
Annabelle loves to write and has been doing so for many years.Backlink Indexer My GPL Store Teckum-All about Knowledge
ReplyDeleteGet 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
ReplyDeletePYTHON COURSE IN CHENNAI | INFYCLE TECHNOLOGIES:
ReplyDeleteInfycle 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
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.
ReplyDeleteBest software training in chennai
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