Advertisement
Guest User

Luke T Computing Chat Room

a guest
Mar 9th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.17 KB | None | 0 0
  1. static bool IsInt(string value)
  2.         {
  3.             foreach (char c in value)
  4.                 if (c < '0' || c > '9') return false;
  5.             return true;
  6.         }
  7.  
  8.         static bool IsBool(string value)
  9.         {
  10.             return value == "false" || value == "true";
  11.         }
  12.  
  13.         static bool StringToBool(string value)
  14.         {
  15.             if (value == "true") return true;
  16.             else if (value == "false") return false;
  17.             else throw new ArgumentException();
  18.         }
  19.  
  20.         static string ScrubSpaces(string value)
  21.         {
  22.             string result = "";
  23.             foreach (char c in value)
  24.                 if (c > 32 && c < 126) result += c;
  25.             return result;
  26.         }
  27.  
  28.         static void FileMissing(string file)
  29.         {
  30.             Console.WriteLine(file + " File Missing. Defaulting to LAN Mode.");
  31.             System.Threading.Thread.Sleep(2000);
  32.             Console.Clear();
  33.         }
  34.  
  35.         static void FileError(string file)
  36.         {
  37.             Console.WriteLine("Error Loading {0} File. Exitting Program in 3...", file);
  38.             System.Threading.Thread.Sleep(1000);
  39.             Console.WriteLine("2");
  40.             System.Threading.Thread.Sleep(1000);
  41.             Console.WriteLine("1");
  42.             System.Threading.Thread.Sleep(1000);
  43.             Environment.Exit(1);
  44.         }
  45.  
  46.         /*static bool FileDirectoryContains(string target, string fileDirectory)
  47.         {
  48.             string[] directories = Directory.GetFiles(fileDirectory);
  49.             foreach (string file in directories)
  50.                 if (target == file) return true;
  51.             return false;
  52.         }*/
  53.  
  54.         static string UserIn(string text)
  55.         {
  56.             Console.WriteLine(text);
  57.             return Console.ReadLine();
  58.         }
  59.  
  60.         static void WriteAt(string text, int x, int y)
  61.         {
  62.             Console.SetCursorPosition(x, y);
  63.             Console.Write(text);
  64.         }
  65.  
  66.         static string UserInPad(string text, int maxLength = 78)
  67.         {
  68.             Console.WriteLine(text);
  69.             int xPos = 0;
  70.             int yPos = Console.CursorTop;
  71.             ConsoleKeyInfo key;
  72.             char[] pass = new char[maxLength];
  73.             do
  74.             {
  75.                 key = Console.ReadKey(true);
  76.                 if (key.KeyChar > 32 && key.KeyChar < 127 && xPos < 78)
  77.                 {
  78.                     pass[xPos] = key.KeyChar;
  79.                     WriteAt("* ", xPos++, yPos);
  80.                 }
  81.                 else if ((key.Key == ConsoleKey.Backspace || key.Key == ConsoleKey.Delete) && xPos > 0)
  82.                 {
  83.                     pass[--xPos] = ' ';
  84.                     WriteAt(" ", xPos, yPos);
  85.                 }
  86.  
  87.             } while (key.Key != ConsoleKey.Enter);
  88.             return ScrubSpaces(new string(pass));
  89.         }
  90.  
  91.         static void WriteColour(string text, ConsoleColor colour)
  92.         {
  93.             Console.BackgroundColor = colour;
  94.             Console.WriteLine(text);
  95.             Console.ResetColor();
  96.         }
  97.  
  98.         static void WriteClear()
  99.         {
  100.             Console.ResetColor();
  101.             Console.Clear();
  102.         }
  103.  
  104.         static int Menu(string[] text, int colourIndex, ConsoleColor[] colourRange, int position = 0, string title = null)
  105.         {
  106.             WriteClear();
  107.             while (true)
  108.             {
  109.                 if (title != null) Console.WriteLine(title);
  110.                 for (int i = 0; i < text.Length; i++)
  111.                 {
  112.                     if (position == i) WriteColour(text[i], colourRange[colourIndex == -1 ? i : colourIndex]);
  113.                     else Console.WriteLine(text[i]);
  114.                 }
  115.                 ConsoleKey key = Console.ReadKey(true).Key;
  116.                 WriteClear();
  117.                 if (key == ConsoleKey.Enter) return position;
  118.                 else if (key == ConsoleKey.Escape) return -1;
  119.                 else if (position > 0 && key == ConsoleKey.UpArrow) position--;
  120.                 else if (position < text.Length - 1 && key == ConsoleKey.DownArrow) position++;
  121.             }
  122.         }
  123.  
  124.         static void Main(string[] args)
  125.         {
  126.             //File.CreateText(@"K:\Computing\Hand-in Area\06 Lower Sixth\LUKE\ChatRooms\test.txt");
  127.             //Environment.Exit(1);
  128.             Dictionary<string, string> settings = new Dictionary<string, string>
  129.             {
  130.                 {"RoomDataLocation", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\"},
  131.                 {"UserDataLocation", ""},
  132.                 {"LockOutPeriod", ""},
  133.                 {"LockOutTime", ""},
  134.                 {"PasswordAttemptLimit", "5"},
  135.                 {"RefreshRate", "50"},
  136.                 {"ChatLimit", "false"},
  137.                 {"ChatLimitMaxLines", "20"},
  138.                 {"SoundOn", "false"}
  139.             };
  140.             Dictionary<string, string> userData = new Dictionary<string, string>();
  141.             if (File.Exists("config.txt"))
  142.                 using (StreamReader read = File.OpenText("config.txt"))
  143.                 {
  144.                     string key;
  145.                     string value;
  146.                     while ((key = read.ReadLine()) != null)
  147.                         if (settings.ContainsKey(key = ScrubSpaces(key)) && (value = read.ReadLine()) != null)
  148.                             settings[key] = value;
  149.                         else
  150.                             FileError("Config");
  151.                 }
  152.             else
  153.                 FileMissing("Config");
  154.  
  155.             SoundPlayer[] sounds = new SoundPlayer[0];
  156.             bool soundOn;
  157.             if (IsBool(settings["SoundOn"])) soundOn = StringToBool(settings["SoundOn"]);
  158.             else soundOn = false;
  159.             try
  160.             {
  161.                 if (soundOn)
  162.                 {
  163.                     sounds = new SoundPlayer[]{
  164.                     new SoundPlayer(@"Sounds\Join.wav"),
  165.                     new SoundPlayer(@"Sounds\OtherJoin.wav"),
  166.                     new SoundPlayer(@"Sounds\Msg.wav"),
  167.                     new SoundPlayer(@"Sounds\Leave.wav")};
  168.                 }
  169.             }
  170.             catch
  171.             {
  172.                 FileError("Sound");
  173.             }
  174.  
  175.             string userDataLocation;
  176.             if (File.Exists(userDataLocation = settings["UserDataLocation"] + "userdata.txt"))
  177.                 using (StreamReader read = File.OpenText(userDataLocation))
  178.                 {
  179.                     string user;
  180.                     string pass;
  181.                     while ((user = read.ReadLine()) != null)
  182.                         if ((pass = read.ReadLine()) != null)
  183.                             userData.Add(user, pass);
  184.                         else
  185.                             FileError("User Data");
  186.                 }
  187.             else
  188.                 FileMissing("User Data");
  189.             string[] signInQuery = new string[] { "New User", "Sign In", "Quit" };
  190.             int n = 0;
  191.             ConsoleColor[] colours = new ConsoleColor[]
  192.             {
  193.                 ConsoleColor.Magenta,
  194.                 ConsoleColor.DarkRed,
  195.                 ConsoleColor.Red,
  196.                 ConsoleColor.Yellow,
  197.                 ConsoleColor.DarkYellow,
  198.                 ConsoleColor.Green,
  199.                 ConsoleColor.DarkGreen,
  200.                 ConsoleColor.Cyan,
  201.                 ConsoleColor.Blue
  202.             };
  203.             while((n = Menu(signInQuery, 0, colours, 0)) >= 0 && n < signInQuery.Length - 1)
  204.             {
  205.                 switch (n)
  206.                 {
  207.                     case 0:
  208.                         string user;
  209.                         if(!userData.ContainsKey(user = UserIn("Please enter your Display Name")))
  210.                         userData.Add(
  211.                             user,
  212.                             UserIn("Please enter your Password").ToLower());
  213.                         break;
  214.                     case 1:
  215.                         //string user;
  216.                         if(userData.ContainsKey(user = UserIn("Please enter your Display Name")))
  217.                         {
  218.                             int attempts = 0;
  219.                             int passwordAttemptLimit = Convert.ToInt32(settings["PasswordAttemptLimit"]);
  220.                             bool passCheck = false;
  221.                             //var test = "";
  222.                             while (!passCheck && attempts++ < passwordAttemptLimit)
  223.                             {
  224.                                 if (userData[user] == UserInPad(("Attempt " + attempts + ": Please enter your Password")))
  225.                                     passCheck = true;
  226.                                 else
  227.                                     Console.WriteLine();
  228.                             }
  229.  
  230.                             if(passCheck)
  231.                             {
  232.                                 string[] roomMenu = new string[] { "Create Room", "Join Room", "Back" };
  233.                                 int roomN;
  234.                                 while ((roomN = Menu(roomMenu, 2, colours, 0)) >= 0 && roomN < roomMenu.Length - 1)
  235.                                 {
  236.                                     switch(roomN)
  237.                                     {
  238.                                         case 0:
  239.                                             string roomName;
  240.                                             string roomDataStore = settings["RoomDataLocation"];
  241.                                             while (File.Exists(roomDataStore + (roomName = UserIn("Please enter the name of your room"))))// + ".txt"))
  242.                                                 Console.WriteLine("Room Already Exists!");
  243.                                             File.CreateText(roomDataStore + roomName).Close();// + ".txt").Close();
  244.                                             break;
  245.                                         case 1:
  246.                                             //string roomDataStore = settings["RoomDataLocation"];
  247.                                             string[] rooms = Directory.GetFiles(settings["RoomDataLocation"]);
  248.                                             int selectedRoom = Menu(rooms, 4, colours);
  249.                                             if (selectedRoom > 0)
  250.                                             {
  251.                                                 bool exitChat = false;
  252.                                                 int refreshRate = Convert.ToInt32(settings["RefreshRate"]);
  253.                                                 string[] chat = new string[0];
  254.                                                 List<string> chatCache = new List<string>();
  255.                                                 int chatCounter = 0;
  256.                                                 string chatTemp = "";
  257.                                                 using (StreamWriter write = new StreamWriter(File.Open(rooms[selectedRoom], FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))//File.AppendText(rooms[selectedRoom]))
  258.                                                 {
  259.                                                     write.WriteLine("!{0} has joined the chat.", user);
  260.                                                 }
  261.                                                 WriteColour("Welcome to the chat, " + user + ".", ConsoleColor.DarkGreen);
  262.                                                 if (soundOn) sounds[0].PlaySync();
  263.                                                 do
  264.                                                 {
  265.                                                     using (StreamReader read = new StreamReader(File.Open(rooms[selectedRoom], FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
  266.                                                     {
  267.                                                         chatCache.Clear();
  268.                                                         string msg;
  269.                                                         while ((msg = read.ReadLine()) != null)
  270.                                                             chatCache.Add(msg);
  271.                                                         if (chatCache.Count() != chat.Length)
  272.                                                         {
  273.                                                             chat = (string[])chatCache.ToArray().Clone();
  274.                                                             //if (chat.Length > 20) chatCounter = chat.Length - 20;
  275.                                                             //else chatCounter = 0;
  276.                                                             WriteClear();
  277.                                                             WriteColour("Type 'leave' or 'exit' to leave the chat room", ConsoleColor.DarkYellow);
  278.                                                             for (int i = chatCounter; i < chat.Length; i++)
  279.                                                                 if ((chatTemp = chat[i]).Length > 0)
  280.                                                                     if (chatTemp[0] == '!') WriteColour(chatTemp, ConsoleColor.DarkCyan);
  281.                                                                     else if (chatTemp[0] == '#') WriteColour(chatTemp, ConsoleColor.DarkRed);
  282.                                                                     else Console.WriteLine(chatTemp);
  283.                                                            
  284.                                                             if(chatTemp.Length > 0)
  285.                                                                 if (chatTemp[0] == '!')
  286.                                                                 {
  287.                                                                     if (soundOn) sounds[1].Play();
  288.                                                                 }
  289.                                                                 else if (chatTemp[0] == '#')
  290.                                                                 {
  291.                                                                     if (soundOn) sounds[3].Play();
  292.                                                                 }
  293.                                                                 else
  294.                                                                 {
  295.                                                                     if (soundOn) sounds[2].Play();
  296.                                                                 }
  297.                                                         }
  298.                                                     }
  299.                                                     if (Console.KeyAvailable)
  300.                                                     {
  301.                                                         using (StreamWriter write = new StreamWriter(File.Open(rooms[selectedRoom], FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))//File.AppendText(rooms[selectedRoom]))
  302.                                                         {
  303.                                                             string msg;
  304.                                                             if ((msg = UserIn("Your message:")).ToLower() == "leave" || msg.ToLower() == "exit")
  305.                                                                 exitChat = true;
  306.                                                             else write.WriteLine("{0}: {1}", user, msg);
  307.                                                         }
  308.                                                     }
  309.                                                     System.Threading.Thread.Sleep(refreshRate);
  310.  
  311.                                                 } while (!exitChat);
  312.                                                 using (StreamWriter write = new StreamWriter(File.Open(rooms[selectedRoom], FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))//File.AppendText(rooms[selectedRoom]))
  313.                                                 {
  314.                                                     write.WriteLine("#{0} has left the chat.", user);
  315.                                                 }
  316.                                             }
  317.                                             break;
  318.                                     }
  319.                                 }
  320.                             }
  321.                         }
  322.                         break;
  323.                 }
  324.             }
  325.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement