井字棋游戏初步完成
实现功能:输入位置数据->打印棋盘->判断是否胜利->继续游戏/退出游戏
缺点:没有清屏函数 判断胜利方法太过无脑
package MYGAME;
import java.util.Scanner;
public class Mygame {
static int winnerx = 0;
static int winnero = 0;
static int row; // 行
static int rank; // 行
static int[][] x = new int[3][3]; // X玩家的棋子
static int[][] o = new int[3][3]; // O玩家的棋子
public static void main(String[] args) {
inputmap();
for (int p = 0; p < 9; p++) {
if (p % 2 == 1) {
oplay();
if (winnero==1){
System.out.println("o选手胜利");
break;
}
} else {
xplay();
if (winnerx==1){
System.out.println("x选手胜利");
break;
}
}
}
System.out.println("游戏结束");
}
// 输出棋盘
public static void inputmap() {
System.out.println(" ");
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if (x[m][n] == 1) {
System.out.print("x|");
} else if (o[m][n] == 1) {
System.out.print("o|");
} else {
System.out.print(" |");
}
}
System.out.println(" ");
}
}
// x选手开始下棋
public static void xplay() {
Scanner input = new Scanner(System.in);
System.out.print("轮到x选手下棋\n");
System.out.print("请选择第几行\n");
row = input.nextInt() - 1;
System.out.print("请选择第几列\n");
rank = input.nextInt() - 1;
x[row][rank] = 1;
inputmap();
win();
}
// o选手开始下棋
public static void oplay() {
Scanner input = new Scanner(System.in);
System.out.print("轮到o选手下棋\n");
System.out.print("请选择第几行\n");
row = input.nextInt() - 1;
System.out.print("请选择第几列\n");
rank = input.nextInt() - 1;
o[row][rank] = 1;
inputmap();
win();
}
// 手动清屏=。=
public static void cleanscreen() {
for (int i = 0; i < 50; i++) {
System.out.println("");
}
}
//判断是否胜利
public static void win() {
if (
(x[0][0] == 1 & x[1][0] == 1 & x[2][0] == 1)||
(x[0][1] == 1 & x[1][1] == 1 & x[2][1] == 1)||
(x[0][2] == 1 & x[1][2] == 1 & x[2][2] == 1)||
(x[0][0] == 1 & x[0][1] == 1 & x[0][2] == 1)||
(x[1][0] == 1 & x[1][1] == 1 & x[1][2] == 1)||
(x[2][0] == 1 & x[2][1] == 1 & x[2][2] == 1)||
(x[0][0] == 1 & x[1][1] == 1 & x[2][2] == 1)||
(x[0][2] == 1 & x[1][1] == 1 & x[2][0] == 1)
){
winnerx=1;
}
if (
(o[0][0] == 1 & o[1][0] == 1 & o[2][0] == 1)||
(o[0][1] == 1 & o[1][1] == 1 & o[2][1] == 1)||
(o[0][2] == 1 & o[1][2] == 1 & o[2][2] == 1)||
(o[0][0] == 1 & o[0][1] == 1 & o[0][2] == 1)||
(o[1][0] == 1 & o[1][1] == 1 & o[1][2] == 1)||
(o[2][0] == 1 & o[2][1] == 1 & o[2][2] == 1)||
(o[0][0] == 1 & o[1][1] == 1 & o[2][2] == 1)||
(o[0][2] == 1 & o[1][1] == 1 & o[2][0] == 1)
){
winnero=1;
}
}
}