Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners I want only one method goes to sleep but both method goes to sleep together

Have Programming Question? Ask it here!
 
 
 


VIkas Gupta
I want only one method goes to sleep but both method goes to sleep together
0 Answer(s)      2 years and 3 months ago
Posted in : Java Beginners


I built a TicTacToe game for android. And i want that there should be some time gap or time difference between User's turn and Computer's turn. Mean i want like a sleep() or any other method should be invoked between User's turn and Computer's turn. But when i call Sleep() before cpuPlay() method or after userPlay() it makes sleep to both user and Android and both wake up together. I really tried very hard to find why it is making sleep() to both method together but i am unable to find. Please help me with this. Thanks in advance. Here's my code

public class Game extends Activity 
  {
    private final int GAME_VICTORY = 0x1;
    private final int GAME_DEFEAT = 0x2;
private final int GAME_TIE = 0x3;
private final int GAME_CONTINUES = 0x4;
private final float UNIQUE_MAX_WEIGHT=0.85f;
static final int ACTIVITY_SELECTION = 1;
private int x_Player_win_counter;
private int o_Player_win_counter;
public static TextView textlevel=null;
public static TextView textlevel1=null;
public double startTime;
double userDuration;
double cpuDuration;
private float[] w;  
private int[] c;        
private int[][] PosTable;   
private Button[] buttons;
private int lineH = -1;
private int lineV = -1;
private int lineD = -1;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    buttons = new Button[9];

    buttons[0] = (Button) findViewById(R.id.Button01);
    buttons[0].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(0);
        }
    });
    buttons[1] = (Button) findViewById(R.id.Button02);
    buttons[1].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(1);
        }
    });
    buttons[2] = (Button) findViewById(R.id.Button03);
    buttons[2].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(2);
        }
    });
    buttons[3] = (Button) findViewById(R.id.Button04);
    buttons[3].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(3);
        }
    });
    buttons[4] = (Button) findViewById(R.id.Button05);
    buttons[4].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(4);
        }
    });
    buttons[5] = (Button) findViewById(R.id.Button06);
    buttons[5].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(5);
        }

    });
    buttons[6] = (Button) findViewById(R.id.Button07);
    buttons[6].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(6);
        }
    });
    buttons[7] = (Button) findViewById(R.id.Button08);
    buttons[7].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(7);
        }
    });
    buttons[8] = (Button) findViewById(R.id.Button09);
    buttons[8].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            btnClicked(8);
        }
    });

  startActivityForResult(new Intent(Game.this, Game.class), ACTIVITY_SELECTION);


    DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
    float h = (float) (dm.heightPixels - (100.0)*dm.density);
    float w = dm.widthPixels;
    for(int i=0;i<9;i++) {
        buttons[i].setHeight((int) (h/3));
        buttons[i].setWidth((int) (w/3));
    }
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    beginPlay();
    if (requestCode == ACTIVITY_SELECTION) {
        if (resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            if (extras.getString("result").equals("CPU")) cpuPlay();
        }
    }
}
public void userGame() {
    new AlertDialog.Builder(this)
    .setTitle("User Won!!!")
    .setMessage("want to start another game")
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {

            buttonsEnable(true);
            beginPlay();
        }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {
            finish();
        }
    })
    .show();        
}

public void cpuGame() {
    new AlertDialog.Builder(this)
    .setTitle("Android Won!!!")
    .setMessage("want to start another game")
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {

            buttonsEnable(true);
            beginPlay();
        }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {
            finish();
        }
    })
    .show();
}

public void tieGame() {
    new AlertDialog.Builder(this)
    .setTitle("TIE!!!")
    .setMessage("want to start another game")
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {

            buttonsEnable(true);
            beginPlay();
        }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {
            finish();
        }
    })
    .show();
}


private void beginPlay() {
    //initializations start 
    w=new float[9];
    c=new int[9];
    InitTable();
    w[0]=0.7f;
    w[1]=0.4f;
    w[2]=0.7f;
    w[3]=0.4f;
    w[4]=0.7f;
    w[5]=0.4f;
    w[6]=0.7f;
    w[7]=0.4f;
    w[8]=0.7f;
    //c[i] : 0 for empty, 1 for cpu, 2 for user
    for(int i=0;i<9;i++)
        c[i]=0;
    //initializations done

    //now we play!


        startTime = System.currentTimeMillis();
        textlevel=(TextView)findViewById(R.id.userInfo);
        textlevel.setText(String.valueOf(x_Player_win_counter));

        textlevel1=(TextView)findViewById(R.id.cpuInfo);
        textlevel1.setText(String.valueOf(o_Player_win_counter));

    for(int i=0;i<9;i++)
        {     
        updateBtn(i);
        buttons[i].setTextColor(Color.BLACK);
        }
    String PlayerName="User";       
    updateGameInfo(PlayerName + " turn.");
}

private void cpuPlay() 
{
    int cpos=getDecision();
    if (cpos == -1) 
    {
        Toast toast = Toast.makeText(getApplicationContext(), "GAME OVER", Toast.LENGTH_SHORT);
        toast.show();
        return;
    } 
    else
    {
    c[cpos]=1;
    updateBtn(cpos);
    String name= "user";
    updateGameInfo(name + " turn");
    int gstatus = CheckGameStatus();
    if (gstatus == GAME_VICTORY) 
    {
        userDuration = (System.currentTimeMillis() - startTime)/1000;
        Toast toast = Toast.makeText(getApplicationContext(), "Congrts You Won in " + userDuration + " seconds", Toast.LENGTH_SHORT);
        toast.show();
        ++x_Player_win_counter;
        userGame();
    }
    else if (gstatus == GAME_DEFEAT) {
        cpuDuration = (System.currentTimeMillis() - startTime)/1000;
        Toast toast = Toast.makeText(getApplicationContext(), "Sorry, Android Won in "  + cpuDuration + " seconds", Toast.LENGTH_SHORT);
        toast.show();
        ++o_Player_win_counter;
        cpuGame();
    }
    else if (gstatus == GAME_TIE) {
        Toast toast = Toast.makeText(getApplicationContext(), "Its a TIE", Toast.LENGTH_SHORT);
        toast.show();
        tieGame();
    }
    else if (gstatus == GAME_CONTINUES) {
        //user plays
    }
    }
}
private void updateBtn(int i) {
    if(c[i]==0)
    {   
        buttons[i].setText(" ");        
    }
    else if(c[i]==1)
    {

        buttons[i].setText("O");
        buttons[i].setTextColor(Color.RED);
    }
    else
    {
        buttons[i].setText("X");            
    }
}

private int CheckGameStatus() {
    int s = 0;
    //check horizontal
    if(c[0]==2&&c[1]==2&&c[2]==2) 
    {
        s = GAME_VICTORY;           
    }
    if(c[3]==2&&c[4]==2&&c[5]==2) 
    {
        s = GAME_VICTORY;           
    }
    if(c[6]==2&&c[7]==2&&c[8]==2) 
    {
        s = GAME_VICTORY;           
    }
    if(c[0]==1&&c[1]==1&&c[2]==1) 
    {
        s = GAME_DEFEAT;            
    }
    if(c[3]==1&&c[4]==1&&c[5]==1) 
    {
        s = GAME_DEFEAT;            
    }
    if(c[6]==1&&c[7]==1&&c[8]==1) 
    {
        s = GAME_DEFEAT;            
    }
    //check vertical
    if(c[0]==2&&c[3]==2&&c[6]==2) 
    {
        s = GAME_VICTORY;           
    }
    if(c[1]==2&&c[4]==2&&c[7]==2) 
    {
        s = GAME_VICTORY;           
    }
    if(c[2]==2&&c[5]==2&&c[8]==2) 
    {
        s = GAME_VICTORY;           
    }
    if(c[0]==1&&c[3]==1&&c[6]==1) 
    {
        s = GAME_DEFEAT;            
    }
    if(c[1]==1&&c[4]==1&&c[7]==1) 
    {
        s = GAME_DEFEAT;
    }
    if(c[2]==1&&c[5]==1&&c[8]==1) 
    {
        s = GAME_DEFEAT;
    }
    //check diagonal
    if(c[0]==2&&c[4]==2&&c[8]==2) {s = GAME_VICTORY;}
    if(c[2]==2&&c[4]==2&&c[6]==2) {s = GAME_VICTORY;}
    if(c[0]==1&&c[4]==1&&c[8]==1) {s = GAME_DEFEAT;}
    if(c[2]==1&&c[4]==1&&c[6]==1) {s = GAME_DEFEAT;}

    if (s != 0) {
        buttonsEnable(false);
        return s;
    }

    boolean box_empty = false;
    for(int i=0;i<9;i++) {
        if (c[i] == 0) box_empty = true;
    }
    if (box_empty) {    //if any box is empty -> game continues
        return GAME_CONTINUES;
    }
    else {  //else there is tie
        buttonsEnable(false);
        return GAME_TIE;
    }
}

private void buttonsEnable(boolean b) {
    for(int i=0;i<9;i++)
        buttons[i].setEnabled(b);
}

