HeadFirstC#赛狗日
——————————————————————————————————————
最近做了HeadFirst的赛狗日章节,现在把自己做出来的代码分享在此,同时也是给自己做个记录,作为一位C#初学者,以后可以参考使用,欢迎大家指教。(所有内容都粘帖进来,并且对窗口所有按钮都做了对应说明)
一、首先是狗类(Greyhound)中所有代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace Chapter4_DogRace01
{
public class Greyhound //Greyhound即格力犬,赛狗专用犬种
{
public int IndexDog;//狗的号码
public int StartingPosition=12;//狗的图片起始位置,int类型
public int RacetrackLength=661;//跑道的长度,int类型
public PictureBox MyPictureBox = null;// 我的图片对象
public int Location = 0;//在跑道上的位置,也即完成的路程,初始值为0
public Random Randomizer;//速度随机生成变量,各个狗的Randomizer引用都要指向同一个Random对象
public Greyhound(PictureBox pictureBox)
{
this.MyPictureBox = pictureBox;
}
public bool Run()//定义狗跑方法,为一个bool值
{
Randomizer = new Random();//实例化Randomizer
int speed = Randomizer.Next(1,10);//定义speed来得到1到10的随机速度
Point p = MyPictureBox.Location;//为Drawing中的类,表示坐标点(X为横坐标)
p.X += speed;//得到坐标点p在横坐标上增加的距离speed
System.Threading.Thread.Sleep(10);//将当前线程休眠10毫秒,可改变狗的速度
Application.DoEvents();//加上这句实现进程同步,使得每个犬获胜几率更接近
MyPictureBox.Location = p;//把p的坐标赋值给我的图片对象的坐标Location
Location = p.X;//p点增加的距离赋值给Location完成的路程
if (Location>=RacetrackLength)//当完成跑道长度,即跑完全程了,返回true
{
return true;//没跑完全程就执行该Run方法,继续跑
}
else
{
return false;//跑完了全程就不执行该Run方法,不跑了
}
}
public void TakeStartingPosition()
{
this.MyPictureBox.Location=new Point(this.StartingPosition,MyPictureBox.Location.Y);
this.Location = 0;//this就是这个狗类,给我的狗图片赋予新的坐标点-0点,即回到开始位置
}
}