Untitled

 avatar
unknown
csharp
8 days ago
2.7 kB
3
Indexable
using System;
using System.Threading;

public class BaiTap60
{
    // Hàm in chuỗi tại vị trí và màu sắc chỉ định
    static void WriteXY(string chuoiS, int cotC, int hangR, ConsoleColor mauChuF, ConsoleColor mauNenB)
    {
        if (hangR < 0 || cotC < 0 || hangR >= Console.WindowHeight || cotC >= Console.WindowWidth)
        {
            // Bỏ qua nếu tọa độ ra ngoài màn hình để tránh lỗi
            return;
        }

        ConsoleColor mauChuCu = Console.ForegroundColor;
        ConsoleColor mauNenCu = Console.BackgroundColor;

        try
        {
            Console.SetCursorPosition(cotC, hangR);
            Console.ForegroundColor = mauChuF;
            Console.BackgroundColor = mauNenB;
            Console.Write(chuoiS);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            
        }
        finally // Đảm bảo màu được reset ngay cả khi có lỗi
        {
            Console.ForegroundColor = mauChuCu;
            Console.BackgroundColor = mauNenCu;
        }
    }

    public static void Main(string[] args)
    {
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        Console.InputEncoding = System.Text.Encoding.UTF8;

        Console.WriteLine("Hàm WriteXY và hiệu ứng chữ rơi");

        string dongChu = "Lập trình C# thật thú vị!";
        int cotGiua = (Console.WindowWidth / 2) - (dongChu.Length / 2);
        if (cotGiua < 0) cotGiua = 0;

        ConsoleColor mauChu = ConsoleColor.Yellow;
        ConsoleColor mauNen = ConsoleColor.Black; // Hoặc Console.BackgroundColor để lấy màu nền hiện tại

        Console.Clear();
        Console.CursorVisible = false;
        Console.WriteLine("Nhấn phím bất kỳ để dừng...");

        for (int hang = 1; hang < 25 && hang < Console.WindowHeight; hang++) // Giới hạn bởi chiều cao console
        {
            if (Console.KeyAvailable) break; // Dừng nếu có phím nhấn

            // Xóa vị trí cũ (nếu không phải dòng đầu)
            if (hang > 1)
            {
                WriteXY(new string(' ', dongChu.Length), cotGiua, hang - 1, mauChu, mauNen);
            }

            // Vẽ ở vị trí mới
            WriteXY(dongChu, cotGiua, hang, mauChu, mauNen);

            Thread.Sleep(100); // Tốc độ rơi
        }

        Console.CursorVisible = true;
        Console.ResetColor(); // Reset màu về mặc định
        Console.SetCursorPosition(0, Math.Min(25, Console.WindowHeight)); // Di chuyển con trỏ xuống dưới
        Console.WriteLine("\nHiệu ứng kết thúc.");
        if(Console.KeyAvailable) Console.ReadKey(true); // Đọc phím nếu có
    }
}
Editor is loading...
Leave a Comment