Exemplo n.º 1
0
        public string Post(cars car)
        {
            try
            {
                string query = @"insert into dbo.Car values ( '" + car.Car_Brand + @"',
                                                              '" + car.Car_Type + @"',
                                                              '" + car.Date_Of_Purchased + @"',
                                                              '" + car.PhotoFileName + @"'

                                                             )";

                DataTable table = new DataTable();
                using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["carsAppDB"].ConnectionString))
                    using (var cmd = new SqlCommand(query, con))
                        using (var da = new SqlDataAdapter(cmd))
                        {
                            cmd.CommandType = CommandType.Text;
                            da.Fill(table);
                        }

                return("Added Successfully! ");
            }

            catch (Exception)
            {
                return("Fail to Add");
            }
        }
Exemplo n.º 2
0
        //field versus properties : https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property

        private void btnComposeCarObjects_Click(object sender, RoutedEventArgs e)
        {
            cars car_1 = new cars();

            cars car_2 = new cars {
                irCarPrice = 250, irCarWeight = 250, srCarBrand = "BMW", srCarColor = "Red", srCarModel = "BMW 228", irProductionYear = 1825, lstRepairYears = new List <int> {
                    1775, 1900, 1645, 1925, 1999
                }
            };

            car_2.saveToAFile("car2.txt");

            //MessageBox.Show("production year " + car_2.irProductionYear);

            cars car_3 = new cars();

            car_3.irCarPrice       = 5000;
            car_3.irCarWeight      = 2500;
            car_3.irProductionYear = 2000;
            car_3.srCarBrand       = "Ford";
            car_3.srCarColor       = "White";
            car_3.srCarModel       = "Ford Escape Hybrid";
            car_3.lstRepairYears   = new List <int>();
            car_3.lstRepairYears.Add(1950);
            car_3.lstRepairYears.Add(2005);


            List <cars> lstMyCars = new List <cars> {
                car_1, car_2, car_3
            };

            lstMyCars.saveToFileCarsList("cars_list.txt");

            File.WriteAllText(@"cars_list_json.txt", JsonConvert.SerializeObject(lstMyCars));
        }
Exemplo n.º 3
0
        public string Put(cars car)
        {
            try
            {
                string query = @"update dbo.Car set 
                                Car_Brand='" + car.Car_Brand + @"', 
                                Car_Type='" + car.Car_Type + @"',
                                Company'" + car.Company + @"',
                                Date_Of_Purchase='" + car.Date_Of_Purchased + @"',
                                PhotoFileName='" + car.PhotoFileName + @"'
                                where CarID =" + car.CarID + @"";

                DataTable table = new DataTable();
                using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["carsAppDB"].ConnectionString))
                    using (var cmd = new SqlCommand(query, con))
                        using (var da = new SqlDataAdapter(cmd))
                        {
                            cmd.CommandType = CommandType.Text;
                            da.Fill(table);
                        }

                return("Updated Successfully! ");
            }

            catch (Exception)
            {
                return("Fail to Update");
            }
        }
Exemplo n.º 4
0
        public JsonResult AracKayit(cars formdata)
        {
            int sonuc = 1;

            if (Helpers.Kullanici.GirisKontrol())
            {
                try
                {
                    rentacarEntities db        = new rentacarEntities();
                    cars             YeniKayit = new cars();
                    YeniKayit.brand     = formdata.brand;
                    YeniKayit.color     = formdata.color;
                    YeniKayit.img       = formdata.img;
                    YeniKayit.km        = formdata.km;
                    YeniKayit.model     = formdata.model;
                    YeniKayit.modelyear = formdata.modelyear;
                    YeniKayit.period    = formdata.period;
                    YeniKayit.price     = formdata.price;
                    YeniKayit.title     = formdata.title;
                    db.cars.Add(YeniKayit);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    sonuc = 0;
                }
            }
            else
            {
                sonuc = 2;
            }
            return(Json(sonuc));
        }
Exemplo n.º 5
0
            public object Clone()
            {
                cars c = new cars(name, color, year, price, count, petrol, dvs, timeToHundred);

                dvs = (engine)dvs.Clone();
                return(c);
            }
Exemplo n.º 6
0
        public HttpResponseMessage updateAUser(int id, cars updateCar)
        {
            if (Thread.CurrentPrincipal.Identity.AuthenticationType == "Admin")
            {
                if (db.cars.Any(car => car.id == id))
                {
                    cars car = db.cars.FirstOrDefault(cars => cars.id == id);

                    car.typeNumber = updateCar.typeNumber;
                    car.currentKM  = updateCar.currentKM;
                    car.proper     = updateCar.proper;
                    car.available  = updateCar.available;
                    car.carNumber  = updateCar.carNumber;


                    db.SaveChanges();
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Инициализация:\n");
            engine dvs1  = new engine("No_Name", 50, 150, 0, 1000);           // конструктор со всеми параметрами
            cars   avto1 = new cars("no_name", "no_color", 2020, 1000, dvs1); // конструктор со всеми параметрами
            engine dvs2  = new engine("No_Name");                             // конструктор с одним параметром
            cars   avto2 = new cars(dvs2);                                    // конструктор с одним параметром
            cars   avto3 = new cars();                                        // конструктор без параметров

            avto1.OutputCars();
            avto1.PutCars();
            Console.WriteLine("\nДанные после ввода:");
            avto1.OutputCars();
            int ProbegFirst = 1;// инициализация переменной для возврата через ref

            avto1.Drive(ref ProbegFirst);
            Console.WriteLine("\nПробег после тест-драйва: ");
            Console.WriteLine(ProbegFirst);
            avto1.Modern(100, 200, 500);
            Console.WriteLine("\n\nПосле модернизации:");
            avto1.OutputCars();
            // объявление и инициализация массива автомобилей
            engine[] arrayE = new engine[2];
            cars[]   arrayC = new cars[2];
            for (int i = 0; i < arrayC.Length; i++)
            {
                arrayE[i] = new engine("no_name", 10, 100, 0, 200);
                arrayC[i] = new cars("no_name", "no_color", 2020, 1000, arrayE[i]);
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].OutputCars();
            }
            Console.WriteLine("\nВвод данных:");
            for (int i = 0; i < arrayC.Length; i++)// заполнение массива
            {
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].PutCars();
            }
            Console.WriteLine("\nДанные после ввода:");
            for (int i = 0; i < arrayC.Length; i++)// заполнение массива
            {
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].OutputCars();
            }
            Console.WriteLine("\nПробег после тест-драйва: ");
            for (int i = 0; i < arrayC.Length; i++)// возвращаемы параметр через out
            {
                int ProbegTwo;
                arrayC[i].DriveTwo(out ProbegTwo);
                Console.WriteLine("\nМашина " + (i + 1) + ": " + ProbegTwo + "КМ");
            }
            Console.WriteLine("\nПосле модернизации: ");
            for (int i = 0; i < arrayC.Length; i++)
            {
                arrayC[i].Modern(100, 200, 500);
                Console.WriteLine("\n");
                arrayC[i].OutputCars();
            }
            Console.ReadLine();
        }
Exemplo n.º 8
0
        public static void loadCarsFromFile(this List <cars> lstMyCars, string srFileName)
        {
            var vrAllFile = File.ReadAllText(srFileName);

            foreach (var vrPerCarObject in vrAllFile.Split(srCarObjectSeperator))
            {
                cars tempCar = new cars();
                tempCar.loadFromFile(vrPerCarObject, true);
                lstMyCars.Add(tempCar);
            }
        }
Exemplo n.º 9
0
        public void HandleCars(List <PatrolLastLocationDTO> availableCars)
        {
            var crispCars = new cars();

            crispCars.C   = availableCars.Count().ToString();
            crispCars.car = new carsCar[availableCars.Count];
            var index = 0;

            foreach (var item in availableCars)
            {
                crispCars.car[index] = new carsCar
                {
                    c  = (index + 1).ToString(),
                    id = item.PatrolId.ToString(),
                    S  = "0",
                    X  = item.Longitude ?? 0,
                    Y  = item.Latitude ?? 0
                };
                index++;
            }
            XmlSerializer serializer   = new XmlSerializer(typeof(cars));
            var           stringwriter = new System.IO.StringWriter();

            //var xmlWriter = new XmlWriter();
            serializer.Serialize(stringwriter, crispCars);
            // XmlWriterSettings settings = new XmlWriterSettings();
            //settings.OmitXmlDeclaration = true;

            //MemoryStream ms = new MemoryStream();
            //XmlWriter writer = XmlWriter.Create(ms, settings);

            //XmlSerializerNamespaces names = new XmlSerializerNamespaces();
            //names.Add("", "");

            //XmlSerializer cs = new XmlSerializer(typeof(cars));

            //cs.Serialize(writer, crispCars, names);

            //ms.Flush();
            //ms.Seek(0, SeekOrigin.Begin);
            //StreamReader sr = new StreamReader(ms);
            //var xml = sr.ReadToEnd();
            //var sessionName = GetActiveSession();
            var allSessions = _client.listSessions();

            if (allSessions != null)
            {
                foreach (var item in allSessions)
                {
                    ParseCars(item.id, stringwriter.ToString());
                }
            }
        }
Exemplo n.º 10
0
        private void btnLoadCarFromFile_Click(object sender, RoutedEventArgs e)
        {
            cars myCar2 = new cars();

            myCar2.loadFromFile("car2.txt");

            List <cars> lstMyCars = new List <cars>();

            lstMyCars.loadCarsFromFile("cars_list.txt");

            List <cars> lstMyCars_json = new List <cars>();

            lstMyCars_json = JsonConvert.DeserializeObject <List <cars> >(File.ReadAllText("cars_list_json.txt"));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            cars = await _context.cars
                   .Include(c => c.mans).FirstOrDefaultAsync(m => m.CID == id);

            if (cars == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Exemplo n.º 12
0
        private void apply_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Place == 0)
            {
                MessageBox.Show("Nie wybrano miejsca!");
            }
            else
            {
                if (editMode == true)
                {
                    editedCar.parking = Place;
                    cars auto = (from m in _db.cars where m.id == editedCar.id select m).Single();
                    auto.parking = Place;
                    _db.SaveChanges();
                }
                else
                {
                    Car.parking = Place;
                    Console.WriteLine(Car.model);
                    Console.WriteLine(Car.parking);
                    cars newCar = new cars();
                    newCar.make     = Car.make;
                    newCar.model    = Car.model;
                    newCar.price    = Convert.ToInt32(Car.price);
                    newCar.margin   = Car.margin;
                    newCar.mileage  = Car.mileage;
                    newCar.power    = Convert.ToInt32(Car.power);
                    newCar.year     = Convert.ToInt32(Car.year);
                    newCar.trany    = Car.trany;
                    newCar.parking  = Car.parking;
                    newCar.desc     = Car.desc;
                    newCar.displ    = Car.displ;
                    newCar.fuelType = Car.fuelType;
                    newCar.parking  = Place;

                    Random rand = new Random();
                    int    hr   = rand.Next(1, 9);
                    int    min  = rand.Next(1, 59);
                    ts1.timerClock(newCar, new TimeSpan(hr, min, 1), ts1.timersList.Count());
                    ts1.tempParkingSlots.Add(Place);
                    ts1.timerColumnNbr++;

                    MessageBox.Show("Pomyslnie dodano pojazd do oferty!");
                    Switcher.Switch(new MainListView(true));
                }
            }
        }
Exemplo n.º 13
0
 public HomeModule()
 {
     Get["/"] = _ => View["index.cshtml"];
     Get["/view_all_cars"] = _ => {
         List <cars> allCar = cars.ShowInventory();
         return(View["view_all_cars.cshtml", allCar]);
     };
     Post["/cars_added"] = _ => {
         cars newCar = new cars(Request.Form["model"], Request.Form["miles"], Request.Form["price"]);
         newCar.Save();
         return(View["cars_added.cshtml", newCar]);
     };
     Post["/car_cleared"] = _ => {
         cars.ClearAll();
         return(View["car_cleared.cshtml"]);
     };
 }
Exemplo n.º 14
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            cars = await _context.cars.FindAsync(id);

            if (cars != null)
            {
                _context.cars.Remove(cars);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            cars = await _context.cars
                   .Include(c => c.mans).FirstOrDefaultAsync(m => m.CID == id);

            if (cars == null)
            {
                return(NotFound());
            }
            ViewData["MID"] = new SelectList(_context.Manufacturers, "MID", "MID");
            return(Page());
        }
Exemplo n.º 16
0
        // Sing: Function to retrieve car details details from the database based on the care hire name.
        //This function returns a structure of car rental details
        public static cars getCarDetails(string carHire)
        {
            //Sing: Database connection string declarations
            System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
            DataTable       dtable  = new DataTable();
            OleDbCommand    command = new OleDbCommand();
            OleDbDataReader reader;

            //Sing : Login database connection
            connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=PrimaryDB.mdb;Jet OLEDB:Database Password=;";
            command.Connection          = connection;

            connection.Open();
            //Sing: SQL database query string
            string query = "SELECT * FROM Cars WHERE CarRentalCompany ='" + carHire + "'";

            command.CommandText = query;
            reader = command.ExecuteReader();

            //Sing: Instantiating a new car structure
            cars carDetails = new cars();

            //Sing: Get all details of car rental
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    if (reader["CarRentalCompany"].ToString() == carHire)
                    {
                        carDetails.numPlate    = reader["NumberPlate"].ToString();
                        carDetails.carMake     = reader["Make"].ToString();
                        carDetails.carModel    = reader["Model"].ToString();
                        carDetails.carType     = reader["CarType"].ToString();
                        carDetails.gearBox     = reader["GearBox"].ToString();
                        carDetails.seats       = reader["Seats"].ToString();
                        carDetails.pricePerDay = reader["pricePerDay"].ToString();
                    }
                }
                reader.Close();
            }
            connection.Close();
            //return car details
            return(carDetails);
        }
Exemplo n.º 17
0
        private void btnTestReadOnlyandConstant_Click(object sender, RoutedEventArgs e)
        {
            //this below would throw error because you cant change value of readonly object after intilization or constructor of static class
            //srSplitValueSeperator = "custom stuff";

            //this below would throw error because you cant change value of constant object after first definition
            //irConstNum = 200;

            //cars.srCarManufacturer this would throw error
            cars myTempCar = new cars();
            var  carm      = myTempCar.srCarManufacturer;

            var carm2 = cars.srCarManufacturer_v2;

            var carm3 = cars.srCarManufacturer_v3;

            cars.srCarManufacturer_v3 = "Global v2";

            //constant vs readonly https://www.pluralsight.com/guides/const-vs-readonly-vs-static-csharp
        }
Exemplo n.º 18
0
        public HttpResponseMessage DeleteUsers(int id)
        {
            if (Thread.CurrentPrincipal.Identity.AuthenticationType == "Admin")
            {
                cars cars = db.cars.FirstOrDefault(car => car.id == id);
                if (cars == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                db.cars.Remove(cars);
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
Exemplo n.º 19
0
        public ParkingMap(cars Car)
        {
            editMode       = true;
            this.editedCar = Car;
            InitializeComponent();
            parkingButton.IsEnabled = false;
            isItBusy();
            string name         = "P" + editedCar.parking.ToString();
            object parkingPlace = ParkingSlots.FindName(name);

            if (parkingPlace is Button)
            {
                Console.WriteLine("P" + editedCar.parking.ToString());
                Button button = parkingPlace as Button;
                button.Background = Brushes.Red;
            }
            else
            {
                Console.WriteLine("P" + editedCar.parking.ToString());
            }
        }
Exemplo n.º 20
0
        public HomeModule()
        {
            Get["/"] = _ => View["index.cshtml"];
            Get["/view_all_cars"] = _ => {
                List <cars> allCar = cars.ShowInventory();
                return(View["view_all_cars.cshtml", allCar]);
            };

            Get["/update_car/{id}"] = parameters => {
                cars car = cars.Find(parameters.id);
                return(View["update_car.cshtml", car]);
            };

            Post["/update_car/{id}"] = parameters => {
                cars        car    = cars.Find(parameters.id);
                List <cars> allCar = cars.ShowInventory();
                cars        newCar = new cars(Request.Form["model"], Request.Form["miles"], Request.Form["price"]);
                allCar[parameters.id] = newCar;
                return(View["update_car.cshtml", newCar]);
            };

            Post["/cars_added"] = _ => {
                cars newCar = new cars(Request.Form["model"], Request.Form["miles"], Request.Form["price"]);
                newCar.Save();
                return(View["cars_added.cshtml", newCar]);
            };

            Post["/car_cleared"] = _ => {
                cars.ClearAll();
                return(View["car_cleared.cshtml"]);
            };

            // Post["/update_car/{id}"] = parameters => {
            //   List<cars> allCar = cars.ShowInventory();
            //   allCar[parameters.id].GetModel = (Request.Form["model"]);
            //   allCar[parameters.id].GetMiles = (Request.Form["miles"]);
            //   allCar[parameters.id].GetPrice = (Request.Form["price"]);
            //   return View["update_car.cshtml", car];
            // };
        }
Exemplo n.º 21
0
        public HttpResponseMessage PostUsers(cars car)
        {
            if (Thread.CurrentPrincipal.Identity.AuthenticationType == "Admin")
            {
                cars newcar = new cars();
                newcar.typeNumber = car.typeNumber;
                newcar.currentKM  = car.currentKM;
                newcar.proper     = car.proper;
                newcar.available  = car.available;
                newcar.carNumber  = car.carNumber;


                db.cars.Add(newcar);
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
Exemplo n.º 22
0
        private void car_btn_Click(object sender, EventArgs e)
        {
            Auto_data.Clear();
            XmlDocument xml = new XmlDocument();

            xml.Load("autok.xml");
            dataGridView1.DataSource = Auto_data;


            foreach (XmlElement element in xml.DocumentElement)
            {
                var car = new cars();
                Auto_data.Add(car);

                car.Gyártó = element.GetAttribute("marka");

                var childElement = (XmlElement)element.ChildNodes[0];
                car.Típus       = childElement.GetAttribute("tipus");
                car.Szín        = childElement.GetAttribute("szin");
                car.Gyártás_éve = childElement.GetAttribute("evjarat");
            }
        }
Exemplo n.º 23
0
        static void Main()
        {
            Console.WriteLine("Hello Humans, Im Watching You.");
            cars C = new cars();

            //Console.WriteLine("\nInternal Collection (Unsorted - IEnumerable,Enumerator)\n");
            //foreach (car c in C)
            //{Console.WriteLine(c.Make + "\t\t" + c.Year);}
            foreach (car c in C)
            {
                string carString = (c.Make + " " + c.Year);
                DisplayStringWithBorder(carString);
            }
            Console.ReadLine();

            foreach (var item in C)
            {
                DisplayStringWithBorder(item.ToString());
            }



            string[] animals = { "Cat", "Alligator", "fox", "donkey", "Cat", "alligator" };
            foreach (var item in animals)
            {
                DisplayStringWithBorder(item.ToString());
            }
            MyClass myClass1 = new MyClass("string1", "string2", 400);

            Console.WriteLine("int1 {0} \nstring1 {1} \nstring2 {2}", myClass1.myClassInt1, myClass1.myClassString1, myClass1.myClassString2);
            Console.ReadLine();

            Array.ForEach(animals, DisplayStringWithBorder);


            HelloWorld();
            ///Pinfo();
        }
Exemplo n.º 24
0
        public JsonResult AracDuzenle(cars formdata)
        {
            int sonuc = 1;

            if (Helpers.Kullanici.GirisKontrol())
            {
                try
                {
                    rentacarEntities db  = new rentacarEntities();
                    cars             bul = db.cars.Where(w => w.id == formdata.id).FirstOrDefault();
                    if (bul == null)
                    {
                        sonuc = 3;
                        return(Json(sonuc));
                    }
                    bul.brand     = formdata.brand;
                    bul.color     = formdata.color;
                    bul.img       = formdata.img;
                    bul.km        = formdata.km;
                    bul.model     = formdata.model;
                    bul.modelyear = formdata.modelyear;
                    bul.period    = formdata.period;
                    bul.price     = formdata.price;
                    bul.title     = formdata.title;
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    sonuc = 0;
                }
            }
            else
            {
                sonuc = 2;
            }
            return(Json(sonuc));
        }
Exemplo n.º 25
0
 public BuyerDataForm(cars Car)
 {
     this.Car = Car;
     InitializeComponent();
 }
Exemplo n.º 26
0
    static void Main()
    {
        //console settings
        Console.BufferHeight = Console.WindowHeight;
        Console.BufferWidth = Console.WindowWidth;
        Console.CursorVisible = false;

        //used for centering the text
        string text;

        text = "CAR GAME";
        Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, 0);
        Console.WriteLine(text);

        text = "Press 1 for seven lanes (easiest)";
        Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 - 2);
        Console.WriteLine(text);

        text = "Press 2 for five lanes (harder)";
        Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 - 1);
        Console.WriteLine(text);

        text = "Press 3 for three lanes (hardest)";
        Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2);
        Console.WriteLine(text);

        text = "Press E to exit";
        Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 + 1);
        Console.WriteLine(text);

        text = "The game will pause on Spacebar";
        Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 + 3);
        Console.WriteLine(text);

        string lanes;
        string difficulty;
        int leftmostLane;
        int rightmostLane;

        while (true)
        {
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo pressedKey = Console.ReadKey(true);
                if ((pressedKey.Key == ConsoleKey.NumPad1) || (pressedKey.Key == ConsoleKey.D1))
                {
                    lanes = "I       I";
                    leftmostLane = Console.BufferWidth / 2 - 3;
                    rightmostLane = leftmostLane + (lanes.Length - 2);
                    difficulty = "seven lanes";
                    break;
                }
                else if ((pressedKey.Key == ConsoleKey.NumPad2) || (pressedKey.Key == ConsoleKey.D2))
                {
                    lanes = "I     I";
                    leftmostLane = Console.BufferWidth / 2 - 2;
                    rightmostLane = leftmostLane + (lanes.Length - 2);
                    difficulty = "five lanes";
                    break;
                }
                else if ((pressedKey.Key == ConsoleKey.NumPad3) || (pressedKey.Key == ConsoleKey.D3))
                {
                    lanes = "I   I";
                    leftmostLane = Console.BufferWidth / 2 - 1;
                    rightmostLane = leftmostLane + (lanes.Length - 2);
                    difficulty = "three lanes";
                    break;
                }
                else if ((pressedKey.Key == ConsoleKey.E))
                {
                    Console.Clear();
                    return;
                }
            }
        }

        Random Randomizer = new Random();

        //how many other (lethal) cars will there be
        int carsCount = Console.BufferHeight / 2 + 2;

        //lower acceleration means faster gameplay
        int harder = 1;
        int sleepTime = 200;

        //gameplay stuff
        int lives = 5;
        int maxLives = lives;
        int gameScore = 0;
        bool carCrash = false;

        //the density variable decides how sparse/abundant will the other cars be (buggy, change at your own risk)
        int density = 2;

        //initiliazing the player's car and adding some info about it
        cars playerCar = new cars();
        playerCar.symbol = '#';
        playerCar.color = ConsoleColor.Yellow;
        playerCar.X = Console.BufferWidth / 2;
        playerCar.Y = Console.BufferHeight - 1;

        //initializing the other cars array and setting some initial random values
        cars[] otherCars = new cars[carsCount];
        for (int i = 0, j = 0; i < carsCount; i++, j -= density)
        {
            otherCars[i].X = Randomizer.Next(leftmostLane, rightmostLane);
            otherCars[i].Y = j;
            otherCars[i].symbol = '&';
        }

        //initializing the bonus life bonus
        cars bonusLife = new cars();
        bonusLife.color = ConsoleColor.Green;
        bonusLife.symbol = '+';

        //initializing the slower speed bonus
        cars bonusSpeed = new cars();
        bonusSpeed.color = ConsoleColor.Red;
        bonusSpeed.symbol = '*';

        //initializing the clear screen bonus (bonusClear.color is missing, because it'll generate a new color on every iteration of the cycle)
        cars bonusClear = new cars();
        bonusClear.symbol = '@';

        Console.Clear();

        while (true)
        {
            //writing the road
            for (int i = 0; i < Console.BufferHeight; i++)
            {
                Console.SetCursorPosition(Console.BufferWidth / 2 - lanes.Length / 2, i);
                Console.Write(lanes);
            }

            //writing the other cars
            for (int i = 0, j = 0; i < otherCars.Length; i++)
            {
                if (otherCars[i].Y == Console.BufferHeight)
                {
                    j -= density;
                    otherCars[i].Y = j;
                    otherCars[i].X = Randomizer.Next(leftmostLane, rightmostLane);
                }
                else if (otherCars[i].Y >= 0)
                {
                    Console.SetCursorPosition(otherCars[i].X, otherCars[i].Y);
                    Console.Write(otherCars[i].symbol);
                    otherCars[i].Y++;
                }
                else if (otherCars[i].Y < 0)
                {
                    otherCars[i].Y++;
                }
            }

            //choose when to give the clear screen bonus
            if (Randomizer.Next(0, 200) == 23 && bonusClear.Y <= 0)
            {
                bonusClear.Y = 1;
                bonusClear.X = Randomizer.Next(leftmostLane, rightmostLane);
            }
            else if (bonusClear.Y == Console.BufferHeight)
            {
                bonusClear.Y = -1;
            }
            else if (bonusClear.Y > 0)
            {
                Console.SetCursorPosition(bonusClear.X, bonusClear.Y);
                Console.ForegroundColor = (ConsoleColor)Randomizer.Next(10, 16);
                Console.Write(bonusClear.symbol);
                bonusClear.Y++;
            }

            //choose when to give the +1 life bonus
            if (Randomizer.Next(0, 150) == 23 && bonusLife.Y <= 0)
            {
                bonusLife.Y = 1;
                bonusLife.X = Randomizer.Next(leftmostLane, rightmostLane);
            }
            else if (bonusLife.Y == Console.BufferHeight)
            {
                bonusLife.Y = -1;
            }
            else if (bonusLife.Y > 0)
            {
                Console.SetCursorPosition(bonusLife.X, bonusLife.Y);
                Console.ForegroundColor = bonusLife.color;
                Console.Write(bonusLife.symbol);
                bonusLife.Y++;
            }

            //choose when to give the slower game bonus
            if (Randomizer.Next(0, 100) == 23 && bonusSpeed.Y <= 0)
            {
                bonusSpeed.Y = 1;
                bonusSpeed.X = Randomizer.Next(leftmostLane, rightmostLane);
            }
            else if (bonusSpeed.Y == Console.BufferHeight)
            {
                bonusSpeed.Y = -1;
            }
            else if (bonusSpeed.Y > 0)
            {
                Console.SetCursorPosition(bonusSpeed.X, bonusSpeed.Y);
                Console.ForegroundColor = bonusSpeed.color;
                Console.Write(bonusSpeed.symbol);
                bonusSpeed.Y++;
            }

            //writing the player's car
            Console.SetCursorPosition(playerCar.X, playerCar.Y);
            if (carCrash)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("@");
                carCrash = false;
            }
            else
            {
                Console.ForegroundColor = playerCar.color;
                Console.Write(playerCar.symbol);
            }
            Console.ForegroundColor = ConsoleColor.White;

            //fixing the buggy road
            Console.SetCursorPosition(rightmostLane, Console.BufferHeight - 1);
            Console.Write("I");

            //moving the car
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo pressedKey = Console.ReadKey(true);
                if (pressedKey.Key == ConsoleKey.RightArrow)
                {
                    Console.SetCursorPosition(playerCar.X, playerCar.Y);
                    Console.Write(" ");
                    playerCar.X++;
                }
                else if (pressedKey.Key == ConsoleKey.LeftArrow)
                {
                    Console.SetCursorPosition(playerCar.X, playerCar.Y);
                    Console.Write(" ");
                    playerCar.X--;
                }
                else if (pressedKey.Key == ConsoleKey.UpArrow)
                {
                    Console.SetCursorPosition(playerCar.X, playerCar.Y);
                    Console.Write(" ");
                    playerCar.Y--;
                }
                else if (pressedKey.Key == ConsoleKey.DownArrow)
                {
                    Console.SetCursorPosition(playerCar.X, playerCar.Y);
                    Console.Write(" ");
                    playerCar.Y++;
                }
                else if (pressedKey.Key == ConsoleKey.Spacebar)
                {
                    text = "PAUSED, press Enter to continue.";
                    Console.SetCursorPosition(Console.BufferWidth - text.Length, Console.BufferHeight / 2);
                    Console.Write(text);
                    Console.ReadLine();
                    text = "                                ";
                    Console.SetCursorPosition(Console.BufferWidth - text.Length, Console.BufferHeight / 2);
                    Console.Write(text);
                }

                //making sure the player's car won't go off the road
                if (playerCar.X == leftmostLane - 1)
                {
                    playerCar.X++;
                }
                else if (playerCar.X == rightmostLane)
                {
                    playerCar.X--;
                }

                if (playerCar.Y == Console.BufferHeight)
                {
                    playerCar.Y--;
                }
                else if (playerCar.Y == -1)
                {
                    playerCar.Y++;
                }
            }

            //checking for collisions
            for (int i = 0; i < otherCars.Length; i++)
            {
                if (otherCars[i].Y == playerCar.Y && otherCars[i].X == playerCar.X)
                {
                    carCrash = true;
                    lives--;
                }
            }
            if (bonusSpeed.X == playerCar.X && bonusSpeed.Y == playerCar.Y)
            {
                sleepTime += 20;
                gameScore += 5;
                bonusSpeed.Y = -1;
            }
            if (bonusLife.X == playerCar.X && bonusLife.Y == playerCar.Y)
            {
                lives++;
                gameScore += 5;
                bonusLife.Y = -1;
            }
            if (bonusClear.X == playerCar.X && bonusClear.Y == playerCar.Y)
            {
                for (int i = 0, j = 0; i < carsCount; i++, j -= density)
                {
                    otherCars[i].Y = j;
                }
                bonusClear.Y = -1;
                gameScore += 5;
            }

            //ending the game
            if (lives == 0)
            {
                Console.Clear();

                text = "GAME OVER!";
                Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 - 2);
                Console.Write(text);

                text = "Score: " + gameScore;
                Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 - 1);
                Console.Write(text);

                text = "Maximum lives: " + maxLives;
                Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2);
                Console.Write(text);

                text = "Playing with " + difficulty + ".";
                Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight / 2 + 1);
                Console.Write(text);

                text = "Press Enter to continue...";
                Console.SetCursorPosition(Console.BufferWidth / 2 - text.Length / 2, Console.BufferHeight - 1);
                Console.Write(text);

                Console.ReadLine();
                return;
            }

            //writing the remaining lives
            Console.SetCursorPosition(0, 0);
            Console.Write("Lives: ");
            if (lives == 1)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.Write(lives);
                Console.BackgroundColor = ConsoleColor.Black;
            }
            else
            {
                Console.Write(lives);
            }

            //counter with the maximum lives
            if (maxLives < lives)
            {
                maxLives = lives;
            }

            //writing the game score
            text = "Score: " + gameScore;
            Console.SetCursorPosition(Console.BufferWidth - text.Length, 0);
            Console.Write(text);

            //writing the game speed
            Console.SetCursorPosition(0, Console.BufferHeight - 1);
            Console.Write("Speed: " + sleepTime + " (lower means faster)");

            //making the game harder (faster)
            if (harder % 10 == 0)
            {
                sleepTime--;
                gameScore += 1;
            }
            harder++;
            Thread.Sleep(sleepTime);
        }
    }
Exemplo n.º 27
0
        static Exception ex;// исключение класса ex
        static void Main(string[] args)
        {
            Console.WriteLine("Инициализация:\n");
            engine dvs  = new engine("No_Name", 50, 150, 0, 1000);          // конструктор со всеми параметрами
            cars   avto = new cars("no_name", "no_color", 2020, 1000, dvs); // конструктор со всеми параметрами

            avto.OutputCars();
            bool f;

            do
            {
                f = false;
                try { avto.PutCars(); }
                catch (FormatException ex)// обработка программного исключения
                {
                    f = true;
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Введите данные еще раз");
                }
                catch (Exception ex)// обработка пользовательского исключения
                {
                    f = true;
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Введите данные еще раз");
                }
            } while (f);
            Console.WriteLine("\nДанные после ввода:");
            avto.OutputCars();
            int probegAfterDrive = 0;

            try { probegAfterDrive = avto.Drive(10); }
            catch (Exception ex)// обработка пользовательского исключения
            {
                Console.WriteLine("Ошибка: " + ex.Message);
                Console.WriteLine("Завершение работы программы");
                Environment.Exit(1);
            }
            Console.Write("\nПробег после тест-драйва: ");
            Console.WriteLine(probegAfterDrive);
            try { avto.Modern(100, 200, 500); }
            catch (Exception ex)// обработка пользовательского исключения
            {
                Console.WriteLine("Ошибка: " + ex.Message);
                Console.WriteLine("Завершение работы программы");
                Environment.Exit(1);
            }
            Console.WriteLine("\n\nПосле модернизации:");
            avto.OutputCars();
            // объявление и инициализация массива автомобилей
            engine[] arrayE = new engine[2];
            cars[]   arrayC = new cars[2];
            for (int i = 0; i < arrayC.Length; i++)
            {
                arrayE[i] = new engine("no_name");
                arrayC[i] = new cars(arrayE[i]);
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].OutputCars();
            }
            Console.WriteLine("\nВвод данных:");
            for (int i = 0; i < arrayC.Length; i++)// заполнение массива
            {
                Console.WriteLine("\nМашина " + (i + 1));
                do
                {
                    f = false;
                    try { arrayC[i].PutCars(); }
                    catch (FormatException ex)
                    {
                        f = true;
                        Console.WriteLine("Ошибка: " + ex.Message);
                        Console.WriteLine("Введите данные еще раз");
                    }
                    catch (Exception ex)
                    {
                        f = true;
                        Console.WriteLine("Ошибка: " + ex.Message);
                        Console.WriteLine("Введите данные еще раз");
                    }
                } while (f);
            }
            Console.WriteLine("\nДанные после ввода:");
            for (int i = 0; i < arrayC.Length; i++)// заполнение массива
            {
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].OutputCars();
            }
            for (int i = 0; i < arrayC.Length; i++)
            {
                try { probegAfterDrive = arrayC[i].Drive(10); }
                catch (Exception ex)
                {
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Завершение работы программы");
                    Environment.Exit(1);
                }
            }
            Console.WriteLine("\nПробег после тест-драйва: ");
            for (int i = 0; i < arrayC.Length; i++)// возвращаемы параметр через out
            {
                Console.WriteLine("\nМашина " + (i + 1) + ": " + probegAfterDrive + "КМ");
            }
            for (int i = 0; i < arrayC.Length; i++)
            {
                try { arrayC[i].Modern(100, 200, 500); }
                catch (Exception ex)
                {
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Завершение работы программы");
                    Environment.Exit(1);
                }
            }
            Console.WriteLine("\nПосле модернизации: ");
            for (int i = 0; i < arrayC.Length; i++)
            {
                Console.WriteLine("\n");
                arrayC[i].OutputCars();
            }
            Console.ReadLine();
        }
