本来很早就很想写个中国象棋,但是一直没有机会,前几天看到有人写了个,然后我也就写了个,代码没有那么短,只是给它分了类,我将它分成四个类;首先一个基类是所有的棋子的抽象类,然后有个具体类,将所有的需要特别设置的放到子类中实现,还有一个棋盘类,他是管理棋子和操作等步骤,最后一个是标志类,用来说明那个棋子被选中.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace ChineseChess { public abstract class APiece { public event EventHandler<EventArgs> Dying; public APiece(ChessBoard cb) { this.ChessBoard = cb; } public Image Image { get; set; } private bool isdead = false; public bool IsDead { get { return isdead; } set { if (value) { if (Dying != null) Dying(this, EventArgs.Empty); // this.ChessBoard.PieceList.Remove(this); } isdead = value; } } public string Name { get; set; } public ChessBoard ChessBoard { get; private set; } public Point Location { get; set; } public bool IsRed { get; set; } public virtual void Eat(APiece p) { p.IsDead = true; } public virtual bool Move(Point node) { if (this.Location == node) return false; var t = this.ChessBoard.GetPiece(node); if (t == null) { this.Location = node; } else { if (t.IsRed != this.IsRed) { this.Eat(t); this.Location = node; } } return true; } protected int Stop(Point Target) { int qry = 0; if (this.Location.X == Target.X) { int max = this.Location.Y > Target.Y ? this.Location.Y : Target.Y; int min = this.Location.Y + Target.Y - max; qry = (from p in this.ChessBoard.PieceList where p.Location.X == this.Location.X && p.Location.Y < max && p.Location.Y > min && !p.IsDead select p).Count(); } if (this.Location.Y == Target.Y) { int max = this.Location.X > Target.X ? this.Location.X : Target.X; int min = this.Location.X + Target.X - max; qry = (from p in this.ChessBoard.PieceList where p.Location.Y == this.Location.Y && p.Location.X < max && p.Location.X > min && !p.IsDead select p).Count(); } return qry; } protected int Step(Point Target) { var dx = Target.X - this.Location.X; var dy = Target.Y - this.Location.Y; return dx * dx + dy * dy; } public virtual void Draw(Graphics g) { if (!IsDead) { g.DrawImage(this.Image, this.ChessBoard.GetPixelRantangle(this.Location)); } } } }