井字游戏
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.util.Scanner; 2 public class WellWordGame { 3 public static char[][] board = new char[3][3]; 4 Scanner input = new Scanner(System.in); 5 public int row; 6 public int column; 7 public WellWordGame() 8 { 9 displayBoard(); 10 for(int i = 0; i <= 2; i++) 11 for(int j = 0; j <= 2; j++) 12 board[i][j] = ' '; 13 } 14 public void start() 15 { 16 while(true) 17 { 18 playXDo(); 19 displayBoard(); 20 if(isWon('X')) 21 { 22 System.out.println("X player Won!"); 23 break; 24 } 25 if(isDraw()) 26 { 27 System.out.println("Draw!"); 28 break; 29 } 30 playODo(); 31 displayBoard(); 32 if(isWon('O')) 33 { 34 System.out.println("O player Won!"); 35 break; 36 } 37 if(isDraw()) 38 { 39 System.out.println("Draw!"); 40 break; 41 } 42 } 43 } 44 public void playXDo() 45 { 46 System.out.println("Enter a row (1, 2, or 3) for player X:"); 47 row = input.nextInt(); 48 System.out.println("Enter a column (1, 2, or 3) for player X:"); 49 column = input.nextInt(); 50 board[row-1][column-1] = 'X'; 51 } 52 public void playODo() 53 { 54 System.out.println("Enter a row (1, 2, or 3) for player O:"); 55 row = input.nextInt(); 56 System.out.println("Enter a column (1, 2, or 3) for player O:"); 57 column = input.nextInt(); 58 board[row-1][column-1] = 'O'; 59 } 60 public void displayBoard() 61 { 62 int i = 0; 63 while(i!=3) 64 { 65 System.out.println("-------------"); 66 //System.out.println("| | | |"); 67 System.out.println("| " + board[i][0] + " | " +board[i][1] + " | "+board[i][2] +" |"); 68 i++; 69 } 70 System.out.println("-------------"); 71 } 72 public static void main(String[] args) { 73 //PlayerO and PlayerX, ,每次一个玩家输入row 和 column,,显示输出结果,并且判断输赢和是否是平局, 74 //如果某个玩家赢了或者平局,输出结果,否则继续 75 WellWordGame game = new WellWordGame(); 76 game.start(); 77 78 } 79 public static boolean isWon(char c) 80 { 81 for(int i = 0; i <= 2; i++)//每一行 82 if(board[i][0] == c && board[i][1] == c && board[i][2] == c) 83 return true; 84 for(int j = 0; j < 3; j++) 85 { 86 if(board[0][j] == c && board[1][j] == c && board[2][j] == c) 87 return true; 88 } 89 if(board[0][0] == c && board[1][1] == c && board[2][2] == c ) 90 return true; 91 if(board[0][2] == c && board[1][1] == c && board[2][0] == c ) 92 return true; 93 return false; 94 } 95 public static boolean isDraw() 96 { 97 for(int i = 0; i <= 2; i++) 98 for(int j = 0; j <= 2; j++) 99 { 100 if(board[i][j] == ' ') 101 return false; 102 } 103 return true; 104 } 105 106 }
是一种在3*3格子上进行的连珠游戏,和五子棋比较类似,由于棋盘一般不画边框,格线排成井字故得名。游戏需要的工具仅为纸和笔,然后由分别代表O和X的两个游戏者轮流在格子里留下标记(一般来说先手者为X)。由最先在任意一条直线上成功连接三个标记的一方获胜。