📄 ex5_26.java
字号:
import javax.swing.JOptionPane;
public class Ex5_26{
public static void main (String[] args) {
char[] chess=new char[10];
char[][] chessboard=new char[3][3];
for(int i=1;i<10;i++){
chess[i]=(char)(i+48);//1的ASCII码对应49
}
printboard(chess);
while(true){//循环让A和B放置棋子直至某一方赢棋或和棋
int row = Integer.parseInt(JOptionPane.showInputDialog("请游戏者A输入行号(0~2):"));
int col = Integer.parseInt(JOptionPane.showInputDialog("请游戏者A输入列号(0~2):"));
while(true){
if(IsOn(row*3+col+1,chess)) {
System.out.println("该位置已放置过棋子,请重新选择位置摆放");
row = Integer.parseInt(JOptionPane.showInputDialog("请游戏者A输入行号(0~2):"));
col = Integer.parseInt(JOptionPane.showInputDialog("请游戏者A输入列号(0~2):"));
}
else break;
}
chessboard[row][col] = 'X';
chess[row*3+col+1]='X';
printboard(chess);
if (Win('X',chess)) {
System.out.println("游戏者A赢了!");
System.exit(0);
}
else if (Draw(chess)){
System.out.println("和棋!");
System.exit(0);
}
row = Integer.parseInt(JOptionPane.showInputDialog("请游戏者B输入行号(0~2):"));
col = Integer.parseInt(JOptionPane.showInputDialog("请游戏者B输入列号(0~2):"));
while(true){
if(IsOn(row*3+col+1,chess)) {
System.out.println("该位置已放置过棋子,请重新选择位置摆放");
row = Integer.parseInt(JOptionPane.showInputDialog("请游戏者B输入行号(0~2):"));
col = Integer.parseInt(JOptionPane.showInputDialog("请游戏者B输入列号(0~2):"));
}
else break;
}
chessboard[row][col] = 'O';
chess[row*3+col+1]='O';
printboard(chess);
if (Win('O',chess)){
System.out.println("游戏者B赢了!");
System.exit(0);
}
else if (Draw(chess)){
System.out.println("和棋!");
System.exit(0);
}
}
}
static void printboard(char[] chess){//输出每一次的棋盘布局
System.out.println("\n");
System.out.println(" "+chess[1]+" "+"|"+" "+chess[2]+" "+"|"+" "+chess[3]);
System.out.println("-----------");
System.out.println(" "+chess[4]+" "+"|"+" "+chess[5]+" "+"|"+" "+chess[6]);
System.out.println("-----------");
System.out.println(" "+chess[7]+" "+"|"+" "+chess[8]+" "+"|"+" "+chess[9]);
System.out.println("\n");
}
static boolean IsOn(int i,char[] chess){//判断该位置是否已放置过棋子
if(chess[i]!=i+'0') return true;
else return false;
}
static boolean Win(char c,char[] chess){//判断是否赢,即只需找到同一行,同一列或两条对角线的棋子全是某一方的即可
for(int i=0;i<=2;i++)
if(chess[i*3+1]==c&&chess[i*3+2]==c&&chess[i*3+3]==c)
return true;
for(int i=0;i<=2;i++)
if(chess[i+1]==c&&chess[i+4]==c&&chess[i+7]==c)
return true;
if(chess[1]==c&&chess[5]==c&&chess[9]==c)
return true;
if(chess[3]==c&&chess[5]==c&&chess[7]==c)
return true;
else return false;
}
static boolean Draw(char[] chess){//判断和棋只需判断当前棋盘已下满且未有一方赢棋
for(int i=1;i<=9;i++){
char c=(char)(i+48);
if(chess[i]==c)
return false;
}
return true;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -