using System;
using System.Threading;
namespace Bike//该案例主要练习对象的封装
{
class Bike
{
private int speed;//速度对象,原本是私有
private int angle;//角度对象,原本是私有
public void ShowInfo()
{
Console.SetCursorPosition(0, 0);
Console.WriteLine("speed:{0,3},ange:{1,3}",speed,angle);
}
/// <summary>
/// 加速方法
/// </summary>
public void Acc()
{
speed = speed+4;
}
/// <summary>
/// 减速方法
/// </summary>
public void Break()
{
speed = speed - 10;
if (speed < 0)//如果速度小于0,那么速度就为0
{
speed = 0;
}
}
/// <summary>
/// 左转方法
/// </summary>
public void TurnLeft()
{
angle--;
}
/// <summary>
/// 右转方法
/// </summary>
public void TurnRight()
{
angle++;
}
/// <summary>
/// 不操作会自动减速
/// </summary>
public void Stay()
{
if (speed > 0)
{
speed--;
}
}
}
class Program
{
static void Main(string[] args)
{
Bike b = new Bike();
for (; ; )
{
if (Console.KeyAvailable)
{
ConsoleKey key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.W://加速
b.Acc();
break;
case ConsoleKey.S://减速
b.Break();
break;
case ConsoleKey.A://左转
b.TurnLeft();
break;
case ConsoleKey.D://右转
b.TurnRight();
break;
}
}
else
{
b.Stay();
}
b.ShowInfo();
Thread.Sleep(50);
}
}
}
}
对象的封装
最新推荐文章于 2023-03-20 21:19:34 发布