井字棋游戏初步完成
实现功能:输入位置数据->打印棋盘->判断是否胜利->继续游戏/退出游戏
缺点:没有清屏函数 判断胜利方法太过无脑
1 package MYGAME; 2 3 import java.util.Scanner; 4 5 public class Mygame { 6 static int winnerx = 0; 7 static int winnero = 0; 8 static int row; // 行 9 static int rank; // 行 10 static int[][] x = new int[3][3]; // X玩家的棋子 11 static int[][] o = new int[3][3]; // O玩家的棋子 12 13 public static void main(String[] args) { 14 inputmap(); 15 for (int p = 0; p < 9; p++) { 16 if (p % 2 == 1) { 17 oplay(); 18 if (winnero==1){ 19 System.out.println("o选手胜利"); 20 break; 21 } 22 } else { 23 xplay(); 24 if (winnerx==1){ 25 System.out.println("x选手胜利"); 26 break; 27 } 28 } 29 } 30 System.out.println("游戏结束"); 31 } 32 33 // 输出棋盘 34 public static void inputmap() { 35 System.out.println(" "); 36 for (int m = 0; m < 3; m++) { 37 for (int n = 0; n < 3; n++) { 38 if (x[m][n] == 1) { 39 System.out.print("x|"); 40 } else if (o[m][n] == 1) { 41 System.out.print("o|"); 42 } else { 43 System.out.print(" |"); 44 } 45 } 46 System.out.println(" "); 47 } 48 } 49 50 // x选手开始下棋 51 public static void xplay() { 52 Scanner input = new Scanner(System.in); 53 System.out.print("轮到x选手下棋\n"); 54 System.out.print("请选择第几行\n"); 55 row = input.nextInt() - 1; 56 System.out.print("请选择第几列\n"); 57 rank = input.nextInt() - 1; 58 x[row][rank] = 1; 59 inputmap(); 60 win(); 61 } 62 63 // o选手开始下棋 64 public static void oplay() { 65 Scanner input = new Scanner(System.in); 66 System.out.print("轮到o选手下棋\n"); 67 System.out.print("请选择第几行\n"); 68 row = input.nextInt() - 1; 69 System.out.print("请选择第几列\n"); 70 rank = input.nextInt() - 1; 71 o[row][rank] = 1; 72 inputmap(); 73 win(); 74 } 75 76 // 手动清屏=。= 77 public static void cleanscreen() { 78 for (int i = 0; i < 50; i++) { 79 System.out.println(""); 80 } 81 } 82 83 84 //判断是否胜利 85 public static void win() { 86 if ( 87 (x[0][0] == 1 & x[1][0] == 1 & x[2][0] == 1)|| 88 (x[0][1] == 1 & x[1][1] == 1 & x[2][1] == 1)|| 89 (x[0][2] == 1 & x[1][2] == 1 & x[2][2] == 1)|| 90 (x[0][0] == 1 & x[0][1] == 1 & x[0][2] == 1)|| 91 (x[1][0] == 1 & x[1][1] == 1 & x[1][2] == 1)|| 92 (x[2][0] == 1 & x[2][1] == 1 & x[2][2] == 1)|| 93 (x[0][0] == 1 & x[1][1] == 1 & x[2][2] == 1)|| 94 (x[0][2] == 1 & x[1][1] == 1 & x[2][0] == 1) 95 ){ 96 winnerx=1; 97 } 98 if ( 99 (o[0][0] == 1 & o[1][0] == 1 & o[2][0] == 1)|| 100 (o[0][1] == 1 & o[1][1] == 1 & o[2][1] == 1)|| 101 (o[0][2] == 1 & o[1][2] == 1 & o[2][2] == 1)|| 102 (o[0][0] == 1 & o[0][1] == 1 & o[0][2] == 1)|| 103 (o[1][0] == 1 & o[1][1] == 1 & o[1][2] == 1)|| 104 (o[2][0] == 1 & o[2][1] == 1 & o[2][2] == 1)|| 105 (o[0][0] == 1 & o[1][1] == 1 & o[2][2] == 1)|| 106 (o[0][2] == 1 & o[1][1] == 1 & o[2][0] == 1) 107 ){ 108 winnero=1; 109 } 110 } 111 112 }