象棋游戏:抽象类里如何提供代表棋子位置的属性和方法?
一、题目:6-6 设计一个象棋游戏。ChessPiece为抽象类,提供代表一个棋子位置的属性和方法,和isMoveLegal方法。还有继承ChessPiece的具体类(如车,马,帅等),这些类要能根据各自的特点具体实现isMoveLegal。 答:第一步:
namespace 书本例题
{
public abstract class ChessPiece
{
public abstract void isMoveLegal();
}
//车类
public class Chariot : ChessPiece
{
int ChariotX,ChariotY;
public Chariot()
{
this.ChariotX = 1;
this.ChariotY = 1;
}
public Chariot(int _x,int _y)
{
this.ChariotX = _x;
this.ChariotY = _y;
}
public override void isMoveLegal()
{
Console.WriteLine("战车当前位置为:({0},{1})", this.ChariotX, this.ChariotY);
int k;
do
{
Console.WriteLine("请输入“战车”移动的步子:");
k = Convert.ToInt32(Console.ReadLine());
} while (k < 1 || k > 9);
//前进
this.ChariotX = this.ChariotX + 0;
this.ChariotY = this.ChariotY + k;
if (this.ChariotY > 8)
{
this.ChariotY = this.ChariotY - (this.ChariotY - 8);
}
Console.WriteLine("前进{0}步后的位置为:({1},{2})",k, this.ChariotX, this.ChariotY);
//后退
this.ChariotX = this.ChariotX + 0;
this.ChariotY = this.ChariotY - k;
if (this.ChariotY <= 0)
{
this.ChariotY = 1;
}
Console.WriteLine("后退{0}步后的位置为:({1},{2})", k, this.ChariotX, this.ChariotY);
//左移
this.ChariotX = this.ChariotX + k;
this.ChariotY = this.ChariotY + 0;
if (this.ChariotX > 8)
{
this.ChariotX = this.ChariotX - (this.ChariotX - 8);
}
Console.WriteLine("左移{0}步后的位置为:({1},{2})", k, this.ChariotX, this.ChariotY);
//右移
this.ChariotX = this.ChariotX - k;
this.ChariotY = this.ChariotY + 0;
if (this.ChariotX <= 0)
{
this.ChariotX = 1;
}
Console.WriteLine("右移{0}步后的位置为:({1},{2})", k, this.ChariotX, this.ChariotY);
}
}
//马类
//public class Horse : ChessPiece
//{
//}
//炮类
//public class Cannon : ChessPiece
//{
//}
class Program
{
static void Main(string[] args)
{
ChessPiece CD;
CD = new Chariot(); //战车
CD.isMoveLegal();
CD = new Chariot(2,4);
CD.isMoveLegal();
//战马
//大炮
Console.ReadKey();
}
}
}
二、困惑
1、我做不到在抽象类中表示属性?
2、还有,“提供代表一个棋子位置的属性和方法”中的“方法”是什么意思?
请高手大侠们指点迷津。谢谢!