Head First C#(赛狗日)
实验背景:
人:Joe、Bob和AI希望参见赛狗赌博。最初,Joe有50元,Bob有75元,AI有45元。每次比赛前,他们都会各自决定是否下注以及所押的赌金。直到比赛前,他们都可以改变赌金,但是一旦比赛开始,赌金就再不能更改了。
赌场:赌场会跟踪每个人持有的现金,以及每个人下注的对象。每次下注至少5元。一场比赛中,赌场对每个人只取一次赌金;也就是说每个人不得重复下注。赌场会检查下注的人确实有足够的现金支付他的赌金,所以如果没有钱来作赌资这个人就不能下注。
下注:每次下注都会“翻倍或全陪”,要求最低5元,而且每个人对一只狗最多下注15元。
比赛:有4只狗在直道上比赛。比赛胜者是第一只穿过终点线的狗。
书中给出的作为参考的类图:
参考别人的博客写的代码
Greyhound类
class Greyhound
{
public int Index; //狗的号码
public int StartingPosition=0;//图片起始坐标
public int RacetrackLength = 600; //路程
public PictureBox MyPictureBox = null; //图片控件
public int Location = 0;//已完成路程
public Random Randomizer;//
//构造函数
public Greyhound(PictureBox picturebox)
{
this.MyPictureBox = picturebox;
this.Index = index;
}
public bool Run()
{
int speed=Randomizer.Next(1, 20);
Point p = MyPictureBox.Location;
p.X += speed;
System.Threading.Thread.Sleep(100);
MyPictureBox.Location = p;
if (p.X >= RacetrackLength)
return true;
else return false;
}
public void TakeStartingPosition()
{
this.MyPictureBox.Location = new Point(this.StartingPosition, MyPictureBox.Location.Y);
this.Location = 0;
}
}
对Grayhound初始化(学着点)
void InitGrey()
{
grey = new Greyhound[]
{
new Greyhound(pictureBox2){Index=1,Randomizer=mainRand},
new Greyhound(pictureBox3){Index=2,Randomizer=mainRand},
new Greyhound(pictureBox4){Index=3,Randomizer=mainRand},
new Greyhound(pictureBox5){Index=4,Randomizer=mainRand},
};
}
Guy类
public class Guy
{
public string Name;//姓名
public Bet Mybet=new Bet ();//赌注信息
public int Cash;//剩余现金
public RadioButton MyRadioButton;
public Label MyLabel;
/// <summary>
/// 下注更新显示信息
/// </summary>
public void UpdateRadio()
{
MyRadioButton.Text = string.Format("{0} has {1} bucks",this.Name,this.Cash.ToString());
}
/// <summary>
/// 重置赌注为0
/// </summary>
public void ClearBet()
{
MyLabel.Text=string.Format("{0} has't placed a bet",this.Name);
Mybet.Amout = 0;
}
/// <summary>
/// 下注
/// </summary>
public bool PlaceBet(int Amout, int Dog)
{
if (Amout > this.Cash)
return false;
this.Mybet.Amout = Amout;
this.Mybet.Dog = Dog;
this.Mybet.Bettor = this;
MyLabel.Text= Mybet.GetDescription();
return true;
}
/// <summary>
/// 清算结果
/// </summary>
public void Collect(int Winner)
{
this.Cash += this.Mybet.PayOut(Winner);
UpdateRadio();
ClearBet();
}
}