private void btnClicked(int i)
{   
    if(c[i]!=0) {
        Toast toast = Toast.makeText(getApplicationContext(), "Position occupied", Toast.LENGTH_SHORT);
        toast.show();
    }
    else 
    {
        //all OK
        c[i] = 2;
        updateBtn(i);       
        String name= "Android";
    //  updateGameInfo(name + " turn");

        int gstatus = CheckGameStatus();
        if (gstatus == GAME_VICTORY) {
            userDuration = (System.currentTimeMillis() - startTime)/1000;
            Toast toast = Toast.makeText(getApplicationContext(), "Congrats You Won in "  + userDuration + " seconds", Toast.LENGTH_SHORT);
            toast.show();
            ++x_Player_win_counter;
            userGame();
        }
        else if (gstatus == GAME_DEFEAT) {
            cpuDuration = (System.currentTimeMillis() - startTime)/1000;
            Toast toast = Toast.makeText(getApplicationContext(), "Sorry, Android Won in "  + cpuDuration + " seconds", Toast.LENGTH_SHORT);
            toast.show();
            ++o_Player_win_counter;
            cpuGame();
        }
        else if (gstatus == GAME_TIE) {
            Toast toast = Toast.makeText(getApplicationContext(), "Its a TIE", Toast.LENGTH_SHORT);
            toast.show();
            tieGame();
        }
        else if (gstatus == GAME_CONTINUES) {   
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cpuPlay();
        }
    }
}

private int getDecision() 
{   
    for(int i=0;i<9;i++)
        for(int j=0;j<9;j++) {
            if(c[i]==1&&c[j]==1)    //place 'o' to win
                if(PosTable[i][j]!=-1)  //if we have 3 in a row
                    if(c[PosTable[i][j]]==0)    //if position is free
                        return PosTable[i][j];
            if(c[i]==2&&c[j]==2)    //place 'o' to prevent user's victory
                if(PosTable[i][j]!=-1)  //if we have 3 in a row
                    if(c[PosTable[i][j]]==0)    //if position is free
                        return PosTable[i][j];
        }

    if(c[0]==1&&c[8]==0) return 8;
    if(c[2]==1&&c[6]==0) return 6;
    if(c[8]==1&&c[0]==0) return 0;
    if(c[6]==1&&c[2]==0) return 2;
    Random r=new Random();
    boolean exist07=false;
    boolean[] free=new boolean[9]; //will hold the free positions
    for(int i=0;i<9;i++)
        free[i]=false;
    for(int i=0;i<9;i++)
        if(c[i]==0) {   //free ??
            free[i]=true;   //add position to free
            if(w[i]==UNIQUE_MAX_WEIGHT) return i;
        }
    //more than 1 positions with same weight
    for(int i=0;i<9;i++)
        if(free[i]) //if position is free
            if(w[i]==0.7f) exist07=true;
    if(exist07)
        for(int i=0;i<9;i++)
            if(free[i]) //if position is free
                if(w[i]==0.4f) free[i]=false;

    int j=0;
    int rn=0;
    int[] tmp;
    for(int i=0;i<9;i++)
        if(free[i]) j++;
    if(j!=0) {
        tmp=new int[j];
        rn=r.nextInt(j);
        j=0;
        for(int i=0;i<9;i++)
            if(free[i]) tmp[j++]=i;
        return tmp[rn];
    }
    else {
        return -1; //else GAME OVER
    }
}
private void InitTable() {

    PosTable=new int[9][9];
    for(int i=0;i<9;i++)
        for(int j=0;j<9;j++)
            PosTable[i][j]=-1;
    PosTable[0][1]=2;
    PosTable[0][2]=1;
    PosTable[0][3]=6;
    PosTable[0][4]=8;
    PosTable[0][6]=3;
    PosTable[0][8]=4;
    PosTable[1][2]=0;
    PosTable[1][4]=7;
    PosTable[1][7]=4;
    PosTable[2][4]=6;
    PosTable[2][5]=8;
    PosTable[2][6]=4;
    PosTable[2][8]=5;
    PosTable[3][4]=5;
    PosTable[3][5]=4;
    PosTable[3][6]=0;
    PosTable[4][5]=3;
    PosTable[4][6]=2;
    PosTable[4][7]=1;
    PosTable[4][8]=0;
    PosTable[5][8]=2;
    PosTable[6][7]=8;
    PosTable[6][8]=7;
    PosTable[7][8]=6;
}

private void updateGameInfo(String info)
{
    Toast.makeText(this, info, Toast.LENGTH_SHORT).show();
    TextView infoView =(TextView) findViewById(R.id.gameInfo);
    infoView.setText(info);
}

