Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- using System.Windows.Forms;
- using System.Text.RegularExpressions;
- namespace Dice_Game {
- class Program {
- public static INIT S; //intialises the INIT class and allows the use of variables within it
- static void Main(string[] args) {
- GameStart(); //starts the program
- }
- public static void GameStart() {
- S = new INIT();
- Functions L = new Functions(); //initialises the Functions class in the form of L which stores all the functions of the game which can be used in the future
- L.ImportUsers();
- Console.WriteLine("Welcome to the Dice Game! \n The rules are: \n -You write Roll to roll the dice \n -You enter your username \n -If you're playing with 2 players you take it turns rolling. \n \n Write 'Start' to Start the game \n Write 'Register' to register \n Write Leaderboard to view the leaderboard");
- //Checks for errors
- try {
- S.Choice = Console.ReadLine();
- }
- catch(ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry, something broke. Let's try again!", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- GameStart();
- }
- catch(ArgumentNullException) {
- MessageBox.Show("Sorry, something broke. Let's try again!", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- GameStart();
- }
- if (S.Choice == "Start" || S.Choice == "start") {
- L.LoginPrompt();
- }
- else if (S.Choice == "Register" || S.Choice == "register") {
- L.RegisterPrompt();
- }
- else if (S.Choice == "Leaderboard" || S.Choice == "leaderboard") {
- Leadboard G = new Leadboard();
- G.ViewLeadBoard();
- GameStart();
- }
- }
- }
- class Leadboard {
- int maxValue = 0;
- int Sum;
- public void ViewLeadBoard() {
- var myFile = File.Create(Program.S.CurrentDirectory + "Temp.txt");
- StreamReader sr = new StreamReader(Program.S.CurrentDirectory + "Leaderboard.txt");
- string contents = sr.ReadToEnd();
- myFile.Close();
- sr.Close();
- TextWriter Tw = new StreamWriter(Program.S.CurrentDirectory + "Temp.txt");
- string[] lines = contents.Split( //splits leaderboard per each line
- new[] { Environment.NewLine },
- StringSplitOptions.None
- );
- string[] temp = new string[2];
- string[,] Strings = new string[lines.Length, 2];
- for (int i = 0; i < lines.Length; i++) {
- temp = Regex.Split(lines[i], @"\d+"); //split at number
- temp[1] = Regex.Match(lines[i], @"\d+").Value;
- Strings[i, 0] = temp[0];
- Strings[i, 1] = temp[1];
- }
- Console.WriteLine("sick");
- while (Sum != -1) {
- Sum = 0;
- for (int i = 0; i < lines.Length; i++) {
- Sum += Convert.ToInt32(Strings[i, 1]);
- }
- if (Sum == 0) {
- Sum = -1;
- break;
- }
- for (int i = 0; i < lines.Length; i++) {
- if (Convert.ToInt32(Strings[i, 1]) > Convert.ToInt32(Strings[maxValue, 1])) {
- maxValue = i; //Find highest number in array, then proceed to delete the 2 records from array and append them to a string on new line
- }
- //else if (Convert.ToInt32(Strings[i + 1, 1]) > Convert.ToInt32(Strings[i, 1])) {
- // maxValue = i - 1;
- //}
- }
- Tw.Write(System.Environment.NewLine + "{0,-20} {1,20}", Strings[maxValue, 0], Strings[maxValue, 1]);
- Strings[maxValue, 1] = "0";
- Console.WriteLine(Strings[0, 1]);
- Console.WriteLine(Strings[1, 1]);
- Console.WriteLine(Strings[2, 1]);
- }
- Tw.Close();
- StreamReader sr2 = new StreamReader(Program.S.CurrentDirectory + "Temp.txt");
- contents = sr2.ReadToEnd();
- sr2.Close();
- File.Delete(Program.S.CurrentDirectory + "Temp.txt");
- Console.Clear();
- Console.WriteLine("-------------------------------------");
- Console.WriteLine("{0,-20} {1,20}", "Username", "Wins");
- Console.WriteLine(contents);
- Console.WriteLine("-------------------------------------");
- Console.WriteLine("");
- Console.WriteLine("Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- }
- class INIT { //creates a class which stores all the variables that might change
- public string Choice;
- public string Choice2;
- public string Username;
- public string Username2;
- public string Password;
- public string Password2;
- public string NUsername;
- public string NPassword;
- public string CurrentDirectory;
- public string[] Users;
- public StreamReader sr;
- public TextWriter tw;
- public string UserFile;
- public string[,] UserPass; //I used a 2 dimensional array because it allows to reference the correct username and password really easily and efficiently
- public bool[] LoginAccepted = new bool[2];
- public bool AI;
- public bool P2;
- }
- class Functions {
- int lineCount;
- public void LoginPrompt() { //Prompt for logging the user in
- bool Pt2 = false;
- void Login2() {
- Console.WriteLine("Please enter the login details for the second player \n ----------------------------");
- Console.WriteLine("Please Input your username");
- try {
- Program.S.Username = Console.ReadLine(); //Reads user response and stores it as a password
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- //Password Section
- //Asks user for input and catches errors if they exist
- Console.WriteLine("Please input your password");
- try {
- Program.S.Password = Console.ReadLine(); //Reads user response and stores it as a password
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- //
- //Code here for checking with the file which I will add in later on
- Pt2 = LoginChecker(Program.S.Username, Program.S.Password);
- }
- Console.WriteLine("AI or 2P (2 Player?)");
- Game B = new Game();
- try {
- Program.S.Choice2 = Console.ReadLine(); // checks if whatever the user inputs doesn't break it
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- if (Program.S.Choice2 == "AI" || Program.S.Choice2 == "ai") {
- //Just continues the program
- Program.S.AI = true;
- }
- else if (Program.S.Choice2 == "2P" || Program.S.Choice2 == "2p") {
- Program.S.P2 = true;
- Login2();
- }
- //Username Section
- //Asks user for input and catches errors if they exist
- Console.WriteLine("Please Input your username");
- try {
- Program.S.Username2 = Console.ReadLine(); //Reads user response and stores it as a password
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- //Password Section
- //Asks user for input and catches errors if they exist within the program
- Console.WriteLine("Please input your password");
- try {
- Program.S.Password2 = Console.ReadLine(); //Reads user response and stores it as a password
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- //
- //Code here for checking with the file which I will add in later on
- if (Program.S.Username2 == Program.S.Username) {
- Console.WriteLine("Players can't both use the same account");
- Console.ReadKey();
- //Restart program function
- }
- bool Pt1 = LoginChecker(Program.S.Username2, Program.S.Password2);
- if (Pt1 == true) {
- if (Program.S.AI == true) {
- Console.WriteLine("Login succesful");
- Console.ReadKey();
- B.AIGAME();
- Environment.Exit(1);
- }
- }
- if (Pt2 == true && Pt1 == true) {
- Console.WriteLine("both work");
- B.P2GAME();
- }
- else if (Pt1 == false || Pt2 == false) {
- Console.WriteLine("Login Failed");
- Console.ReadKey();
- }
- //ADD LIMITED LOGIN ALLOWANCES
- }
- public void RegisterPrompt() { //Prompt for Registering the user
- //Username Section
- Console.WriteLine("Please enter your new Username");
- try {
- Program.S.NUsername = Console.ReadLine(); //Reads user response and stores it as a password
- if (Program.S.NUsername.Any(char.IsDigit) == true) {
- Console.WriteLine("Sorry, the username cannot contain numbers \n Press any key to try again \n");
- Console.ReadKey();
- RegisterPrompt();
- }
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- if (Program.S.NUsername.Length > 16) { //if the Username the user is trying to register exceeds 16 characters in length this forces the user to restart the registering process
- Console.WriteLine("Your username exceeded the 16 character limit, please try again \n");
- RegisterPrompt();
- }
- else if (Program.S.NUsername.Length < 3) { //checks if the username is smaller than 3 characters in length
- Console.WriteLine("Your username is too short, the login process will restart \n");
- RegisterPrompt();
- }
- //This will check if the username already exists
- DoesUserExist();
- // Password Section
- Console.WriteLine("Please enter your new password to associate with that username");
- try {
- Program.S.NPassword = Console.ReadLine(); //Reads user response and stores it as a password
- }
- catch (ArgumentOutOfRangeException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (ArgumentNullException) {
- MessageBox.Show("Sorry something broke", "Error", //outputs error message if the program breaks
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- if (Program.S.NPassword.Length > 16) { //if the Password the user is trying to register exceeds 16 characters in length this forces the user to restart the registering process
- Console.WriteLine("Your Password exceeded the 16 character limit, please try again \n");
- RegisterPrompt();
- }
- else if (Program.S.NPassword.Length < 3) { //checks if the username is smaller than 3 characters in length
- Console.WriteLine("Your password is too short, the login process will restart \n");
- RegisterPrompt();
- }
- //This will add the new details to the list
- AddtoList();
- Program.GameStart();
- }
- void AddtoList() { //This method adds the details to the list of existing users
- Program.S.tw = new StreamWriter(Program.S.UserFile, true);
- Program.S.tw.Write(Environment.NewLine + Program.S.NUsername + "|" + Program.S.NPassword);
- Program.S.tw.Close();
- }
- bool LoginChecker(string Username, string Password) {
- for (int y = 0; y < lineCount ; y++) {
- if (Username == Program.S.UserPass[y, 0] && Password == Program.S.UserPass[y, 1]) {
- return true;
- }
- }
- return false;
- }
- void DoesUserExist() { //Checks whether the user exists
- try {
- var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
- Program.S.sr = new StreamReader(Program.S.UserFile);
- string contents = Program.S.sr.ReadToEnd();
- if (contents.Contains(Program.S.NUsername)) {
- Console.WriteLine("Sorry this user already exists, please pick another username, \n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- Program.S.sr.Close();
- RegisterPrompt();
- }
- else if (Program.S.NUsername.Any(char.IsDigit) || regexItem.IsMatch(Program.S.NUsername)) {
- Console.WriteLine("Sorry, the username cannot contain digits or special characters, \n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- RegisterPrompt();
- }
- Program.S.sr.Close();
- }
- catch(ArgumentNullException) {
- //If no users exist stops the program from crashing
- }
- Console.WriteLine("Check passed... The user does not exist, press any key to continue");
- Console.ReadLine();
- }
- void SplitPass() { //splits the username and passwords into program friendly and readable format for validation
- string[] temp = new string[2];
- Program.S.UserPass = new string[lineCount, 2];
- for (int i = 0; i < lineCount; i++) {
- temp = Program.S.Users[i].Split('|');
- Program.S.UserPass[i, 0] = temp[0];
- Program.S.UserPass[i, 1] = temp[1];
- }
- }
- public void ImportUsers() { //imports the Username/Password file
- Program.S.CurrentDirectory = Directory.GetCurrentDirectory() +"\\"; //Saves the current working directory
- Program.S.UserFile = Program.S.CurrentDirectory + "Users.txt";
- //when the users files exists
- if (File.Exists(Program.S.UserFile) == true) {
- //Counts the lines (Each Line is a user)
- try {
- lineCount = File.ReadLines(Program.S.UserFile).Count();
- Program.S.Users = File.ReadAllLines(Program.S.UserFile); //Adds all of the users to the array
- Program.S.sr.Close();
- }
- catch(NullReferenceException) {
- //ignores it and doesn't create an array
- }
- }
- //when the users file doesn't exist
- else if (File.Exists(Program.S.UserFile) == false) {
- File.Create(Program.S.UserFile);
- }
- try {
- SplitPass();
- }
- catch (ArgumentNullException) {
- //If no users exists
- }
- catch (NullReferenceException) {
- //If no users exists
- }
- }
- }
- class Game {
- Player p1; //initialises the players
- Player p2;
- int Counter = 0; //resets and initialises the counter
- public void AIGAME() {
- p1 = new Player() {
- Name = Program.S.Username2, //sets player 1's name to player 1 input
- Score = 0,
- OldScore = 0
- };
- p2 = new Player() {
- Name = "AI", //sets player 2's name to be that of the ai
- Score = 0,
- OldScore = 0
- };
- do {
- Progresz(false);
- } while (Counter < 4);
- while (p1.Score == p2.Score) {
- Progresz(true);
- }
- switch (p1.Score > p2.Score) {
- case true:
- Console.WriteLine(p1.Name + " Has Won!");
- Console.ReadKey();
- WriteWins(p1.Name);
- break;
- case false:
- Console.WriteLine(p2.Name + " Has Won!");
- Console.ReadKey();
- break;
- }
- }
- void Progresz(bool Option) {
- if (Option == false) {
- p1.Score += Roll(false);
- if (p1.Score > p1.OldScore) { //Checks if the player rolled an even or odd then displays it as output
- Console.WriteLine(p1.Name + " rolled an even, +10 points to " + p1.Name + ", \n " + p1.Name + "'s current score is: " + p1.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- else if (p1.Score < p1.OldScore) { //checks if the player score is less than 0
- if (p1.Score < 0) {
- p1.Score = 0;
- }
- Console.WriteLine(p1.Name + " rolled an odd, -5 points to " + p1.Name + ", \n " + p1.Name + "'s current score is: " + p1.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- p1.OldScore = p1.Score;
- p2.Score += Roll(false);
- if (p2.Score > p2.OldScore) {
- Console.WriteLine(p2.Name + " rolled an even, +10 points to " + p2.Name + ", \n" + p2.Name + "'s current score is: " + p2.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- else if (p2.Score < p2.OldScore) {
- if (p2.Score < 0) {
- p2.Score = 0;
- }
- Console.WriteLine(p2.Name + " rolled an odd, -5 points to " + p2.Name + ", \n" + p2.Name + "'s current score is: " + p2.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- p2.OldScore = p2.Score;
- Counter++;
- }
- else if (Option == true) {
- p1.Score += Roll(true);
- if (p1.Score > p1.OldScore) {
- Console.WriteLine(p1.Name + " rolled an even, +10 points to " + p1.Name + ", \n " + p1.Name + "'s current score is: " + p1.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- else if (p1.Score < p1.OldScore) {
- if (p1.Score < 0) {
- p1.Score = 0;
- }
- Console.WriteLine(p1.Name + " rolled an odd, -5 points to " + p1.Name + ", \n " + p1.Name + "'s current score is: " + p1.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- p1.OldScore = p1.Score;
- p2.Score += Roll(true);
- if (p2.Score > p2.OldScore) {
- Console.WriteLine(p2.Name + " rolled an even, +10 points to " + p2.Name + ", \n" + p2.Name + "'s current score is: " + p2.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- else if (p2.Score < p2.OldScore) {
- if (p2.Score < 0) {
- p2.Score = 0;
- }
- Console.WriteLine(p2.Name + " rolled an odd, -5 points to " + p2.Name + ", \n" + p2.Name + "'s current score is: " + p2.Score, "\n \n Press any key to continue");
- Console.ReadKey();
- Console.Clear();
- }
- p2.OldScore = p2.Score;
- }
- }
- int Roll(bool Option) {
- Random Big = new Random(); //instantiates the random class
- if (Option == false) { //runs only if the loop has been run less than 4 times. i.e does this for the main part of the program
- int d = 0;
- int a = Big.Next(1, 6); int b = Big.Next(1, 6); //randomises the values of a and b
- if (a == b) { //if dice scores are equal, roll once more again
- int c = Big.Next(1, 6);
- d = a + b + c;
- }
- else if (a != b) { //If Die scores are not equal, add the scores together
- d = a + b;
- }
- switch (d % 2) { //checks whether the result of the die scores is even
- case 0: //if it is, return 10
- return 10;
- case 1: //if it is not even, return -5
- return -5;
- }
- }
- else if (Option == true) { //if the code has been run more than 4 times and the scores of both players are equal, only one die will roll
- int a = Big.Next(1, 6);
- switch (a % 2) {
- case 0:
- return 10;
- case 1:
- return -5;
- }
- }
- return -5;
- }
- public void P2GAME() { //When the 2 player mode is selected
- p1 = new Player() { //defines a player
- Name = Program.S.Username2, //stores the player's name as the players username
- Score = 0, //sets player's score to 0
- OldScore = 0 //sets the old score to 0
- };
- p2 = new Player() {
- Name = Program.S.Username,
- Score = 0,
- OldScore = 0
- };
- do { //do while loop, whilst the counter is smaller than 4, continue the dice game
- Progresz(false);
- } while (Counter < 4);
- while (p1.Score == p2.Score) {
- Progresz(true);
- }
- switch (p1.Score > p2.Score) {
- case true:
- Console.WriteLine(p1.Name + " Has Won!");
- Console.ReadKey();
- WriteWins(p1.Name);
- break;
- case false:
- Console.WriteLine(p2.Name + " Has Won!");
- Console.ReadKey();
- WriteWins(p2.Name);
- break;
- }
- }
- void WriteWins(string Winner) {
- //Reads the contents of leaderboard.txt and if it doesn't exists it creates a new file called leaderboard.txt and writes the winner into it
- if (File.Exists(Program.S.CurrentDirectory + "Leaderboard.txt") == true) {
- StreamReader sr = new StreamReader(Program.S.CurrentDirectory + "Leaderboard.txt");
- string contents = sr.ReadToEnd();
- sr.Close();
- File.WriteAllText(Program.S.CurrentDirectory + "Leaderboard.txt", string.Empty);
- TextWriter Tw = new StreamWriter(Program.S.CurrentDirectory + "Leaderboard.txt", true);
- if (contents.Contains(Winner)) {
- string[] temp = new string[2];
- string[] lines = contents.Split( //splits leaderboard per each line
- new[] { Environment.NewLine },
- StringSplitOptions.None
- );
- int resultString = 0;
- for (int i = 0; i < lines.Length; i++) {
- temp = Regex.Split(lines[i], @"\d+"); //@"(?<=\p{L})(?=\p{N})"
- bool match = Regex.IsMatch(temp[0], string.Format(@"\b{0}\b", Regex.Escape(Winner)));
- if (match == true) {
- resultString = Convert.ToInt32(Regex.Match(lines[i], @"\d+").Value);
- resultString++;
- lines[i] = Regex.Replace(lines[i], @"\d+", Convert.ToString(resultString));
- Tw.Write(lines[0]);
- for (int y = 1; y < lines.Length; y++) {
- Tw.Write(System.Environment.NewLine + lines[y]);
- }
- Tw.Close();
- break;
- }
- }
- }
- else if (File.Exists(Program.S.CurrentDirectory + "Leaderboard.txt") == false) {
- File.Create(Program.S.CurrentDirectory + "Leaderboard.txt");
- Tw.WriteLine(Winner + "1");
- Tw.Close();
- }
- else if (contents.Contains(Winner) == false) {
- Tw.WriteLine(Winner + "1");
- Tw.Close();
- }
- }
- }
- }
- public class Player {
- public string Name;
- public int Score;
- public int OldScore;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement