C++练习实例———中国象棋小游戏

通过在控制台输出字符来实现一个中国象棋小游戏实际上是很简单的,也非常有趣。游戏是人人对战模式,实现后的效果如下:

代码思路很简单,就是创建好各个游戏对象的类,然后用一个管理类来实现游戏规则就可以了。但是这里我想说因为中国象棋的棋子种类和数量是固定的,可以视为稳定的代码(不会再扩展),继而整个程序都是稳定的,这里我认为就不需要使用多态或策略模式,使用多态是为了隔离程序中的稳定代码和变化代码,当代码全部为稳定时就不需要用,否则反而会变的麻烦。下面直接上代码:

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;
	}
	//四个
  • 17
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值