В прикладном окне ездят несколько машин, которые движутся по кольцевой дороге. Проблема в окне Interface, созданного для выведения на экран состояния объектов, при нажатии на запуск/остановку машин это не выводиться на экран состояния, выводиться только после добавления/удаления автомобиля.
Код | using System; using System.Text; using System.Windows.Forms; using System.Threading; using System.Drawing; using System.Collections.Generic; using System.Collections;
namespace KURSOVAYA {
delegate void delEv();
class Car //класс машины { public event delEv ev; int num; //номер машины int speed; //скорость машины int r; //радиус кольца string name; //имя машины int x, y; //текущая позиция машины bool great, //признак движения по большому кругу life; //жизнь потока Thread t1; //поток bool run; bool moving, onrefuel, oncirclesmallroad; int indikator, //индикатор наполнения бензобака max_indikator; //public Image img; public ArrayList aL; int i; Rectangle station; public Car(int N, string Name, int X, int Y, bool greatNew) { //img = Image.FromFile("image/car.jpg"); num = N; name = Name; speed = 2; x = X; y = Y; great = greatNew; run = false; life = false; moving = false; indikator = 0; max_indikator = 20; X = station.Right; Y = station.Top + station.Height / 2; Start();// } //------------ ~Car() { life = false; } // Деструктор
public void Start() // Стартовать { if (!run) { run = true; life = true; t1 = new Thread(new ThreadStart(Move)); t1.Start(); } }
public void Suspend() // Приостановить { moving = true; /*if (run) { run = false; t1.Suspend(); }*/ }
public void Resume() // Возобновить { lock (this) { moving = false; Monitor.Pulse(this); } /*if (!run) { run = true; t1.Resume(); }*/ } //------------ public int N { get { return num; } } public int X //свойство координаты X центра машины { get { return x; } } public int Y //свойство координаты Y центра машины { get { return y; } }
int counter; // время существования void Move() //движение { while (life) { counter++; if (great) OnCirclebigroad(); if (!great) OnCirclesmallroad(); if (oncirclesmallroad) OnCirclesmallroad(); if (onrefuel) OnRefuel(); if (ev != null) ev(); Thread.Sleep(100); lock (this) { if (moving) Monitor.Wait(this); } } }
void OnCirclebigroad() //движение по большому кругу { r = 160; x = 170 + (int)Math.Round(r * Math.Cos(counter * 0.1 * speed)); y = 170 + (int)Math.Round(r * Math.Sin(counter * 0.1 * speed)); Console.WriteLine("X=" + x + "Y=" + y + "R=" + r); if (X < station.Right && X > station.Left && Y > station.Top && Y < station.Bottom) { speed = -speed; great = false; onrefuel = true; Console.WriteLine("onstation"); } /*if (counter == 64) { great = false; counter = 0; }*/
}
void OnCirclesmallroad() //движение по малому кругу { r = 120; x = 170 + (int)Math.Round(r * Math.Cos(counter * 0.1 * -1 * speed)); y = 170 + (int)Math.Round(r * Math.Sin(counter * 0.1 * -1 * speed)); Console.WriteLine("X=" + x + "Y=" + y + "R=" + r); if (X < station.Right && X > station.Left && Y > station.Top && Y < station.Bottom) { speed = -speed; oncirclesmallroad = false; onrefuel = true; Console.WriteLine("onstation"); } /*if (counter == 64) { great = true; counter = 0; }*/ }
void OnRefuel() //заправка машины { indikator++; if (indikator == max_indikator) { onrefuel = false; if (i % 2 == 1) { great = true; } else { great = false; } Console.WriteLine("oncircleroad"); } Console.WriteLine("X=" + (aL[i] as Car).X + " indikator=" + indikator); indikator = 0; }
public void Finish() { life = false; } }
class Cars : Form { public ArrayList aL; public int n, c; // кол-во машин //Image PetrolSt;
public void HandlerEv() // Обработчик события ev { Console.WriteLine(" HandlerEv"); Invalidate(); }
public Cars() { //PetrolSt = Image.FromFile("image/petrol.jpg"); n = 2; this.DoubleBuffered = true; aL = new ArrayList(n); for (int i = 0; i < aL.Capacity; i++) { if (i % 2 == 1) { Car c = new Car(i, "Машина", 165, 330, true); c.ev += new delEv(HandlerEv); aL.Add(c); } else { Car c = new Car(i, "Машина", 312, 96, false); c.ev += new delEv(HandlerEv); aL.Add(c); } } Text = "Cars"; Start(); } //------------- public void Start() // Стартовать { for (int i = 0; i < aL.Count; i++) { (aL[i] as Car).Start(); } } public void Suspend() // Возобновить { for (int i = 0; i < aL.Count; i++) { (aL[i] as Car).Suspend(); } //Invalidate(); } //--------------- public void Resume() // Приостановить { for (int i = 0; i < aL.Count; i++) { (aL[i] as Car).Resume(); } //Invalidate(); }
//--------------
/* void HandlerEv() { Invalidate(); }*/
protected override void OnPaint(PaintEventArgs e) //рисование {
e.Graphics.DrawEllipse(new Pen(Color.Black, 40), 20, 20, 320, 320); e.Graphics.DrawEllipse(new Pen(Color.Black, 40), 65, 65, 230, 230); e.Graphics.FillRectangle(new SolidBrush(Color.Brown), 370, 100, 70, 170); for (int i = 0; i < aL.Count; i++) { //рисование машины e.Graphics.DrawRectangle(new Pen(Color.Red, 4), (aL[i] as Car).X, (aL[i] as Car).Y, 20, 20); //e.Graphics.DrawRectangle(new Pen(Color.Green, 4), pCar[i].X, pCar[i].Y, 20, 20); e.Graphics.DrawString((aL[i] as Car).N.ToString(), Font, new SolidBrush(Color.Blue), (aL[i] as Car).X + 4, (aL[i] as Car).Y + 4); //e.Graphics.DrawRectangle(new Pen(Color.Blue, 4), pCar[i].X, pCar[i].Y, 20, 20); } } protected override void OnClosed(EventArgs e) //закрытие { //for (int i = 0; i < aL.Count; i++) // aL[i].Finish();
} }
class User : Cars // Класс пользователя машин { private bool run; public int i; Form pChildForm, Interface; Button pBut, pBut2, pBut3; TextBox Text0; private int rzm = 10;
public User() { run = true; //--------------- pBut = new Button(); pBut.Location = new Point(32, 24); pBut.Name = "pBut"; pBut.Size = new System.Drawing.Size(120, 30); pBut.Text = "Suspend/Resume"; pBut.Click += new EventHandler(OnBut); //--------------- pBut2 = new Button(); pBut2.Location = new Point(120, 24); pBut2.Name = "pBut"; pBut2.Size = new System.Drawing.Size(120, 30); pBut2.Text = "Delete"; pBut2.Click += new EventHandler(Delete); //--------------- pBut3 = new Button(); pBut3.Location = new Point(210, 24); pBut3.Name = "pBut"; pBut3.Size = new System.Drawing.Size(120, 30); pBut3.Text = "Add a car"; pBut3.Click += new EventHandler(Add); ClientSize = new System.Drawing.Size(200, 150); //--------------- pChildForm = new Form(); pChildForm.Location = new Point(500, 500); pChildForm.Size = new Size(800, 450); pChildForm.Text = "User"; pChildForm.Show(); pChildForm.Controls.Add(pBut); pChildForm.Controls.Add(pBut2); pChildForm.Controls.Add(pBut3); Text0 = new TextBox(); Text0.Location = new Point(200, 60); Text0.Name = "T0"; Text0.Size = new System.Drawing.Size(80, 20); pChildForm.ClientSize = new System.Drawing.Size(350, 100); pChildForm.Controls.Add(Text0); //-----------------Interface-------------- Interface = new Form(); // Создать дочернее окно (форму) Interface.Location = new Point(700, 100);// и разместить его. Interface.Size = new Size(600, 600); // Определить раз-мер Interface.Text = "Interface"; // Задать заголовок дочернего окна Interface.Show(); // Показать дочернее окно Interface.ClientSize = new System.Drawing.Size(500, 250); Interface.Paint += new PaintEventHandler(Interface_Paint); } //------------------------------ void Interface_Paint(object sender, PaintEventArgs e) { for (int i = 0; i < aL.Count; i++) { Car car = (Car)aL[i]; e.Graphics.DrawString("Машина №" + i, new System.Drawing.Font("Arial", 10), new SolidBrush(Color.Red), new Point(rzm, 100)); Interface.Update(); if (run) { e.Graphics.DrawString("Машина запущена", new System.Drawing.Font("Arial", 8), new SolidBrush(Color.Red), new Point(rzm, 60)); rzm = rzm + 130; Interface.Update(); } else { e.Graphics.DrawString("Машина остановлена", new System.Drawing.Font("Arial", 8), new SolidBrush(Color.Red), new Point(rzm, 60)); rzm = rzm + 130; Interface.Update(); } } } private void HandlerEv() // Обработать событие { rzm = 10; Interface.Invalidate(); }
//--------------- void OnBut(object obj, EventArgs e) // Обработчик кнопки { Console.WriteLine("OkMouse"); if (run) { run = false; Suspend(); } else if (!run) { run = true; Resume(); } Interface.Invalidate(); } //--------------- void Add(object obj, EventArgs e) { Random rand = new Random(); for (int i = 0; i < Convert.ToInt32(Text0.Text); i++) { if (rand.Next(10) % 2 == 1) { Car c = new Car(i, "Машина", 165, 330, true); c.ev += new delEv(HandlerEv); (aL[i] as Car).Start(); aL.Add(c); } else { Car c = new Car(i, "Машина", 312, 96, false); c.ev += new delEv(HandlerEv); (aL[i] as Car).Start(); aL.Add(c); } } Update(); rzm = 10; Interface.Invalidate(); //i++; }
void Delete(object obj, EventArgs e) { for (int i = 0; i < Convert.ToInt32(Text0.Text); i++) { if (aL.Count != 0) { aL.RemoveAt(aL.Count - 1); Update(); rzm = 10; Interface.Invalidate(); //i--; } } }
/* class Refill { public int station; private bool run; pubic Refill() { run = true; } }*/ //--------------- static void Main() //самая главная функция { Cars aL = new Cars(); Application.Run(new User()); //for (int i = 0; i < aL.Count; i++) // Завершить потоки //aL[i].Finish();
} } }
|
|