p-GeoGame / CSharp_GeographyGame / presidentsForm.cs
presidentsForm.cs
Raw
// President images to reference: https://presidenstory.com/stat_pht.php
//

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading.Tasks;
using System.Configuration;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.Threading;
using System.Text;

namespace CSharp_GeographyGame
{
    public partial class presidentsForm : Form
    {
        string connectionString;
        SqlConnection connection;
        double corCount = 0;
        double perNum = 0.0;
        bool clockIt = false;
        string nID;
        int totPres = 46;
        string difficulty;
        bool isShown = false;

        string[] presCount = new string[]
        {
                "1ST", "2ND", "3RD", "4TH", "5TH", "6TH", "7TH", "8TH", "9TH", "10TH",
                "11TH", "12TH", "13TH", "14TH", "15TH", "16TH", "17TH", "18TH", "19TH", "20TH",
                "21ST", "22ND", "23RD", "24TH", "25TH", "26TH", "27TH", "28TH", "29TH", "30TH",
                "31ST", "32ND", "33RD", "34TH", "35TH", "36TH", "37TH", "38TH", "39TH", "40TH",
                "41ST", "42ND", "43RD", "44TH", "45TH", "46TH"
        };

        string[] presNames = new string[]
        {
                "George Washington", "John Adams", "Thomas Jefferson", "James Madison", "James Monroe", "John Adams", "Andrew Jackson", "Martin Buren", "William Harrison", "John Tyler",
                "James Polk", "Zachary Taylor", "Millard Fillmore", "Franklin Pierce", "James Buchanan", "Abraham Lincoln", "Andrew Johnson", "Ulysses Grant", "Rutherford Hayes", "James Garfield",
                "Chester Arthur", "Grover Cleveland", "Benjamin Harrison", "Grover Cleveland", "William McKinley", "Theodore Roosevelt", "William Taft", "Woodrow Wilson", "Warren Harding", "Calvin Coolidge",
                "Herbert Hoover", "Franklin Roosevelt", "Harry Truman", "Dwight Eisenhower", "John Kennedy", "Lyndon Johnson", "Richard Nixon", "Gerald Ford", "James Carter", "Ronald Reagan",
                "George Bush", "William Clinton", "George Bush", "Barack Obama", "Donald Trump", "Joe Biden"
        };

        string[] presMidNames = new string[]
        {
                "George Washington", "John Adams", "Thomas Jefferson", "James Madison", "James Monroe", "John Quincy Adams", "Andrew Jackson", "Martin Van Buren", "William Henry Harrison", "John Tyler",
                "James K. Polk", "Zachary Taylor", "Millard Fillmore", "Franklin Pierce", "James Buchanan", "Abraham Lincoln", "Andrew Johnson", "Ulysses S. Grant", "Rutherford B. Hayes", "James Garfield",
                "Chester A. Arthur", "Grover Cleveland", "Benjamin Harrison", "Grover Cleveland", "William McKinley", "Theodore Roosevelt", "William Howard Taft", "Woodrow Wilson", "Warren G. Harding", "Calvin Coolidge",
                "Herbert Hoover", "Franklin D. Roosevelt", "Harry S. Truman", "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard M. Nixon", "Gerald R. Ford", "James Carter", "Ronald Reagan",
                "George H. W. Bush", "Bill Clinton", "George W. Bush", "Barack Obama", "Donald J. Trump", "Joseph Biden"
        };

        string[] presArray = new string[]
        {
                "https://presidenstory.com/usimag/phot2/washington.jpg", "https://presidenstory.com/usimag/phot2/adams.jpg",
                "https://presidenstory.com/usimag/phot2/jefferson.jpg", "https://presidenstory.com/usimag/phot2/madison.jpg",
                "https://presidenstory.com/usimag/phot2/monroe.jpg", "https://presidenstory.com/usimag/phot2/quincyadams.jpg",
                "https://presidenstory.com/usimag/phot2/jackson.jpg", "https://presidenstory.com/usimag/phot2/vanburen.jpg",
                "https://presidenstory.com/usimag/phot2/h_harrison.jpg", "https://presidenstory.com/usimag/phot2/tyler.jpg",
                "https://presidenstory.com/usimag/phot2/polk.jpg", "https://presidenstory.com/usimag/phot2/taylor.jpg",
                "https://presidenstory.com/usimag/phot2/fillmore.jpg", "https://presidenstory.com/usimag/phot2/pierce.jpg",
                "https://presidenstory.com/usimag/phot2/buchanan.jpg", "https://presidenstory.com/usimag/phot2/lincoln.jpg",
                "https://presidenstory.com/usimag/phot2/ajohnson.jpg", "https://presidenstory.com/usimag/phot2/grant.jpg",
                "https://presidenstory.com/usimag/phot2/hayes.jpg", "https://presidenstory.com/usimag/phot2/garfield.jpg",
                "https://presidenstory.com/usimag/phot2/arthur.jpg", "https://presidenstory.com/usimag/phot2/cleveland.jpg",
                "https://presidenstory.com/usimag/phot2/harrison.jpg", "https://presidenstory.com/usimag/phot2/cleveland.jpg",
                "https://presidenstory.com/usimag/phot2/mckinley.jpg", "https://presidenstory.com/usimag/phot2/roosevelt.jpg",
                "https://presidenstory.com/usimag/phot2/taft.jpg", "https://presidenstory.com/usimag/phot2/wilson.jpg",
                "https://presidenstory.com/usimag/phot2/harding.jpg", "https://presidenstory.com/usimag/phot2/coolidge.jpg",
                "https://presidenstory.com/usimag/phot2/hoover.jpg", "https://presidenstory.com/usimag/phot2/fdr.jpg",
                "https://presidenstory.com/usimag/phot2/truman.jpg", "https://presidenstory.com/usimag/phot2/ike.jpg",
                "https://presidenstory.com/usimag/phot2/jfk.jpg", "https://presidenstory.com/usimag/phot2/johnson.jpg",
                "https://presidenstory.com/usimag/phot2/nixon.jpg", "https://presidenstory.com/usimag/phot2/ford.jpg",
                "https://presidenstory.com/usimag/phot2/carter.jpg", "https://presidenstory.com/usimag/phot2/reagan.jpg",
                "https://presidenstory.com/usimag/phot2/bush.jpg", "https://presidenstory.com/usimag/phot2/clinton.jpg",
                "https://presidenstory.com/usimag/phot2/wbush.jpg", "https://presidenstory.com/usimag/phot2/obama.jpg",
                "https://presidenstory.com/usimag/phot2/donald-trump.jpg", "https://presidenstory.com/usimag/phot2/donald-trumpwon.jpg"
        };

        public presidentsForm(string inName)
        {
            nID = inName;
            InitializeComponent();
            userToolStripMenuItem.Text = "User: " + inName;
            bgWorker.DoWork += bgWorker_DoWork;
            bgWorker.ProgressChanged += bgWorker_ProgressChanged;
            connectionString = ConfigurationManager.ConnectionStrings["CSharp_GeographyGame.Properties.Settings.userScoresConnectionString"].ConnectionString;
        }

        private void presidentsForm_Shown(object sender, EventArgs e)
        {
            bgWorker.RunWorkerAsync();
        }

        private void insertDataLocally(double scoreID, string sqlFormattedDate)
        {
            //// FOR LOCAL DATABASE
            string con = "INSERT INTO USPresscores ([Name], [Difficulty], [Score], [Time], [Date]) VALUES(@name, @diff, @score, @time, @date)";
            using (connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(con, connection))
            {
                try
                {
                    connection.Open();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                command.Parameters.AddWithValue("@name", nID);
                command.Parameters.AddWithValue("@diff", difficulty);
                command.Parameters.AddWithValue("@score", scoreID);
                command.Parameters.AddWithValue("@time", lblClock.Text);
                command.Parameters.AddWithValue("@date", sqlFormattedDate);
                int result = command.ExecuteNonQuery();
                // Check Error
                if (result < 0)
                    MessageBox.Show("Error inserting data into database!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                connection.Close();
            }
        }

        private void insertDataOnline(double scoreID, string sqlFormattedDate)
        {
            //// FOR ONLINE DATABASE
            string conWeb = "Server = remotemysql.com; Port = 3306; database = 2Ds6YxqaDW; username = 2Ds6YxqaDW; password = VJKMThFkcO";
            MySqlConnection connTwo = new MySqlConnection(conWeb);
            MySqlCommand commWeb = connTwo.CreateCommand();
            commWeb.CommandType = System.Data.CommandType.Text;
            commWeb.CommandText = "INSERT INTO onUSpresscores (Name, Difficulty, Score, Time, Date) VALUES(@name, @diff, @score, @time, @date)";
            commWeb.Parameters.AddWithValue("@name", nID);
            commWeb.Parameters.AddWithValue("@diff", difficulty);
            commWeb.Parameters.AddWithValue("@score", scoreID);
            commWeb.Parameters.AddWithValue("@time", lblClock.Text);
            commWeb.Parameters.AddWithValue("@date", sqlFormattedDate);
            try
            {
                connTwo.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Insertion failed because: " + ex.Message);
            }
            commWeb.ExecuteNonQuery();
            connTwo.Close();
        }

        private void vbScoreInputDialog(double scoreID, string sqlFormattedDate)
        {
            //// Using microsoft.visualbasic reference allowing the user to choose where to submit his score (allows offline score submission)
            string message, title, defaultValue;
            object myValue;

            message = "Would you like to submit your results to the Local, Online, or Both databases?\n" +
                "Type the following in the textbox below:\n" +
                "Local\n" +
                "Online\n" +
                "Both";
            title = "Score Submission";
            defaultValue = "Both";

            bool validSelection = false;

            do
            {
                myValue = Interaction.InputBox(message, title, defaultValue); // input box

                if ((string)myValue == "")
                {
                    object uChoice = Microsoft.VisualBasic.Interaction.MsgBox("Are you sure you don't want to submit your score?", MsgBoxStyle.YesNo, "Score Submission");
                    if ((int)uChoice == 6)
                    {
                        System.Environment.Exit(0);
                    }
                    else
                    {
                        // do nothing, reset back to original input box
                    }
                }
                else if ((string)myValue == "Local" || (string)myValue == "local")
                {
                    insertDataLocally(scoreID, sqlFormattedDate);
                    validSelection = true;
                }
                else if ((string)myValue == "Online" || (string)myValue == "online")
                {
                    insertDataOnline(scoreID, sqlFormattedDate);
                    validSelection = true;
                }
                else if ((string)myValue == "Both" || (string)myValue == "both")
                {
                    insertDataLocally(scoreID, sqlFormattedDate);
                    insertDataOnline(scoreID, sqlFormattedDate);
                    validSelection = true;
                }
                else
                {
                    Microsoft.VisualBasic.Interaction.MsgBox("Wrong input entered... Please try again and this time, read.");
                }
            } while (validSelection == false);
            /////
        }

        private void presidentsForm_Load(object sender, EventArgs e)
        {
            btnShowNames.Enabled = false;
            btnSubmit.Enabled = false;
            btnPause.Enabled = false;
            btnQuit.Enabled = false;
        }

        private void PercentageFormula()
        {
            perNum = ((corCount / totPres) * 100);
            lblPercentage.Text = perNum.ToString("0.###") + "%";
        }

        private void presidentsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            FormProvider.gForm.Show();
        }

        private void presidentsListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://presidenstory.com/stat_pht.php");
        }

        int presIncrem = 0;
        private void btnBegin_Click(object sender, EventArgs e)
        {
            if (rbBeginner.Checked == false && rbAdvanced.Checked == false)
            {
                MessageBox.Show("Please select normal or advanced.", "Select Difficulty");
                return;
            }

            if (rbBeginner.Checked == true)
            {
                btnShowNames.Enabled = true;
            }
            else
            {
                btnShowNames.Enabled = false;
            }

            clockIt = true;
            tbPresEntry.Enabled = true;
            btnSubmit.Enabled = true;
            lblClock.ForeColor = System.Drawing.Color.Blue;
            timerClock.Stop();
            timerClock.Start();
            btnBegin.Enabled = false;

            if (btnPause.Enabled == false || btnQuit.Enabled == false)
            {
                btnPause.Enabled = true;
                btnQuit.Enabled = true;
            }

            rbBeginner.Enabled = false;
            rbAdvanced.Enabled = false;

            lblPresNo.Text = presCount[presIncrem];
            pbPresidents.ImageLocation = presArray[presIncrem];

        }

        int listViewCount = 1;
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            ListViewItem entry = new ListViewItem(listViewCount.ToString());

            if (string.Compare(tbPresEntry.Text, presNames[presIncrem], true) == 0 || string.Compare(tbPresEntry.Text, presMidNames[presIncrem], true) == 0)
            {
                entry.BackColor = Color.LightGreen;
                entry.SubItems.Add(tbPresEntry.Text);
                entry.SubItems.Add("Correct");
                lviewAnswers.Items.Add(entry);
                corCount++;
                lblCorrect.Text = corCount.ToString();
                PercentageFormula();
                tbPresEntry.Text = string.Empty;
            }
            else
            {
                entry.BackColor = Color.LightPink;
                entry.SubItems.Add(tbPresEntry.Text);
                entry.SubItems.Add("Incorrect");
                lviewAnswers.Items.Add(entry);
            }

            listViewCount++;
            presIncrem++;
            tbPresEntry.Text = string.Empty;

            if (presIncrem >= totPres)
            {
                btnSubmit.Enabled = false;
                btnBegin.Enabled = false;
                btnPause.Enabled = false;
                presIncrem = 0;
                tbPresEntry.Enabled = false;
                if (corCount != totPres)
                {
                    btnQuit.PerformClick();
                }
                lviewAnswers.Items.Clear();
                rbBeginner.Enabled = true;
                rbAdvanced.Enabled = true;
                return;
            }

            lblPresNo.Text = presCount[presIncrem];
            pbPresidents.ImageLocation = presArray[presIncrem];
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            timerClock.Stop();
            string xTract = lblPercentage.Text.Trim(new Char[] { '%', '*', '.' });
            double xConversion; // CHANGED THIS
            Double.TryParse(xTract, out xConversion);
            double scoreID = xConversion;
            DateTime myDateTime = DateTime.Now;
            string sqlFormattedDate = myDateTime.ToString("MM-dd-yyyy HH:mm:ss.fff");

            vbScoreInputDialog(scoreID, sqlFormattedDate);

            i = 0;
            clockIt = false;
            lblClock.ForeColor = System.Drawing.Color.Black;
            lblClock.Text = "00:00:00";
            lblCorrect.Text = 0.ToString();
            lblPercentage.Text = "%";
            corCount = 0;
            progBar.Value = 0;

            MessageBox.Show(new Form { TopMost = true }, "If you scored over 70%, you are a true historian. Give it another go to aim for 100%!", "Score Submitted");
            if (btnBegin.Enabled == false || btnPause.Enabled == false)
            {
                btnBegin.Text = "Begin";
                btnBegin.Enabled = true;
                btnPause.Enabled = true;
            }

            btnPause.Enabled = false;
            btnQuit.Text = "End";
            btnQuit.Enabled = false;
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            clockIt = false;
            timerClock.Stop();
            lblClock.ForeColor = System.Drawing.Color.Red;

            if (btnBegin.Enabled == false)
            {
                btnBegin.Text = "Resume";
                btnBegin.Enabled = true;
            }

            btnSubmit.Enabled = false;
            tbPresEntry.Enabled = false;
            btnPause.Enabled = false;
        }

        int i = 0;
        private void timerClock_Tick(object sender, EventArgs e)
        {
            i++;
            if (lblClock.ForeColor == System.Drawing.Color.Red)
            {
                lblClock.ForeColor = System.Drawing.Color.Blue;
            }
            TimeSpan time = TimeSpan.FromSeconds(i);
            lblClock.Text = time.ToString(@"hh\:mm\:ss");
        }

        private void rbBeginner_CheckedChanged(object sender, EventArgs e)
        {
            pbDefault.Visible = false;
            pbPresidents.Visible = true;
            difficulty = "Normal";
        }

        private void rbAdvanced_CheckedChanged(object sender, EventArgs e)
        {
            pbDefault.Visible = true;
            pbPresidents.Visible = false;
            difficulty = "Advanced";
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            double cCount = 0;
            double prev = 0;
            progBar.Invoke((MethodInvoker)(() => progBar.Minimum = 0));
            progBar.Invoke((MethodInvoker)(() => progBar.Maximum = totPres));

            while (true)
            {
                cCount = corCount;

                if (cCount > prev)
                {
                    prev = cCount;
                    progBar.Invoke((MethodInvoker)(() => progBar.Increment(1)));
                    bgWorker.ReportProgress((int)cCount);
                }
                Application.DoEvents();

                if (cCount == totPres)
                {
                    break; // ***is needed for the bgWorker to end to run bgWorker_RunWorkerCompleted
                }
            }

        }

        private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progBar.Value = e.ProgressPercentage;
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("Error. I suck.");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("Ran into an unknown error... I really suck.");
            }
            else
            {
                if (lblCorrect.Text.ToString() == lblTotal.Text.ToString())
                {
                    lblClock.ForeColor = System.Drawing.Color.Green;
                }
                timerClock.Stop();
                i = 0;
                clockIt = false;
                System.Diagnostics.Process.Start("https://i.redd.it/pv5x0ifvw9r21.jpg");
                string xTract = lblPercentage.Text.Trim(new Char[] { '%', '*', '.' });
                double xConversion; // MIGHT BE WRONG
                Double.TryParse(xTract, out xConversion);
                double scoreID = xConversion;
                DateTime myDateTime = DateTime.Now;
                string sqlFormattedDate = myDateTime.ToString("MM-dd-yyyy HH:mm:ss.fff");

                vbScoreInputDialog(scoreID, sqlFormattedDate);

                DialogResult diaBox;
                diaBox = MessageBox.Show("Remarkable! This test was very hard and if you reached this point you are one of the smartest people in the world. Would you like to take the test again?", "Congratulations", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (diaBox == DialogResult.Yes)
                {
                    lblClock.ForeColor = System.Drawing.Color.Black;
                    ResetText();
                    lblClock.Text = "00:00:00";
                    progBar.Value = 0;
                    lblPercentage.Text = "%";
                    btnPause.Enabled = false;
                    btnQuit.Enabled = false;
                    lviewAnswers.Items.Clear();
                    corCount = 0;
                }
                if (diaBox == DialogResult.No)
                {
                    btnBegin.Enabled = false;
                    btnPause.Enabled = false;
                    btnQuit.Enabled = false;
                }
            }
        }

        private void tbPresEntry_KeyDown(object sender, KeyEventArgs e)
        {
            ActiveForm.AcceptButton = btnSubmit;
        }

        private void viewDatabaseScoresToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool isOpen = false;

            foreach (Form F in Application.OpenForms)
            {
                if (F.Name == "dbscoresForm")
                {
                    isOpen = true;
                    F.BringToFront();
                }
            }
            if (isOpen == false)
            {
                dbscoresForm dbF = new dbscoresForm();
                dbF.Show();
            }
        }

        private void btnShowAnswers_Click(object sender, EventArgs e)
        {
            // original size of form: 612, 544
            if (btnShowAnswers.Text == "Show Given Answers")
            {
                this.Width = 612;
                btnShowAnswers.Text = "Hide Given Answers";
            }
            else
            {
                this.Width = 354;
                btnShowAnswers.Text = "Show Given Answers";
            }
        }

        private void btnShowNames_Click(object sender, EventArgs e)
        {
            bool isOpen = false;

            foreach (Form F in Application.OpenForms)
            {
                if (F.Name == "presidentsnamesForm")
                {
                    isOpen = true;
                    F.BringToFront();
                }
            }
            if (isOpen == false)
            {
                presidentsnamesForm presnamesForm = new presidentsnamesForm();
                presnamesForm.Show();
            }
        }

        private void exitProgramToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var process in Process.GetProcessesByName("Trainer"))
            {
                process.Kill();
            }
            Application.ExitThread();
            Application.Exit();
        }

        private void trainerInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool isOpen = false;

            foreach (Form F in Application.OpenForms)
            {
                if (F.Name == "infoForm")
                {
                    isOpen = true;
                    F.BringToFront();
                }
            }
            if (isOpen == false)
            {
                infoForm inf = new infoForm();
                inf.Show();
            }
        }

        private void lviewAnswers_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control == true && e.KeyCode == Keys.C)
            {
                CopyListBox(lviewAnswers);
            }
        }

        public void CopyListBox(ListView list)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in list.SelectedItems)
            {
                ListViewItem l = item as ListViewItem;
                if (l != null)
                    foreach (ListViewItem.ListViewSubItem sub in l.SubItems)
                        sb.Append(sub.Text + "\t");
                sb.AppendLine();
            }
            Clipboard.SetDataObject(sb.ToString());

        }

        private void presidentsForm_MouseMove(object sender, MouseEventArgs e)
        {
            Control ctrl = this.GetChildAtPoint(e.Location);

            if (ctrl != null)
            {
                if (ctrl == this.btnShowNames && !isShown)
                {
                    string tipstring = this.toolTipNames.GetToolTip(this.btnShowNames);
                    this.toolTipNames.Show(tipstring, this.btnShowNames, this.btnShowNames.Width / 2, this.btnShowNames.Height / 2);
                    isShown = true;
                }
            }
            else
            {
                this.toolTipNames.Hide(this.btnShowNames);
                isShown = false;
            }

            if (btnShowNames.Enabled == true)
            {
                toolTipNames.Active = false;
            }
        }

    }
}