Math Drop Program Using Arrays & Array Class Methods

MathDropCd

MathDropMainForm

MathDropResultsForm

This was a program that gave you a random list of arithmetic problems. You would drag the math problem from the left-side to the correct answer on the right-side. Each answer was stored in a two-dimensional array. This program taking advantage of one-dimensional, two-dimensional, and jagged arrays. I realize you can do more with and Array List or Collections. I just wanted to see what would need to happen is I chose to use arrays instead. I might re-write this later using Collections instead simply for the ease of coding. That and adding more arithmetic problems and answers. Here’s the source.


MainForm Class


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MathDrop
{
    public partial class MainForm : Form
    {
        private GameSettings myGameSettings = new GameSettings();     //Declaring an instance for the game settings.
        private Button[,] _buttons;                                   //The Buttons array.
        private Question[] _questions;                                //The questions array.
        private Question[][] _answers;                                //The answers jagged array.
        private string[][] _results;                                  //Results jagged array.

        public MainForm()
        {
            //Calling the method that will create the Button controls and arrays.
            createButtonsAndArrays();

            InitializeComponent();

            //Calling the method to clear the questions and answers arrays. Then create new questions and populate
            //the ListBox.
            resetProgram();
        }

        //Method that exits and closes the program.
        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //If the reset option is selected from the main menu then the resetProgram() method is called.
            resetProgram();
        }

        private void mainSplitContainer_SplitterMoved(object sender, SplitterEventArgs e)
        {
            //If the splitter is moved force a layout event to occur.
            this.PerformLayout();
        }

        private void resultsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ResultsForm resultsForm = new ResultsForm(_results);
            resultsForm.ShowDialog();
        }

        private void createButtonsAndArrays()
        {
            //Allocating a two-dimensional array for the squares using Button controls.
            _buttons = new Button[myGameSettings.SquaresCount, myGameSettings.SquaresCount];

            //Allocate a one dimensional array for the questions.
            _questions = new Question[myGameSettings.NumberOfQuestions];

            //Allocating a jagged array for our answers.
            _answers = new Question[myGameSettings.SquaresCount * myGameSettings.SquaresCount][];

            //Allocating a jagged array that will store the answers to the questions the user picks.
            _results = new string[1][];

            //Looping thru and creating each Button control and properites.
            for (int rows = 0; rows < myGameSettings.SquaresCount; rows++)     
            {
                for (int columns = 0; columns < myGameSettings.SquaresCount; columns++)
                {
                    //Create and assign a new Button for each.
                    Button button = new Button()
                    {
                        Text = myGameSettings.ButtonAnswer.ToString(),
                        BackColor = Color.White,
                        FlatStyle = FlatStyle.Popup,
                        Cursor = Cursors.Hand,
                        AllowDrop = true
                    };
                    _buttons[rows, columns] = button;

                    //Increment the answer value so the button text will change thru each iteration of the loop.
                    myGameSettings.ButtonAnswer++;

                    //Adding an event handler for the DragEvent event for each button.
                    _buttons[rows, columns].DragEnter += new DragEventHandler(buttonDragEnterHandler);

                    //Adding an event handler for the DragDrop event for each button.
                    _buttons[rows, columns].DragDrop += new DragEventHandler(buttonDragDropHandler);
                }
            }
        }

        private void buttonDragEnterHandler(object sender, DragEventArgs e)
        {
            //Only show the drag effects if the data is the correct type.
            if (!e.Data.GetDataPresent(typeof(Question)))
                e.Effect = DragDropEffects.None;
            else
                //Show the Move effect cursor.
                e.Effect = DragDropEffects.Move;
        }

        private void buttonDragDropHandler(object sender, DragEventArgs e)
        {
            //Only process the drag operation if the data is the correct type.
            if (e.Data.GetDataPresent(typeof(Question)))
            {
                //Extract the question from the drag data and make sure it isn't null.
                Question question = (Question)e.Data.GetData(typeof(Question));
                if (question != null)
                {
                    Button button = sender as Button;
                    //MessageBox.Show(question + "\n" + button.Text + " Selected");    //Test code to show the question and text of the box being dragged into. Can remove later.

                    //Store all of the answers in the jagged array.
                    int answer;
                    if (!int.TryParse(button.Text, out answer))
                        answer = 0;

                    if (_answers
== null) //The jagged array hasn't been created yet, so create the first entry. _answers
= new Question[1]; else //There are already entries in the jagged array, resize the length to + 1. Array.Resize(ref _answers
, _answers
.Length + 1); //Now lets test to see if the answer is correct, display a dialog box. //If correct remove the question from the listbox. if (button.Text == question.TheAnswer.ToString()) { //Remove the question from the listbox. questionsListBox.Items.RemoveAt(questionsListBox.SelectedIndex); myGameSettings.Correct = true; //Setting the answer bool to true if the answer is correct. MessageBox.Show(button.Text + " is correct!"); } else { myGameSettings.Correct = false; //Setting the answer bool to false if the answer is in-correct. MessageBox.Show("Wrong answer, try again."); } if (!myGameSettings.Correct) { //Setting the result string if the answer is incorrect. myGameSettings.Result = "Answer: " + answer + " - " + "Question: " + question + " (Incorrect)"; //Adding the results string to the jagged array. _results[myGameSettings.Counter] = new string[1] { "Answer: " + answer + " - " + "Question: " + question + " (Incorrect)" }; //Counter increment for the jagged array index. This keeps us from getting an arrayOutOfBounds exception. Array.Resize(ref _results, _results.Length + 1); myGameSettings.Counter++; } else { //Setting the result string if the answer is correct. myGameSettings.Result = "Answer: " + answer + " - " + "Question: " + question + " (Correct)"; //Adding the results string to the jagged array. _results[myGameSettings.Counter] = new string[1] { "Answer: " + answer + " - " + "Question: " + question + " (Correct)" }; //Counter increment for the jagged array index. This keeps us from getting an arrayOutOfBounds exception. Array.Resize(ref _results, _results.Length + 1); myGameSettings.Counter++; } } } } private void questionsListBox_MouseMove(object sender, MouseEventArgs e) { //Make sure we have the mouse button down when dragging to the answer and a valid //list item is under the mouse. if (e.Button == MouseButtons.Left) { if (questionsListBox.SelectedIndex != ListBox.NoMatches) questionsListBox.DoDragDrop((Question)questionsListBox.Items[questionsListBox.SelectedIndex], DragDropEffects.All); } } private void MainForm_Layout(object sender, LayoutEventArgs e) { //Getting the height and width for each Button using the inside height and width of the //right-hand panel (Panel2) of the panel control. myGameSettings.ButtonWidth = mainSplitContainer.Panel2.ClientRectangle.Width / myGameSettings.SquaresCount; myGameSettings.ButtonHeight = mainSplitContainer.Panel2.ClientRectangle.Height / myGameSettings.SquaresCount; //Looping thru and setting the location and dimensions of each Button control. for (int rows = 0; rows < myGameSettings.SquaresCount; rows++) { for (int columns = 0; columns < myGameSettings.SquaresCount; columns++) { _buttons[rows, columns].SetBounds(myGameSettings.ButtonWidth * columns, myGameSettings.ButtonHeight * rows, myGameSettings.ButtonWidth, myGameSettings.ButtonHeight); } } //Adding the Button controls to the Panel collection. if (mainSplitContainer.Panel2.Controls.Count == 0) //Checking to make sure the Panel is empty. { for (int rows = 0; rows < myGameSettings.SquaresCount; rows++) { for (int columns = 0; columns < myGameSettings.SquaresCount; columns++) mainSplitContainer.Panel2.Controls.Add(_buttons[rows, columns]); } } } private void resetProgram() { //Setting things up to get a random number. Random random = new Random(); //Getting the maximum answer for the questions. myGameSettings.setMaxAnswer(); //Clearing the questions array. Array.Clear(_questions, 0, _questions.Length); //Clearing answers jagged array and setting all the elements to null. for (int i = 0; i < _answers.Length; i++) { if (_answers[i] != null) { Array.Clear(_answers[i], 0, _answers[i].Length); _answers[i] = null; } } //Coming up with the random questions. for (int i = 0; i < myGameSettings.NumberOfQuestions; i++) { myGameSettings.RandomLeft = random.Next(0, myGameSettings.MaxAnswer + 1); myGameSettings.RandomRight = random.Next(0, myGameSettings.MaxAnswer - myGameSettings.RandomLeft + 1); //Calling the method that will get and set the answer to the math equation. myGameSettings.setAnswer(); //Forming the string to display in the left side of the Panel. string question = myGameSettings.RandomLeft.ToString() + " + " + myGameSettings.RandomRight.ToString(); //Adding the questions to the questions array via a constructor. _questions[i] = new Question() { TheQuestion = question, TheAnswer = myGameSettings.Answer }; } //Reset any existing questions in the ListBox and add the new ones upon refresh or program load. questionsListBox.Items.Clear(); foreach (Question items in _questions) { questionsListBox.Items.Add(items); } } } }

ResultsForm Class


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MathDrop
{
    public partial class ResultsForm : Form
    {
        public ResultsForm()
        {
            InitializeComponent();
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public ResultsForm(string[][] results)
        {
            InitializeComponent();

            //Using the try / catch method to catch the exception that's thrown when accessing the array elements this way.
            try
            {
                //Iterating thru the jagged array and displaying the element data.
                for (int i = 0; i < results.Length; i++)
                {
                    //Console.WriteLine(results[i][0]);    //Test line to see the data. Can remove later.
                    resultsListBox.Items.Add(results[i][0]);
                }
            }
            catch (NullReferenceException)
            {

            }
        }
    }
}

Question Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathDrop
{
    class Question
    {
        private string _theQuestion;
        private int _theAnswer;

        public string TheQuestion
        {
            get { return _theQuestion; }
            set { _theQuestion = value; }
        }

        public int TheAnswer
        {
            get { return _theAnswer; }
            set { _theAnswer = value; }
        }

        //We will over-ride the ToString() method so when adding an array to the ListBox it will
        //call this version to display the questions.
        public override string ToString()
        {
            return _theQuestion;
        }
    }
}

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s