通过在控制台输出字符来实现一个中国象棋小游戏实际上是很简单的,也非常有趣。游戏是人人对战模式,实现后的效果如下:
代码思路很简单,就是创建好各个游戏对象的类,然后用一个管理类来实现游戏规则就可以了。但是这里我想说因为中国象棋的棋子种类和数量是固定的,可以视为稳定的代码(不会再扩展),继而整个程序都是稳定的,这里我认为就不需要使用多态或策略模式,使用多态是为了隔离程序中的稳定代码和变化代码,当代码全部为稳定时就不需要用,否则反而会变的麻烦。下面直接上代码:
Point类
#ifndef POINT_H
#define POINT_H
#include<iostream>
using namespace std;
//坐标类
class Point
{
public:
Point(int x = 0, int y = 0) : m_x(x), m_y(y) {};
~Point() {};
Point& operator=(const Point &p)
{
m_x = p.m_x;
m_y = p.m_y;
return *this;
}
bool operator==(const Point &p)const {
if (m_x == p.m_x&&m_y == p.m_y)
return true;
else return false;
}
void Set(const int x, const int y) { m_x = x; m_y = y; }
void SetX(const int x) { m_x = x; }
void SetY(const int y) { m_y = y; }
int GetX() const { return m_x; }
int GetY()const { return m_y; }
private:
int m_x;
int m_y;
};
#endif
Chess类
#ifndef CHESS_H
#define CHESS_H
#include"Point.h"
enum ChessCamp//棋子阵营(红绿两方)
{
RED,GREEN
};
enum ChessType//棋子种类
{
MA,SHUAI,CHE,PAO,SHI,BING,XIANG
};
class Chess
{
public:
Chess(ChessType type, ChessCamp camp, Point position)
:m_type(type),m_camp(camp),m_position(position)
{}
~Chess(){}
Point GetPosition()const { return m_position; }
void SetPosition(const Point& newposition) { m_position = newposition; }
ChessType GetType()const { return m_type; }
ChessCamp GetCamp()const { return m_camp; }
private:
ChessType m_type;
ChessCamp m_camp;
Point m_position;
};
#endif // !CHESS_H
ChessBoard(棋盘)类
#ifndef CHESSBOARD_H
#define CHESSBOARD_H
#include<Windows.h>
#include"chess.h"
class ChessBoard
{
public:
bool m_isend;
ChessBoard();
~ChessBoard() {}
void PrintBoard();
void ChangeChess(const Point& spos, const Point& tpos);
Chess* GetChess(const Point& pos)const
{
return m_allchess[pos.GetX()][pos.GetY()];
}
void Clear() {
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 9; j++)
{
if (m_allchess[i][j] != nullptr)
{
delete m_allchess[i][j];
m_allchess[i][j] = nullptr;
}
}
}
}
private:
Chess* m_allchess[10][9];
};
#endif
#include"ChessBoard.h"
ChessBoard::ChessBoard()
{
m_isend = false;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 9; j++)
m_allchess[i][j] = nullptr;
}
//四个