2012-04-18 3 views
-1

Android 용 TicTacToe 게임을 만들었습니다. 사용자의 턴이나 안드로이드의 턴과 같이 곧 턴을 시작할 화면에 표시하고 싶습니다. 작동하는 this에 대한 updateGameInfo 함수를 만들었지 만 디스플레이에 적절한 출력을 얻기 위해이 함수를 어디에서 호출해야하는지 결정할 수 없습니다. 미리 감사드립니다. 여기 당신이 후 updateGameInfo 부분을 넣을 수 있다고 생각 내 코드이벤트 변경 안 함

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 static TextView textlevel2=null; 
public static TextView textlevel3=null; 
public double userBest_Time=0; 
public double cpuBest_Time=0; 
public double startTime; 
long prev_Time=0; 
double userDuration; 
double cpuDuration; 
private float[] w; 
private int[] c;   
private int[][] PosTable; 
private Button[] buttons; 
    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() { 
    //computer plays first 
    int cpos=getDecision(); 
    if (cpos == -1) { 
     Toast toast = Toast.makeText(getApplicationContext(), "GAME OVER", Toast.LENGTH_SHORT); 
     toast.show(); 
     return; 
    } 
    c[cpos]=1; 
    updateBtn(cpos); 
    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) 
     { 
     String PlayerName="Android";   
     updateGameInfo(PlayerName + " turn."); 
     try { 
      Thread.sleep(500); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     buttons[i].setText("O"); 
     buttons[i].setTextColor(Color.RED); 

     } 
    else 
     { 
     String PlayerName="User";  
     updateGameInfo(PlayerName + " turn."); 
     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); 
     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) { 
      cpuPlay(); 
     } 
    } 
} 

private int getDecision() { 
    String Player="Android"; 
// updateGameInfo(Player + " turn."); 
    try { 
     Thread.sleep(500); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    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) 
{ 
    TextView infoView =(TextView) findViewById(R.id.gameInfo); 
    infoView.setText(info); 
} 

}

답변

1

헤이 변경하려면 btnClicked에있는 game_contiues 코드

String name= "Android"; 
      updateGameInfo("Wait it's" + name + " turn"); 
      new Handler().postDelayed(new Runnable() { 

       @Override 
       public void run() { 
        cpuPlay(); 
       } 
      },500); 

이 의지 기분이 언짢아 밖으로 정렬 문제

1

입니다 .. 여기

 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); 
    updateGameInfo(Player + " turn.");<---every time you are updating the value on button call updategameinfo... 
    .... 
    //remaining code... 

와 ..

 private void cpuPlay() { 
    //computer plays first 
    int cpos=getDecision(); 
    if (cpos == -1) { 
    Toast toast = Toast.makeText(getApplicationContext(), "GAME OVER", Toast.LENGTH_SHORT); 
     toast.show(); 
    return; 
    } 
    c[cpos]=1; 
    updateBtn(cpos); 
    updateGameInfo(Player + " turn.");<----- 
    //remaining code here... 
+0

덕분에 짝 텍스트를 게임을 길게 설정하여 원하는 목적지이 실제로 작동하고 있지만, 실제로는 너무 빨리 해당 컴퓨터 돈을 발생 ' 해당 필드를 업데이트 할 시간을 얻으십시오. 그래서 나는 cpuPlay() 전에 sleep() 메소드를 구현하려했지만, 둘 다 사용자와 안드로이드를 함께 사용하여 잠을 자고 함께 깨우므로 컴퓨터가 업데이트 할 시간을 얻지 못하고있다. sleep()을 사용하는 방법을 알려주거나 wait()를 사용해야합니까? Thanks in Advance –

+0

이 줄 다음에 sleep을 사용할 수 있습니다 .. updateGameInfo (Player + "turn."); <----- .. 내 대답의 마지막 줄 ...하지만 스레드를 1 초 동안 잠자면 여기에 .. 다음 CPU 재생 후 .. 스레드는 그 시간 동안 잠들고 터치와 같은 입력을 취할 수 없기 때문에 사용자가 재생할 수 있습니다 .. – 5hssba

+0

도움을 다시 한번 고마워, 그것은 잠을 사용하여 작동하지 않습니다 때문에 둘 다 같은 스레드에 의해 실행되기 때문에 두 가지 방법을 모두 사용합니다. 하지만 아무 문제가있어 처리기를 사용하여 솔루션을 가지고 있기 때문에 –

1

사용 처리기, 당신은