Java 8.9 游戏:井字游戏(C++&Java)

思路框架同8.20 :

C++:

#include<iostream>
#include<string>
using namespace std;
class Chess {
public:
	Chess();                         //初始化成员数据
	void show();                     //显示棋盘
	int input(int x,int y,int key);  //下棋
	int judge(int x,int y);          //判断结果
	string C[2] = { "X","O" };
private:
	string Graph[3][3];
	int  R = 9;                      //棋盘剩余空格
};
Chess::Chess(){
	for (int i = 0; i < 3; i++) {     //初始化Graph
		for (int j = 0; j < 3; j++) {
			Graph[i][j] = " ";  
		}
	}
}
void Chess::show(){
	for (int i = 0; i<3 ; i++) {
		cout << "-------------" << endl;
		cout << "|";
		for (int j = 0; j < 3; j++) 
			cout <<" "<< Graph[i][j] << " |";
		cout << endl;
	}
	cout << "-------------" << endl;
}
int Chess::input(int x,int y,int key) {
	if (y > 3 || y < 0){           //越界检测
		cout << "y is out of range[0,6]" << endl;
		return 1;
	}
	if (x > 3 || x < 0) {
		cout << "x is out of range" << endl;
		return 1;
	}
	if (Graph[x][y] != " ") {      //不能在同一格下棋
		cout << "(" << x << "," << y << "): has  exist" << endl;
		return 1;
	}

	Graph[x][y] = C[key % 2];    //赋值
	R--;                         //剩余格子减一
	return 0;
}
int Chess::judge(int x,int y) {
	int kx[8] = { 0, 1, 1, 1 },      //八个方向(4个正方向,另外4个负方向取反)
		ky[8] = { 1, 1, 0,-1 };
	int a, b, count = 0;
	for (int i = 0; i < 4; i++) {          //八个方向检测
		a = x;          //数据初始化
		b = y;
		count = 0;
		for (int j = 0; j < 2; j++) {      //检测四个正方向
			a += kx[i];
			b += ky[i];
			if (b > 2 || a > 2 || a < 0 || b < 0 || Graph[a][b] == " ")        //边界检测
				break;
			if (Graph[a][b] == Graph[x][y] )
				count++;
		}
		a = x;
		b = y;
		for (int j = 0; j < 2; j++) {      //检测四个负方向
			a -= kx[i];
			b -= ky[i];
			if (b > 2 || a > 2 || a < 0 || b < 0 || Graph[a][b] == " ")        //边界检测
				break;
			if (Graph[a][b] == Graph[x][y])
				count++;
		}
		if (count == 2)                 //四子相连,此人胜出
			return 1;
	}
	if(R==0)
		return -1;
	return 0;                         
}
int main() {
	Chess myChess;
	myChess.show();
	int x,y,key;
	for (int i = 0;;) {         //i奇偶决定颜色
		cout << "Enter a row (0, 1 or 2) for player "<< myChess.C[i % 2] <<": ";
		cin >> x;
		cout << "Enter a column (0, 1 or 2) for player " << myChess.C[i % 2] << ": ";
		cin >> y;
		if (myChess.input(x, y, i))    //bug检测
			continue;
		system("cls");          //清屏
		myChess.show();
		key = myChess.judge(x, y);   //key判断输赢,平局
		if (key==1) {
			cout << myChess.C[i % 2] << " player won" << endl;
			break;
		}
		else if (key == -1) {
			cout << "Chess draw" << endl;
			break;
		}
		i++;
	}
return 0;
}

Java:

         请自己写

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/82914405
8.9