Exemplo n.º 28
0
 static long masodperc(cars ido)
 {
     return(ido.hours * 3600 + ido.minutes * 60 + ido.seconds);
 }
Exemplo n.º 29
0
        static Exception ex;// исключение класса ex
        static void Main(string[] args)
        {
            const int Length = 2; // размер массива
            bool      f;          // флажок для зашиты от некорректного ввода
            int       probegAfterDrive = 0;

            // объявление и инициализация массива автомобилей
            engine[] arrayE = new engine[Length];
            cars[]   arrayC = new cars[Length];
            for (int i = 0; i < Length; i++)
            {
                arrayE[i] = new engine("no_name");
                arrayC[i] = new cars(arrayE[i]);
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].OutputCars();
            }
            Console.WriteLine("\nВвод данных:");
            for (int i = 0; i < Length; i++)// заполнение массива
            {
                Console.WriteLine("\nМашина " + (i + 1));
                do
                {
                    f = false;
                    try { arrayC[i].PutCars(); }
                    catch (FormatException ex)
                    {
                        f = true;
                        Console.WriteLine("Ошибка: " + ex.Message);
                        Console.WriteLine("Введите данные еще раз");
                    }
                    catch (Exception ex)
                    {
                        f = true;
                        Console.WriteLine("Ошибка: " + ex.Message);
                        Console.WriteLine("Введите данные еще раз");
                    }
                } while (f);
            }
            Console.WriteLine("\nДанные после ввода:");
            for (int i = 0; i < Length; i++)// заполнение массива
            {
                Console.WriteLine("\nМашина " + (i + 1));
                arrayC[i].OutputCars();
            }
            Console.WriteLine("\nПробег после тест-драйва: ");
            for (int i = 0; i < Length; i++)
            {
                try {
                    probegAfterDrive = arrayC[i].Drive(10);
                    Console.WriteLine("\nМашина " + (i + 1) + ": " + probegAfterDrive + "КМ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Завершение работы программы");
                    Environment.Exit(1);
                }
            }
            for (int i = 0; i < Length; i++)
            {
                try { arrayC[i].Modern(100, 200, 500); }
                catch (Exception ex)
                {
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Завершение работы программы");
                    Environment.Exit(1);
                }
            }
            Console.WriteLine("\nПосле модернизации: ");
            for (int i = 0; i < arrayC.Length; i++)
            {
                Console.WriteLine("\n");
                arrayC[i].OutputCars();
            }
            //двумерный массив
            engine[,] arrayEngineTwo = new engine[Length, Length];
            cars[,] arrayCarsTwo     = new cars[Length, Length];
            int count = 1;

            for (int i = 0; i < Length; i++)
            {
                for (int j = 0; j < Length; j++)
                {
                    arrayEngineTwo[i, j] = new engine("no_name");
                    arrayCarsTwo[i, j]   = new cars(arrayEngineTwo[i, j]);
                    Console.WriteLine("\nМашина " + count);
                    arrayCarsTwo[i, j].OutputCars();
                    count++;
                }
            }
            Console.WriteLine("\nВвод данных:");
            count = 1;
            for (int i = 0; i < Length; i++)
            {
                for (int j = 0; j < Length; j++)// заполнение массива
                {
                    Console.WriteLine("\nМашина " + count);
                    count++;
                    do
                    {
                        f = false;
                        try { arrayCarsTwo[i, j].PutCars(); }
                        catch (FormatException ex)
                        {
                            f = true;
                            Console.WriteLine("Ошибка: " + ex.Message);
                            Console.WriteLine("Введите данные еще раз");
                        }
                        catch (Exception ex)
                        {
                            f = true;
                            Console.WriteLine("Ошибка: " + ex.Message);
                            Console.WriteLine("Введите данные еще раз");
                        }
                    } while (f);
                }
            }
            Console.WriteLine("\nДанные после ввода:");
            count = 1;
            for (int i = 0; i < Length; i++)
            {
                for (int j = 0; j < Length; j++)
                {
                    Console.WriteLine("\nМашина " + count);
                    arrayCarsTwo[i, j].OutputCars();
                    count++;
                }
            }
            count = 1;
            Console.WriteLine("\nПробег после тест-драйва: ");
            for (int i = 0; i < Length; i++)
            {
                for (int j = 0; j < Length; j++)
                {
                    try { probegAfterDrive = arrayCarsTwo[i, j].Drive(10);
                          Console.WriteLine("\nМашина " + count + ": " + probegAfterDrive + "КМ");
                          count++; }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Ошибка: " + ex.Message);
                        Console.WriteLine("Завершение работы программы");
                        Environment.Exit(1);
                    }
                }
            }
            for (int i = 0; i < Length; i++)
            {
                for (int j = 0; j < Length; j++)
                {
                    try { arrayCarsTwo[i, j].Modern(100, 200, 500); }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Ошибка: " + ex.Message);
                        Console.WriteLine("Завершение работы программы");
                        Environment.Exit(1);
                    }
                }
            }
            Console.WriteLine("\nПосле модернизации: ");
            count = 1;
            for (int i = 0; i < Length; i++)
            {
                for (int j = 0; j < Length; j++)
                {
                    Console.WriteLine("\nМашина " + count);
                    arrayCarsTwo[i, j].OutputCars();
                    count++;
                }
            }
            Console.ReadLine();
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            FileStream   fs    = new FileStream("vehicles.txt", FileMode.Open);
            StreamReader sr    = new StreamReader(fs);
            int          index = 0;

            cars[] car = new cars[1000];
            while (true)
            {
                string line = sr.ReadLine();
                if (line == null)
                {
                    break;
                }
                string[] uj = line.Split(' ');
                car[index].hours           = int.Parse(uj[0]);
                car[index].minutes         = int.Parse(uj[1]);
                car[index].seconds         = int.Parse(uj[2]);
                car[index].registrationnum = uj[3];
                index++;
            }
            sr.Close();
            fs.Close();

            /*for (int i = 0; i < hossz; i++)
             * {
             *  Console.WriteLine(  car[i].hours + " " +
             *  car[i].minutes + " "+
             *  car[i].seconds + " " +
             *  car[i].registrationnum);
             * }
             */
            Console.WriteLine("EXERCISE 2:");
            int min = car[0].hours;
            int max = car[0].hours;

            for (int i = 0; i < hossz; i++)
            {
                if (min > car[i].hours)
                {
                    min = car[i].hours;
                }
            }
            for (int i = 0; i < hossz; i++)
            {
                if (max < car[i].hours)
                {
                    max = car[i].hours;
                }
            }

            Console.WriteLine(max + 1 - min);

            Console.WriteLine("EXERCISE 3: ");
            int aktualisora = 25;

            for (int i = 0; i < hossz; i++)
            {
                if (aktualisora != car[i].hours)
                {
                    Console.WriteLine(car[i].hours + " hours: " + car[i].registrationnum);
                    aktualisora = car[i].hours;
                }
            }



            Console.WriteLine("EXERCISE 4:");  // else if-el is lehet!!!
            int motor = 0;
            int truck = 0;
            int bus   = 0;

            for (int i = 0; i < hossz; i++)
            {
                if (car[i].registrationnum.Contains("B"))
                {
                    bus++;
                }
            }
            for (int i = 0; i < hossz; i++)
            {
                if (car[i].registrationnum.Contains("M"))
                {
                    motor++;
                }
            }
            for (int i = 0; i < hossz; i++)
            {
                if (car[i].registrationnum.Contains("K"))
                {
                    truck++;
                }
            }
            Console.WriteLine("number of busses: {0}, number of trucks: {1}, number of motors: {2}", bus, truck, motor);
            Console.WriteLine("EXERCISE 5: ");
            long max2 = 0;

            for (int i = 0; i < hossz - 1; i++)
            {
                if (masodperc(car[i + 1]) - masodperc(car[i]) > max2)
                {
                    max2 = masodperc(car[i + 1]) - masodperc(car[i]);
                }
            }
            long ora  = max2 / 3600;
            long perc = (max2 % 3600) / 60;
            long mp   = (max2 % 3600) % 60;

            Console.WriteLine(max2 % 3600);
            Console.WriteLine("EXERCISE 6:");
            kiir(max2);



            Console.WriteLine("PLEASE GIVE THE REMEMBERED NUMBERS OF THE REGISTARTION NUMBER AND REPLACE THE UNKKNOWN WITH *:");
            string search   = Console.ReadLine();
            int    searched = 0;

            for (int i = 0; i < hossz; i++)
            {
                if (car[i].registrationnum.Contains(search))
                {
                    searched = i;
                }
            }
            Console.WriteLine(car[searched].registrationnum);
            Console.WriteLine("EXERCISE 7: ");

            FileStream   fs2         = new FileStream("checked.txt", FileMode.Create);
            StreamWriter sw          = new StreamWriter(fs2);
            long         ellenorzott = masodperc(car[0]);

            sw.WriteLine(car[0].registrationnum + " " + car[0].hours + " " + car[0].minutes + " " + car[0].seconds);
            for (int i = 0; i < hossz; i++)
            {
                if (masodperc(car[i]) - ellenorzott >= 300)
                {
                    ellenorzott = masodperc(car[i]);
                    sw.WriteLine(car[i].registrationnum + " " + car[i].hours + " " + car[i].minutes + " " + car[i].seconds);
                }
            }
            sw.Close();
            fs2.Close();



            Console.ReadKey();
        }