Advertisement
View Answers

Related Tutorials/Questions & Answers:
I want only one method goes to sleep but both method goes to sleep together
I want only one method goes to sleep but both method goes to sleep... userPlay() it makes sleep to both user and Android and both wake up together. I really tried very hard to find why it is making sleep() to both method together but i
I want only one method goes to sleep but both method goes to sleep together
I want only one method goes to sleep but both method goes to sleep... userPlay() it makes sleep to both user and Android and both wake up together. I really tried very hard to find why it is making sleep() to both method together but i
Advertisements
example of sleep and wait method
example of sleep and wait method  write a program to use the sleep and wait method of thread class
sleep method in thread java program
sleep method in thread java program  How can we use sleep method... example ,we have used sleep method. we are passing some interval to the sleep... Description:- In this thread example ,we have used sleep method. we are passing
Java Thread : sleep() method
Java Thread : sleep() method In this section we are going to describe sleep() method with example in java thread. sleep() method : Suppose you want to stop your thread for a specific time period, you can use sleep() method
PHP Sleep Wakeup Method
__sleep or not. If so, then the function execute that method prior to any other... that the object may have. PHP Sleep and Wakeup Method Example: <?php...The __sleep and __wakeup Function in PHP The __sleep function in PHP is useful
Java Sleep Thread
Java Thread sleep() is a static method. It sleeps the thread for the given... or GUI programming for animation Java Sleep Thread Example public class... public void run() { for (int i = 1; i <= 4; i++) { if (i % 2 == 0
__sleep and __wakeup
__sleep and __wakeup  What?s the special meaning of _sleep and _wakeup
yield and sleep
yield and sleep  hello, What is the difference between yield() and sleep
how can i define only one method from the interface. - Java Beginners
how can i define only one method from the interface.  If i am having an interface with 3 methods(declaration) . If i want to use only one method... the solution for that. please i want it immediately.  Hi friend
need a jar file to come out of sleep mode
then phone goes to out of sleep mode. can any body help me with this subject ? I...need a jar file to come out of sleep mode  Hi I need a jar file... it to any address by email . But when the phone goes to sleep mode
What is the special meaning of __sleep and __wakeup?
What is the special meaning of __sleep and __wakeup?  What?s the special meaning of _sleep and _wakeup
What?s the special meaning of __sleep and __wakeup?
What?s the special meaning of __sleep and __wakeup?  What?s the special meaning of _sleep and _wakeup
I want to Transfer only 1/3rd of contents from one folder to other but my code is transferring all contents
I want to Transfer only 1/3rd of contents from one folder to other but my code...("No files in directory: " + src); } for (int i = 0; i < entries.length; i++) { File file = entries[i
I have only one day to visit the Jaipur..
I have only one day to visit the Jaipur..  Hi, I have only a day to travel in Jaipur ..hence, bit worried about what to see first
Java Method Synchronized
is a keyword used in Java ensures that only one Java thread execute an object's synchronized method at a time. The concept lies on the thread, that allows... Java Method Synchronized     
This code send email two times but i want only once
This code send email two times but i want only once   public void dbbackup_notify(String email,String data,String subject){ String toEmails = email; Session session=Session.getInstance(props, new
This code send email two times but i want only once
This code send email two times but i want only once   public void dbbackup_notify(String email,String data,String subject){ String toEmails = email; Session session=Session.getInstance(props, new
method
method   how and where, we can define methods ? can u explain me with full programme and using comments
method
method  can you tell me how to write an abstract method called ucapan() for B2 class class A2{ void hello(){ system.out.println("hello from A2"); }} class B2 extends A2{ void hello(){ system.out.println("hello from B2
i have one txt field and one button.when i entere any test in testfield then only button should be enabled.
i have one txt field and one button.when i entere any test in testfield then only button should be enabled.  i have one txt field and one button.when i entere any test in testfield then only button should be enabled. i need
i have one txt field and one button.when i entere any test in testfield then only button should be enabled. i need for this
i have one txt field and one button.when i entere any test in testfield then only button should be enabled. i need for this   i have one txt field and one button.when i entere any test in testfield then only button should
How i write a function/method in jsp?
How i write a function/method in jsp?  How write the function/method in jsp? Using that method i can retrieve the value coming from database. give me example plz. Actually i want to show the list of user detail
Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container and the bean provider.
the ejbPassivate method completes must be one of the following: A serializable... Identify the use and the behavior of the ejbPassivate method in a session bean, including the responsibilities of both the container
Programming - countVowels() method
one parameter, a string, and it returns the int number of vowels (a e i o u... as the vowels. Case. It should handle both upper and lower case vowels. No I/O. As usual, this method should do no I/O. Method header. The method should
How to Insert image and data both together in database in JSP/Servlet ?
How to Insert image and data both together in database in JSP/Servlet ? ...="NewAdmission2011_12.jsp" METHOD="POST"> <br><br><br> <center> <...(e.getMessage()); } } %> //if i remove below lines then it insert
i want to create an application with only a button which on click displays table from database using struts2 and hibernate on eclipse
i want to create an application with only a button which on click displays table from database using struts2 and hibernate on eclipse  please help me i have to submit this soon
how to open one Jframe from main method call
how to open one Jframe from main method call  I have downloaded... don't want in my project Here is the code that i have included in main method... the main() method, when i run this Engine.java class game starts running
can i estimate estimate execution time for a method without knowing implementation details of a method - Java Interview Questions
can i estimate estimate execution time for a method without knowing implementation details of a method  hi all, can i estimate estimate execution time for a method without knowing implementation details of a method. Thanks
method inside the method??
method inside the method??  can't we declare a method inside a method in java?? for eg: public class One { public static void main(String[] args) { One obj=new One(); One.add(); private static void add
Works only for one row
Works only for one row   Hi, My below code is working only if there is a single row. could you please help me in doing it for all the rows...; <form name="abc" method="post" action="">
I invoke the ResultSet methods afterLast and beforeFirst when the method next works.
I invoke the ResultSet methods afterLast and beforeFirst when the method next works.  Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next works
i want validation for one text field and text area,email,combobox, in that email will validte by useing regular expressions?
i want validation for one text field and text area,email,combobox, in that email will validte by useing regular expressions?  i want validation for one text field and text area,email,combobox, in that email will validte by useing
i want to store dynamic number of value on one jsp and retrieve them on other.
i want to store dynamic number of value on one jsp and retrieve them on other.  in my problem, i want to run a query from database.then while in loop... are being created in result loop. i.e while(rs.next){}. i want to store
i want to copy files from one machine to other using java and the code will be running on third machine
i want to copy files from one machine to other using java and the code will be running on third machine  i want to copy some files from one machine... machine say 'c'. So , can you help me on this that how can i do this using
Method
of method in java object-oriented technique first one is the Instance method and the other one is the class method.     Method Overloading... Method      
Method overriding
Method overriding  can a method declared in one package be over ridden in a different package?   A subclass in a different package can only override the non-final methods declared public or protected
method question
method question  How do I figure out the difference in a method heading, a method body, and a method definition
customize method in java
customize method in java  hi there i want to create one customize method in which any no of parameters can be pass e.g the limit is 13 and if user wants to enter 3 inputs then that much can only be proceed so can i have solution
Programming - reverse() method
. Method only. Write only the method, not main program. No I/O. As usual, this method should do no I/O. Method header. The method should... Java: Programming - reverse() method Problem Write a method which has one
method overloading
method overloading  public void test(int a) public void test(long a) public void test(object a) i will call some x.test(1258448); which method is called if it is called first one why it not call the third one
init method
init method  why init method used in servlet?   The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed
i want code for these programs
i want code for these programs   Advances in operating system Laboratory Work: (The following programs can be executed on any...-relaxation method and n processes which use Shared Memory API. Design, develop
get method
get method   how to use get method: secure method is post method and most of use post method why use a get method
I want this jsp answers
I want this jsp answers    How can we declare third party classes... be the default executable method inside the generated servlet? If we are developing jsp... for particular jsp pages? If we want to develop any jsp pages using eclipse where we can
I want this jsp answers
I want this jsp answers    How can we declare third party classes... be the default executable method inside the generated servlet? If we are developing jsp... for particular jsp pages? If we want to develop any jsp pages using eclipse where we can
Method Overriding in Java
Method Overriding in Java means a Subclass uses extends keyword to override a super class method. In Overriding both subclass and superclass must have same... be overridden only if they are inherited by the subclass. Example of Method
java method
java method  can we declare a method in java like this static { System.loadLibrary("nativelib"); } i have seen this in a java learning E book. i don't understand the static { } plz help me. what kind of method
method overloading
method overloading  public void test(int a){} public void test(long a){} i will call some x.test(125) which method is called pls tell me
i want to learn Jquery
i want to learn Jquery  i want to learn jquery can u plz guide me   Yes, you can learn these technologies by yourself. Go through the following links: Ajax Tutorials JSON Tutorials JQuery Tutorials
 

 

 

DMCA.com