You are on page 1of 18

************************************************************************

Name: Deepak Sharma


Roll No:BE 64
Assignment Title:Implementation of MiniMax approach for TIC-TAC-TOE using Java/
Scala/ Python-Eclipse Use GUI Player X and Player O are using their mobiles for the play.
Refresh the screen after the move for both the players.
******************************************************************
ClentActivity.java
package com.example.NaughtsAndCrosses;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";

private boolean connected = false;


private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
new Handler().post(new ClientThread());
/* Thread cThread = new Thread(new ClientThread());
cThread.start();*/
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {

InetAddress serverAddr = InetAddress.getByName(serverIpAddress);


Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket
.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
MainActivity.java
package com.example.NaughtsAndCrosses;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends Activity {


// Representing the game state:
private boolean noughtsTurn = false; // Who's turn is it? false=X true=O
private char board[][] = new char[3][3]; // for now we will represent the board as an
array of characters
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupOnClickListeners();
resetButtons();
}
/**
* Called when you press new game.
*
* @param view the New Game Button
*/
public void newGame(View view) {
noughtsTurn = false;
board = new char[3][3];
resetButtons();
}

/**
* Reset each button in the grid to be blank and enabled.
*/
private void resetButtons() {
TableLayout T = (TableLayout) findViewById(R.id.tableLayout);
for (int y = 0; y < T.getChildCount(); y++) {
if (T.getChildAt(y) instanceof TableRow) {
TableRow R = (TableRow) T.getChildAt(y);
for (int x = 0; x < R.getChildCount(); x++) {
if (R.getChildAt(x) instanceof Button) {
Button B = (Button) R.getChildAt(x);
B.setText("");
B.setEnabled(true);
}
}
}
}
TextView t = (TextView) findViewById(R.id.titleText);
t.setText(R.string.app_name);
}
/**
* Method that returns true when someone has won and false when nobody has.<br />
* It also display the winner on screen.
*
* @return
*/
private boolean checkWin() {
char winner = '\0';
if (checkWinner(board, 3, 'X')) {
winner = 'X';
} else if (checkWinner(board, 3, 'O')) {
winner = 'O';

}
if (winner == '\0') {
return false; // nobody won
} else {
// display winner
TextView T = (TextView) findViewById(R.id.titleText);
T.setText(winner + " wins");
return true;
}
}
/**
* This is a generic algorithm for checking if a specific player has won on a tic tac toe
board of any size.
*
* @param board the board itself
* @param size the width and height of the board
* @param player the player, 'X' or 'O'
* @return true if the specified player has won
*/
private boolean checkWinner(char[][] board, int size, char player) {
// check each column
for (int x = 0; x < size; x++) {
int total = 0;
for (int y = 0; y < size; y++) {
if (board[x][y] == player) {
total++;
}
}
if (total >= size) {
return true; // they win
}
}

// check each row


for (int y = 0; y < size; y++) {
int total = 0;
for (int x = 0; x < size; x++) {
if (board[x][y] == player) {
total++;
}
}
if (total >= size) {
return true; // they win
}
}
// forward diag
int total = 0;
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
if (x == y && board[x][y] == player) {
total++;
}
}
}
if (total >= size) {
return true; // they win
}
// backward diag
total = 0;
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
if (x + y == size - 1 && board[x][y] == player) {
total++;
}

}
}
if (total >= size) {
return true; // they win
}
return false; // nobody won
}
/**
* Disables all the buttons in the grid.
*/
private void disableButtons() {
TableLayout T = (TableLayout) findViewById(R.id.tableLayout);
for (int y = 0; y < T.getChildCount(); y++) {
if (T.getChildAt(y) instanceof TableRow) {
TableRow R = (TableRow) T.getChildAt(y);
for (int x = 0; x < R.getChildCount(); x++) {
if (R.getChildAt(x) instanceof Button) {
Button B = (Button) R.getChildAt(x);
B.setEnabled(false);
}
}
}
}
}
/**
* This will add the OnClickListener to each button inside out TableLayout
*/
private void setupOnClickListeners() {
TableLayout T = (TableLayout) findViewById(R.id.tableLayout);
for (int y = 0; y < T.getChildCount(); y++) {

if (T.getChildAt(y) instanceof TableRow) {


TableRow R = (TableRow) T.getChildAt(y);
for (int x = 0; x < R.getChildCount(); x++) {
View V = R.getChildAt(x); // In our case this will be
each button on the grid
V.setOnClickListener(new PlayOnClick(x, y));
}
}
}
}
/**
* Custom OnClickListener for Noughts and Crosses<br />
* Each Button for Noughts and Crosses has a position we need to take into account
*
* @author Lyndon Armitage
*/
private class PlayOnClick implements View.OnClickListener {
private int x = 0;
private int y = 0;
public PlayOnClick(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void onClick(View view) {
if (view instanceof Button) {
Button B = (Button) view;
board[x][y] = noughtsTurn ? 'O' : 'X';
B.setText(noughtsTurn ? "O" : "X");
B.setEnabled(false);

noughtsTurn = !noughtsTurn;
// check if anyone has won
if (checkWin()) {
disableButtons();
}
}
}
}
}
ServerActivity.java
package com.example.NaughtsAndCrosses;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class ServerActivity extends Activity {
private TextView serverStatus;

// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
new Handler().post(new ServerThread());
/*

Thread fst = new Thread(new ServerThread());


fst.start();*/

}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {

// LISTEN FOR INCOMING CLIENTS


Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
@Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect
your phones.");
}
});
e.printStackTrace();
}

}
} else {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return
inetAddress.getHostAddress().toString(); }
}
}

} catch (SocketException ex) {


Log.e("ServerActivity", ex.toString());
}
return null;
}
@Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/server_ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Server IP" >
</EditText>
<Button
android:id="@+id/connect_phones"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect" />

</LinearLayout>
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:orientation="vertical" >
<Button
android:id="@+id/newGameBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_gravity="center_horizontal"
android:onClick="newGame"
android:text="New Game"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TableLayout
android:id="@+id/tableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/topLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />

<Button
android:id="@+id/topRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="3"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="3"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button

android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="3"
android:height="100dp"
android:text="O"
android:textAppearance="?android:attr/textAppearanceLarge"
android:width="100dp" />
</TableRow>
</TableLayout>
<TextView
android:id="@+id/titleText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/black" />
</LinearLayout>
Server.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/server_status"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
***************************************************************************
***

Output:

You might also like