1、在俄罗斯方块程序中,有L形,T形,田形等多种形状,它们是图形的多种形态,可以创建一个名为Shape的基类,而后派生L形,T形等,之后可以在运行时动态绘制各种形状。
1)创建一个名位Teris的控制台应用程序、
2)各个类之间的关系如下图所示:
待上传·····························
3)创建名为Shape的抽象类,包括ShapeType属性和显示信息方法,以及抽象方法绘制:
4)创建名为ShapeL的派生类,实现基类的绘制
5)创建名为ShapeT的派生类,实现基类的绘制
6)创建名为ShapeZ的派生类,实现基类的绘制
7)创建名为ShapeBlock(田字形)的派生类,实现基类的绘制
8)在Program.cs中添加如下代码,实现随机生成图形:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;//进程函数的库函数,Thread.Sleep(1000); namespace Teris { enum ShapeType { Block = 0, L, T, Z }//枚举类型的使用 class Program { static void Main(string[] args) { Random rnd = new Random(); while (true) { Shape shape = null; ShapeType type = (ShapeType)rnd.Next(4);//random.Next(MaxValue)----------返回一个小于所指定最大值的非负随机数 switch (type)//switch选择,建立一个类, { case ShapeType.Block: shape = new ShapeBlock(); break; case ShapeType.L: shape = new ShapeL(); break; case ShapeType.T: shape = new ShapeT(); break; case ShapeType.Z: shape = new ShapeZ(); break; } if (shape != null)//如果所建立的类存在,则相应得调用它的函数 { shape.DisplayInfo(); shape.Draw(); Console.WriteLine("----------------------"); Thread.Sleep(1000);//防止刷新太快,让系统停止1秒} } } } public abstract class Shape//建立一个shape图形抽象类 { private string shapeType;//图形形状变量 public string ShapeType//图形形状属性 { get { return shapeType; } set { shapeType = value; } } public void DisplayInfo()//展示图形类型的方法 { Console.WriteLine("当前图形类型" + shapeType); } public abstract void Draw();//抽象类的展示图形的方法 } public class ShapeL : Shape { public ShapeL()//shapeL的无参对象 { ShapeType = "L形"; } public override void Draw()//重载抽象类的展示图形的方法 { Console.WriteLine("|"); Console.WriteLine("|"); Console.Write("|"); Console.WriteLine("__"); } } public class ShapeT : Shape { public ShapeT()//shapeT的无参对象 { ShapeType = "T形"; } public override void Draw()//重载抽象类的展示图形的方法 { Console.WriteLine("_______"); Console.WriteLine(" |"); Console.WriteLine(" |"); } } public class ShapeZ : Shape { public ShapeZ()//shapeZ的无参对象 { ShapeType = "Z形"; } public override void Draw()//重载抽象类的展示图形的方法 { Console.WriteLine("----"); Console.WriteLine(" |"); Console.WriteLine(" |"); Console.WriteLine(" ----"); } } class ShapeBlock : Shape { public ShapeBlock()//shapeBlock的无参对象 { ShapeType = "田形"; } public override void Draw()//重载抽象类的展示图形的方法 { Console.WriteLine(" _________"); Console.WriteLine("| | |"); Console.WriteLine("| | |"); Console.WriteLine(" --------- "); Console.WriteLine("| | |"); Console.WriteLine("| | |"); Console.WriteLine(" --------- "); } } } }
运行结果:
待上传·······························
Nearth===021/c#抽象类、多态和接口(练习题1)
最新推荐文章于 2020-02-09 08:31:30 发布