using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace LiikkuvaAuto { public delegate void Tormays(int kunto, int tormayksia); public delegate void Rikki(object sender, AutoEventArgs e); public partial class LiikkuvaAuto : PictureBox { [Category("Liikkuva Auto"), Description("Auton nopeus"), DefaultValue(5), Browsable(true)] public int nopeus { get { return p_nopeus; } set { p_nopeus = value; } } private int p_nopeus = 10; private System.Windows.Forms.Timer ajastin = new System.Windows.Forms.Timer(); public Tormays tormays; public Rikki rikki; private int p_kunto = 10; private int tormayksia = 0; private bool p_random_sijainti = false; [Category("Liikkuva Auto"), Description("Auton alkukunto"), DefaultValue(10), Browsable(true)] public int kunto { get { return p_kunto; } set { if ( value >= 0 ) p_kunto = value; } } [Category("Liikkuva Auto"), Description("Arvotaanko satunnainen alkusijainti autolle"), DefaultValue(false), Browsable(true)] public bool random_sijainti { get { return p_random_sijainti; } set { p_random_sijainti = value; } } private bool p_random_kunto = true; [Category("Liikkuva Auto"), Description("Arvotaanko satunnainen kunto autolle"), DefaultValue(true), Browsable(true)] public bool random_kunto { get { return p_random_kunto; } set { p_random_kunto = value; } } public LiikkuvaAuto() { InitializeComponent(); this.ParentChanged += new System.EventHandler(this.OnParentChanged); this.TabStop = false; if (random_kunto) { Random r = new Random(); kunto = r.Next(1, kunto); } } // parentiin eli tässä tapauksessa lomakkeeseen voidaan viitata vasta, kun kontrolli on lisätty lomakkeelle // eli ei vielä suoraan konstruktorissa vaan esim. ParentChanged-tapahtuman jälkeen private void OnParentChanged(object sender, EventArgs e) { if (Parent == null) return; if (this.DesignMode != true) { ajastin.Enabled = true; ajastin.Tick += new System.EventHandler(this.ajastin_Tick); } if (random_sijainti == false) return; Random r = new Random(); this.Location = new System.Drawing.Point(r.Next(0, Parent.ClientSize.Width - ClientSize.Width), r.Next(0, Parent.ClientSize.Height - ClientSize.Height)); } private void ajastin_Tick(object sender, EventArgs e) { if (this.DesignMode == true) return; if (kunto > 0) { int vanhanopeus = nopeus; if (Left <= 0) nopeus = -nopeus; if (Right >= Parent.ClientSize.Width) nopeus = -nopeus; if (vanhanopeus != nopeus) { tormayksia++; kunto--; if (tormays != null) tormays(kunto, tormayksia); if (rikki != null && kunto == 0) { AutoEventArgs ee = new AutoEventArgs(tormayksia); rikki(this, ee); } if ( kunto == 0) return; } Left = Left + nopeus; } } } public class AutoEventArgs : EventArgs { private int tormaykset = 0; public int tormayksia { get { return tormaykset; } set { if (value > 0) tormaykset = value; } } public AutoEventArgs(int torm = 1) { tormayksia = torm; } } }