Exemplo n.º 31
0
        delegate void Write(string msg); // делегат

        static void Main(string[] args)
        {
            Console.WriteLine("Инициализация:\n");
            engine dvs   = new engine("no_name", 10, 100, 0, 1000);                     // конструктор со всеми параметрами
            engine dvs1  = new engine();
            cars   avto  = new cars("no_name", "no_color", 2020, 1000, 10, 50, dvs, 5); // конструктор со всеми параметрами
            cars   avto1 = new cars("no_name", "no_color", 2020, 10000, 20, 0, dvs1, 10);

            avto = (cars)avto1.Clone();// глубокое клонирование
            Write message = Message;

            AddTov(avto);// вызов метода где использ абстракт класс
            Console.WriteLine("Машина:");
            Console.WriteLine(avto);
            avto.zapravka(message);
            bool f;

            do
            {
                f = false;
                try { avto.Read(); }
                catch (FormatException ex)// обработка программного исключения
                {
                    f = true;
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Введите данные еще раз");
                }
                catch (Exception ex)// обработка пользовательского исключения
                {
                    f = true;
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Введите данные еще раз");
                }
            } while (f);
            Console.WriteLine("\nДанные после ввода:");
            Console.Write(avto);
            int probegAfterDrive = 0;

            avto.zapravka(message);
            try { probegAfterDrive = avto.Drive(10); }
            catch (Exception ex)// обработка пользовательского исключения
            {
                Console.WriteLine("Ошибка: " + ex.Message);
                Console.WriteLine("Завершение работы программы");
                Environment.Exit(1);
            }
            Console.Write("\nПробег после тест-драйва: ");
            Console.WriteLine(probegAfterDrive);
            try { avto.Modern(100, 200, 500); }
            catch (Exception ex)// обработка пользовательского исключения
            {
                Console.WriteLine("Ошибка: " + ex.Message);
                Console.WriteLine("Завершение работы программы");
                Environment.Exit(1);
            }
            Console.WriteLine("\n\nПосле модернизации:");
            Console.Write(avto);
            Sale <cars> NEWPRICE = new Sale <cars>(avto, 4);                          // создание объекта шаблоа класса

            Console.WriteLine("Цена со скидкой: " + NEWPRICE.GetPriceWithSale());     // метод получения цены со скидкой
            avto.Sell();                                                              // вызов базового метода продажи авто
            avto.Sell(4);                                                             // вызов метода производного класса
            Console.WriteLine("Самолет:");
            plane pl = new plane("no_name", "no_color", 2020, 1000, 10, 10000, 5, 0); // конструктор со всеми параметрами

            pl.zapravka(message);
            pl.zapravka(message);
            Console.WriteLine(pl);
            do
            {
                f = false;
                try { pl.Read(); }
                catch (FormatException ex)// обработка программного исключения
                {
                    f = true;
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Введите данные еще раз");
                }
                catch (Exception ex)// обработка пользовательского исключения
                {
                    f = true;
                    Console.WriteLine("Ошибка: " + ex.Message);
                    Console.WriteLine("Введите данные еще раз");
                }
            } while (f);
            Console.WriteLine("\nДанные после ввода:");
            Console.Write(pl);

            pl.Fly(1);
            Console.WriteLine("Налет (в часах) после полета: " + pl.HOURFLY);
            pl.Sell();
            Console.ReadLine();
        }