Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static bool IsInt(string value)
- {
- foreach (char c in value)
- if (c < '0' || c > '9') return false;
- return true;
- }
- static bool IsBool(string value)
- {
- return value == "false" || value == "true";
- }
- static bool StringToBool(string value)
- {
- if (value == "true") return true;
- else if (value == "false") return false;
- else throw new ArgumentException();
- }
- static string ScrubSpaces(string value)
- {
- string result = "";
- foreach (char c in value)
- if (c > 32 && c < 126) result += c;
- return result;
- }
- static void FileMissing(string file)
- {
- Console.WriteLine(file + " File Missing. Defaulting to LAN Mode.");
- System.Threading.Thread.Sleep(2000);
- Console.Clear();
- }
- static void FileError(string file)
- {
- Console.WriteLine("Error Loading {0} File. Exitting Program in 3...", file);
- System.Threading.Thread.Sleep(1000);
- Console.WriteLine("2");
- System.Threading.Thread.Sleep(1000);
- Console.WriteLine("1");
- System.Threading.Thread.Sleep(1000);
- Environment.Exit(1);
- }
- /*static bool FileDirectoryContains(string target, string fileDirectory)
- {
- string[] directories = Directory.GetFiles(fileDirectory);
- foreach (string file in directories)
- if (target == file) return true;
- return false;
- }*/
- static string UserIn(string text)
- {
- Console.WriteLine(text);
- return Console.ReadLine();
- }
- static void WriteAt(string text, int x, int y)
- {
- Console.SetCursorPosition(x, y);
- Console.Write(text);
- }
- static string UserInPad(string text, int maxLength = 78)
- {
- Console.WriteLine(text);
- int xPos = 0;
- int yPos = Console.CursorTop;
- ConsoleKeyInfo key;
- char[] pass = new char[maxLength];
- do
- {
- key = Console.ReadKey(true);
- if (key.KeyChar > 32 && key.KeyChar < 127 && xPos < 78)
- {
- pass[xPos] = key.KeyChar;
- WriteAt("* ", xPos++, yPos);
- }
- else if ((key.Key == ConsoleKey.Backspace || key.Key == ConsoleKey.Delete) && xPos > 0)
- {
- pass[--xPos] = ' ';
- WriteAt(" ", xPos, yPos);
- }
- } while (key.Key != ConsoleKey.Enter);
- return ScrubSpaces(new string(pass));
- }
- static void WriteColour(string text, ConsoleColor colour)
- {
- Console.BackgroundColor = colour;
- Console.WriteLine(text);
- Console.ResetColor();
- }
- static void WriteClear()
- {
- Console.ResetColor();
- Console.Clear();
- }
- static int Menu(string[] text, int colourIndex, ConsoleColor[] colourRange, int position = 0, string title = null)
- {
- WriteClear();
- while (true)
- {
- if (title != null) Console.WriteLine(title);
- for (int i = 0; i < text.Length; i++)
- {
- if (position == i) WriteColour(text[i], colourRange[colourIndex == -1 ? i : colourIndex]);
- else Console.WriteLine(text[i]);
- }
- ConsoleKey key = Console.ReadKey(true).Key;
- WriteClear();
- if (key == ConsoleKey.Enter) return position;
- else if (key == ConsoleKey.Escape) return -1;
- else if (position > 0 && key == ConsoleKey.UpArrow) position--;
- else if (position < text.Length - 1 && key == ConsoleKey.DownArrow) position++;
- }
- }
- static void Main(string[] args)
- {
- //File.CreateText(@"K:\Computing\Hand-in Area\06 Lower Sixth\LUKE\ChatRooms\test.txt");
- //Environment.Exit(1);
- Dictionary<string, string> settings = new Dictionary<string, string>
- {
- {"RoomDataLocation", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\"},
- {"UserDataLocation", ""},
- {"LockOutPeriod", ""},
- {"LockOutTime", ""},
- {"PasswordAttemptLimit", "5"},
- {"RefreshRate", "50"},
- {"ChatLimit", "false"},
- {"ChatLimitMaxLines", "20"},
- {"SoundOn", "false"}
- };
- Dictionary<string, string> userData = new Dictionary<string, string>();
- if (File.Exists("config.txt"))
- using (StreamReader read = File.OpenText("config.txt"))
- {
- string key;
- string value;
- while ((key = read.ReadLine()) != null)
- if (settings.ContainsKey(key = ScrubSpaces(key)) && (value = read.ReadLine()) != null)
- settings[key] = value;
- else
- FileError("Config");
- }
- else
- FileMissing("Config");
- SoundPlayer[] sounds = new SoundPlayer[0];
- bool soundOn;
- if (IsBool(settings["SoundOn"])) soundOn = StringToBool(settings["SoundOn"]);
- else soundOn = false;
- try
- {
- if (soundOn)
- {
- sounds = new SoundPlayer[]{
- new SoundPlayer(@"Sounds\Join.wav"),
- new SoundPlayer(@"Sounds\OtherJoin.wav"),
- new SoundPlayer(@"Sounds\Msg.wav"),
- new SoundPlayer(@"Sounds\Leave.wav")};
- }
- }
- catch
- {
- FileError("Sound");
- }
- string userDataLocation;
- if (File.Exists(userDataLocation = settings["UserDataLocation"] + "userdata.txt"))
- using (StreamReader read = File.OpenText(userDataLocation))
- {
- string user;
- string pass;
- while ((user = read.ReadLine()) != null)
- if ((pass = read.ReadLine()) != null)
- userData.Add(user, pass);
- else
- FileError("User Data");
- }
- else
- FileMissing("User Data");
- string[] signInQuery = new string[] { "New User", "Sign In", "Quit" };
- int n = 0;
- ConsoleColor[] colours = new ConsoleColor[]
- {
- ConsoleColor.Magenta,
- ConsoleColor.DarkRed,
- ConsoleColor.Red,
- ConsoleColor.Yellow,
- ConsoleColor.DarkYellow,
- ConsoleColor.Green,
- ConsoleColor.DarkGreen,
- ConsoleColor.Cyan,
- ConsoleColor.Blue
- };
- while((n = Menu(signInQuery, 0, colours, 0)) >= 0 && n < signInQuery.Length - 1)
- {
- switch (n)
- {
- case 0:
- string user;
- if(!userData.ContainsKey(user = UserIn("Please enter your Display Name")))
- userData.Add(
- user,
- UserIn("Please enter your Password").ToLower());
- break;
- case 1:
- //string user;
- if(userData.ContainsKey(user = UserIn("Please enter your Display Name")))
- {
- int attempts = 0;
- int passwordAttemptLimit = Convert.ToInt32(settings["PasswordAttemptLimit"]);
- bool passCheck = false;
- //var test = "";
- while (!passCheck && attempts++ < passwordAttemptLimit)
- {
- if (userData[user] == UserInPad(("Attempt " + attempts + ": Please enter your Password")))
- passCheck = true;
- else
- Console.WriteLine();
- }
- if(passCheck)
- {
- string[] roomMenu = new string[] { "Create Room", "Join Room", "Back" };
- int roomN;
- while ((roomN = Menu(roomMenu, 2, colours, 0)) >= 0 && roomN < roomMenu.Length - 1)
- {
- switch(roomN)
- {
- case 0:
- string roomName;
- string roomDataStore = settings["RoomDataLocation"];
- while (File.Exists(roomDataStore + (roomName = UserIn("Please enter the name of your room"))))// + ".txt"))
- Console.WriteLine("Room Already Exists!");
- File.CreateText(roomDataStore + roomName).Close();// + ".txt").Close();
- break;
- case 1:
- //string roomDataStore = settings["RoomDataLocation"];
- string[] rooms = Directory.GetFiles(settings["RoomDataLocation"]);
- int selectedRoom = Menu(rooms, 4, colours);
- if (selectedRoom > 0)
- {
- bool exitChat = false;
- int refreshRate = Convert.ToInt32(settings["RefreshRate"]);
- string[] chat = new string[0];
- List<string> chatCache = new List<string>();
- int chatCounter = 0;
- string chatTemp = "";
- using (StreamWriter write = new StreamWriter(File.Open(rooms[selectedRoom], FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))//File.AppendText(rooms[selectedRoom]))
- {
- write.WriteLine("!{0} has joined the chat.", user);
- }
- WriteColour("Welcome to the chat, " + user + ".", ConsoleColor.DarkGreen);
- if (soundOn) sounds[0].PlaySync();
- do
- {
- using (StreamReader read = new StreamReader(File.Open(rooms[selectedRoom], FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
- {
- chatCache.Clear();
- string msg;
- while ((msg = read.ReadLine()) != null)
- chatCache.Add(msg);
- if (chatCache.Count() != chat.Length)
- {
- chat = (string[])chatCache.ToArray().Clone();
- //if (chat.Length > 20) chatCounter = chat.Length - 20;
- //else chatCounter = 0;
- WriteClear();
- WriteColour("Type 'leave' or 'exit' to leave the chat room", ConsoleColor.DarkYellow);
- for (int i = chatCounter; i < chat.Length; i++)
- if ((chatTemp = chat[i]).Length > 0)
- if (chatTemp[0] == '!') WriteColour(chatTemp, ConsoleColor.DarkCyan);
- else if (chatTemp[0] == '#') WriteColour(chatTemp, ConsoleColor.DarkRed);
- else Console.WriteLine(chatTemp);
- if(chatTemp.Length > 0)
- if (chatTemp[0] == '!')
- {
- if (soundOn) sounds[1].Play();
- }
- else if (chatTemp[0] == '#')
- {
- if (soundOn) sounds[3].Play();
- }
- else
- {
- if (soundOn) sounds[2].Play();
- }
- }
- }
- if (Console.KeyAvailable)
- {
- using (StreamWriter write = new StreamWriter(File.Open(rooms[selectedRoom], FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))//File.AppendText(rooms[selectedRoom]))
- {
- string msg;
- if ((msg = UserIn("Your message:")).ToLower() == "leave" || msg.ToLower() == "exit")
- exitChat = true;
- else write.WriteLine("{0}: {1}", user, msg);
- }
- }
- System.Threading.Thread.Sleep(refreshRate);
- } while (!exitChat);
- using (StreamWriter write = new StreamWriter(File.Open(rooms[selectedRoom], FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))//File.AppendText(rooms[selectedRoom]))
- {
- write.WriteLine("#{0} has left the chat.", user);
- }
- }
- break;
- }
- }
- }
- }
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement