TicTacToe Game Implementation

The project describes how to use 2D graphics and draw TicTacToe board.

Underlying Algorithm:

Basic description of algorithm in step by step form:

1.) Create a Project TicTacToe

2.) Add some images into your drawable folder for drawing cross and ball image.

3.) Run the application.

Steps to Create:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. TicTacToe. Enter following information:

Project name: TicTacToe
Build Target: Android 2.3.3
Application name: TicTacToe
Package name: org.example.TicTacToe
Create Activity: TicTacToe

On Clicking Finish TicTacToe code structure is generated with the necessary Android Packages being imported along with TicTacToe.java. TicTacToe class will look like following:

 

package org.example.TicTacToe;

import android.app.Activity;
import android.os.Bundle;

public class TicTacToe extends Activity {
private Game game1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
game1 = new Game(this);
setContentView(game1);
}
}

 

 

 

package org.example.TicTacToe;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class Ball extends Cell {

public Ball(int x, int y) {
super(x, y);
}

public void draw(Canvas g, Resources res, int x, int y, int w, int h) {
Bitmap im = BitmapFactory.decodeResource(res, R.drawable.bola);
g.drawBitmap(im, null, new Rect(x*w, y*h, (x*w)+w, (y*h)+h), new Paint());
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Ball) {
return true;
} else {
return false;
}
}

@Override
public String toString() {
return "O";
}
}

 

 

 

package org.example.TicTacToe;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class Game extends View {

private Cell[][] singlesquare = null;
int x = 3;
int y = 3;
private int l;
private int a;
private boolean whatdrawn = false;
private int playerwin = 3;
private Paint caneta;

Handler handler = new Handler() {
// @Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
invalidate();
break;
case 1:
Toast.makeText(getContext(), "You Win!", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getContext(), "Computer Win!", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getContext(), "Loose!", Toast.LENGTH_SHORT).show();
break;
default:
break;
}

super.handleMessage(msg);
}
};

public int getGameSize() {
return x;
}

public Game(Context context) {
super(context);

caneta = new Paint();

this.caneta.setARGB(255, 0, 0, 0);
this.caneta.setAntiAlias(true);
this.caneta.setStyle(Style.STROKE);
this.caneta.setStrokeWidth(5);

l = this.getWidth();
a = this.getHeight();

singlesquare = new Cell[x][y];

int xss = l / x;
int yss = a / y;

for (int z = 0; z < y; z++) {
for (int i = 0; i < x; i++) {
singlesquare[z][i] = new Empty(xss * i, z * yss);
}
}
}

@Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < singlesquare.length; i++) {
for (int j = 0; j < singlesquare[0].length; j++) {
singlesquare[i][j].draw(canvas, getResources(), j, i, (this
.getWidth() + 3)
/ singlesquare.length, this.getHeight()
/ singlesquare[0].length);
}
}

int xs = this.getWidth() / x;
int ys = this.getHeight() / y;
for (int i = 0; i <= x; i++) {
canvas.drawLine(xs * i, 0, xs * i, this.getHeight(), caneta);
}
for (int i = 0; i <= y; i++) {
canvas.drawLine(0, ys * i, this.getWidth(), ys * i, caneta);
}

super.onDraw(canvas);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
int x_aux = (int) (event.getX() / (this.getWidth() / x));
int y_aux = (int) (event.getY() / (this.getHeight() / y));
drawimage(x_aux, y_aux);
return super.onTouchEvent(event);
}

public String getPiece(int player) {
switch (player) {
case 1:
return "x";
case -1:
return "o";
}
return null;
}

public void drawimage(int x_aux, int y_aux) {
Cell cel = null;
if (whatdrawn)
{
cel = new Cross(singlesquare[x_aux][y_aux].x,singlesquare[x_aux][y_aux].y);
whatdrawn = false;
}
else
{
cel = new Ball(singlesquare[x_aux][y_aux].x, singlesquare[x_aux][y_aux].y);
whatdrawn = true;
}

singlesquare[y_aux][x_aux] = cel;

handler.sendMessage(Message.obtain(handler, 0));

if (validate_game()) {
if (whatdrawn) {
System.out.println("You Win");
handler.sendMessage(Message.obtain(handler, 1));
} else {
System.out.println("Computer Win");
handler.sendMessage(Message.obtain(handler, 2));
}
resizegame(x);

} else if (isFull()) {
System.out.println("Loose");
handler.sendMessage(Message.obtain(handler, 3));
resizegame(x);

}
}

private boolean validate_game() {
int contador = 0;
Cell anterior = null;

for (int i = 0; i < singlesquare.length; i++) {
for (int j = 0; j < singlesquare[0].length; j++) {
System.out.print(singlesquare[i][j]);
if (!singlesquare[i][j].equals(anterior)
|| singlesquare[i][j] instanceof Empty) {

anterior = singlesquare[i][j];
contador = 0;
} else {
contador++;
}
if (contador >= getPlayerwin() - 1) {
return true;
}

}
System.out.println("");
anterior = null;
contador = 0;
}

anterior = null;
for (int j = 0; j < singlesquare[0].length; j++) {
for (int i = 0; i < singlesquare.length; i++) {
System.out.print(singlesquare[i][j]);
if (!singlesquare[i][j].equals(anterior)
|| singlesquare[i][j] instanceof Empty) {
anterior = singlesquare[i][j];
contador = 0;
} else {
contador++;
}

if (contador >= getPlayerwin() - 1) {
return true;
}

}
System.out.println("");
anterior = null;
contador = 0;
}

anterior = null;
for (int j = singlesquare[0].length - 1; j >= 0; j--) {
int yau = 0;
for (int z = j; z < singlesquare[0].length; z++) {
if (!singlesquare[yau][z].equals(anterior)
|| singlesquare[yau][z] instanceof Empty) {
anterior = singlesquare[yau][z];
contador = 0;
} else {
contador++;
}

if (contador >= getPlayerwin() - 1) {
return true;
}
yau++;
}
contador = 0;
anterior = null;
}

anterior = null;
for (int j = 0; j < singlesquare[0].length; j++) {
int yau = 0;
for (int z = j; z >= 0; z--) {
if (!singlesquare[yau][z].equals(anterior)
|| singlesquare[yau][z] instanceof Empty) {
anterior = singlesquare[yau][z];
contador = 0;
} else {
contador++;
}

if (contador >= getPlayerwin() - 1) {
return true;
}

yau++;
}
contador = 0;
anterior = null;
}
return false;
}

public boolean isFull() {
for (int i = 0; i < singlesquare.length; i++) {
for (int j = 0; j < singlesquare[0].length; j++) {
if (singlesquare[i][j] instanceof Empty) {
return false;
}
}
}
return true;
}

public void resizegame(int s) {
x = s;
y = s;

singlesquare = new Cell[x][y];

int xss = l / x;
int yss = a / y;

for (int z = 0; z < y; z++) {
for (int i = 0; i < x; i++) {
singlesquare[z][i] = new Empty(xss * i, z * yss);
}
}
handler.sendMessage(Message.obtain(handler, 0));
}

public int getPlayerwin() {
return playerwin;
}
}

 

 

 

package org.example.TicTacToe;

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Point;

public abstract class Cell extends Point {

public Cell(int x, int y) {
super(x, y);
}

abstract public void draw(Canvas g,Resources res, int x, int y, int w, int h);
}

 

 

 

package org.example.TicTacToe;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class Empty extends Cell {

public Empty(int x, int y) {
super(x, y);
}

public void draw(Canvas g, Resources res, int x, int y, int w, int h) {
Bitmap im = BitmapFactory.decodeResource(res, R.drawable.vazio);
g.drawBitmap(im, null, new Rect(x*w, y*h, (x*w)+w, (y*h)+h), new Paint());
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Empty) {
return true;
} else {
return false;
}
}
@Override
public String toString() {
return " ";
}
}

 

 

 

package org.example.TicTacToe;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class Cross extends Cell {

public Cross(int x, int y) {
super(x, y);
}

public void draw(Canvas g, Resources res, int x, int y, int w, int h) {
Bitmap im = BitmapFactory.decodeResource(res, R.drawable.cruz);
g.drawBitmap(im, null, new Rect(x*w, y*h, (x*w)+w, (y*h)+h), new Paint());
}

@Override
public boolean equals(Object obj) {
if (obj instanceof Cross) {
return true;
} else {
return false;
}
}

@Override
public String toString() {
return "X";
}
}

 

 

Output – The final output:

Use following images as your resource:

1.)

2.)

3.)

Leave a Comment:

45 comments
Prashant Kumar says June 20, 2011

Nice article!!
But please let me know about “Vazio” and “Cruz”.
I assume they are the names of the images, but what kind of images are they??

Regards,

Reply
Prashant Kumar says June 20, 2011

Nice article!!
But please let me know about "Vazio" and "Cruz".
I assume they are the names of the images, but what kind of images are they??

Regards,

Reply
Sushant says June 20, 2011

Yes,

vazio, cruz and bola these are names of images only. these all are .jpg images which you have to put in res/drawable (drawable-hdpi, drawable-mdpi and drawable-ldpi) folder.

You can put the images of u r choice to change the look of tictactoe. Don’t forget to change these names into the code.

Thanks.

Reply
Prashant Kumar says June 20, 2011

Hi Sushant,
Thanks for your prompt reply..

This code has no problem in execution but, when yoiu click on the one of the rectangles(“Vazio image”). It gives the error..
Activity TicTacToe(in application TicTacToe) is not responding.

Reply
Sushant says June 20, 2011

I run the same and found no error. I have attached the images i am using to the post for you. Please try with those once.

Thanks.

Reply
sheetal says August 15, 2011

Hello sushant,
M doing a project in android named ‘Barcode Scanner’. But how to determine the cost from the barcode image captured?

Reply
Sachin says October 31, 2011

Hi Sushant,

I run this application , there is error show-“sorry ,The application Tic Tac Toe(process org.example.TicTacToe) has stopped unexpectedly. Please try again”

Thanks

Reply
Sachin says October 31, 2011

Hi Sushant,

I run this application , there is error show-"sorry ,The application Tic Tac Toe(process org.example.TicTacToe) has stopped unexpectedly. Please try again"

Thanks

Reply
Sachin says October 31, 2011

Hi Sushant,

what about main.xml and string.xml

Thanks & Regards

Reply
Sachin Gupta says November 2, 2011

Hi Sushant,

Developing this application , what about main.xml what we do in this XML, please suggest.

Thanks Sachin

Reply
ritesh says November 9, 2011

In this code I found Lots Of errors……like You click on same box or cell your choice changed but its not right……….

Reply
Dan says November 17, 2011

When I was looking through the code in the game class, in 2 of the for loops i saw:
for (int z = j; z >= 0; z–)
shouldnt the “z-” be z++ because this produces an error?

Reply
compgeek245 says November 29, 2011

This was an awesome code. It helped me out a ton!! Thanks Sushant! But I had the same problem and I used your attached images. What could possibly be wrong?

Reply
Jelle says January 10, 2012

It doesn’t say where to make a class or anything… I’m trying to make a TicTacToe game but this isn’t really a step by step tutorial.

Reply
rizal says January 17, 2012

i’m very nebie in programing….

how about main.xml???
how the sorce code??
please help me….

Reply
enss says February 3, 2012

This article is very simple and easy to understand. Thanks a lot for this valuable article. 🙂

Reply
enss says February 3, 2012

Hii.. Your article looks very interesting, but apparently it have not been able to play against the computer. So I have added AI in your code, so it could play with computer. I just added some functions in Game.java here is the code : http://ideone.com/KgXvG
I think my code is not completely perfect, but I hope you are pleased. 🙂

Reply
vinod says February 8, 2012

when we click on the same cell twice, the same cell is over written… pls solve this problem soon

Reply
vinod says February 8, 2012

when we click on the same cell twice, the same cell is over written… pls solve this problem soon … pls solve dis

Reply
vinod says February 8, 2012

when we click on the same cell twice, the same cell is over written… pls solve this problem soon .. pls solve

Reply
PerfectReign says February 27, 2012

Nice article. I also am not able to load anything. I run the code in the android emulator and the grid comes up but no images.

I also ran this on my phone and same thing.

I then created my own jpg images for bola, cruz and vazio. No luck there either.

Reply
WorldOrder says March 8, 2012

the codes give no error, when i start the app it will run but i only see a black page. the game layout dont show..

can you help plz? i have put the images you provided in the post in the drawable folder

thanks

Reply
WorldOrder says March 8, 2012

the codes give no error, when i start the app it will run but i only see a black page. the game layout dont show..

can you help plz? i have put the images you provided in the post in the drawable folder

thanks!

Reply
Zeeshan says March 25, 2012

Give 16 errors…..

Reply
Jane says April 2, 2012

Hi please can I get comments to each of code or a tut. video explaining what each lines are for?

Reply
Nazeem says May 2, 2012

Hi Sushant,

This is really great article easy to follow but I am getting the same error whenever I click on the rectangles (Vazio image)

“Activity TicTacToe(in application TicTacToe) is not responding”

Reply
Nazeem says May 2, 2012

Hi Sushant,

This is really great article easy to follow but I am getting the same error whenever I click on the rectangles (Vazio image)

"Activity TicTacToe(in application TicTacToe) is not responding"

Reply
mohamad says May 30, 2012

hey bro i tried this but when i go into the games it crash

Reply
willy says August 2, 2012

Can we play against computer instead of human vs human?

Reply
willy says August 2, 2012

Hi,

The game is amazing but i got some question to ask.

Can we play against computer instead of human vs human?

Reply
jamie says August 2, 2012

Hi,

This game is amazing

I would like to know whether we can play against the computer instead of playing against human.

Appreciate it.

Reply
Jaydeep says August 11, 2012

 which images are used?

Reply
Mudit Srivastava1387 says August 14, 2012

the images are not diplaying in the game
 

Reply
vandana says September 3, 2012

its showing oly tat vazio image not getting remaining outputs

Reply
ruby says September 23, 2012

Can i have the code for main.xml

Reply
ponce says December 8, 2012

hey,,,,my friend gave to me tic tac toe full project. can you help me something about this project? I will share this project,,please help. I want to object X and O is limited to each object 3 pieces. so there are only X = 3 and O = 3, not more, so that the object can slide because there are 3 columns blank, can u do it???
this is my email :
yogapraditagames@gmail.com

Reply
curious says January 20, 2013

Hi Sushant,
Is vazio the ‘x’ and cruz the ‘o’ pictures respectively?

Reply
rizwan says January 23, 2013

Hi,

Can you please share the XML file for above code?? It will be more helpful.

Thank you,
regards,
Rizwan

Reply
phen sophat says March 9, 2013

can you tell me about R.drawable.vazio?what vazio?

Reply
Aniket Nandanwar says March 28, 2013

hey which code goes where?
i am a learner trying to get into my first app so dont have much idea…i hope you would guide…:)
hoping for as soon reply…

Reply
saide says September 24, 2013

create

Reply
saide says September 24, 2013

you may create two player using bluetooth?

Reply
vicky S raj says October 21, 2013

cruz, bola cruz are the images and image type which used is .png

Reply
AndroidLover says February 22, 2015

Could some one tell how to place these codes? do we just copy and past it to the TicTacToe.java file? can some one give step by step instructions?

Thanks

Reply
Nabin Khadka says July 19, 2015

I have similar implementation here. Please comment on that. Thank you

http://nabinkhadka.hubpages.com/hub/tictactoe

Reply
Add Your Reply