8 Replies - 404 Views - Last Post: 21 January 2019 - 03:14 PM Rate Topic: -----

#1 rowlanda38   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 21-January 19

using arrays

Posted 21 January 2019 - 01:38 AM

im creating the game hammurabi and im stuck ive got the base game all running with the codes for inputs and everything working but im at the stage where i now need to create the results after 10 years and im having trouble storing data after each year for example i need to store the the amount of people starved for every year and then work out the average and display, my code so far is as follows

// variables
       int year = 1;
       int arrivals = 0;
       int population = 100;
       int acres = 1000;
       int harvested = 0;
       int rats = 5;
       int trading = 18;
       int ratsAte = 0;
       int bushels = 2800;
       int bushelsHarvested = 0;
       int bushelsTrading = 0;
       int plague = 0;
       int starved = 0;

       

       


       private void btnAllocate_Click(object sender, EventArgs e)

       {
           

          
           


           // moves the game forward a year every time the allocate button is clicked
           year = year + 1;


           // random amount of people come to the city
           Random random = new Random();
           arrivals = random.Next(1, 16);

           // plague that halfs the population
           Random random4 = new Random();
           plague = random.Next(1, 21);
           if (plague == 1)
           {
               population = population / 2;
               MessageBox.Show("You were hit by a plague, half your population died");
           }
           else
           {
               plague = 0;
               
           }


           

           // working out the amount of people starved
           if (int.Parse(txtFeeding.Text) < (22 * population / 2))
           {
               MessageBox.Show("You starved " + population);
               
           }
           if (int.Parse(txtFeeding.Text) >= (22 * population / 2) && int.Parse(txtFeeding.Text) < 20 * population)
           {
               starved = ((20 * population) - (int.Parse(txtFeeding.Text))) / 20;
              
           }

           // possibilty of rats
           Random random2 = new Random();
           rats = random.Next(1, 11);

           if (rats == 5)
           {
               ratsAte = bushels * 10 / 100;
               lblRats.Text = "Rats ate " + ratsAte + " bushels.";
               
           }
           else
           {
               ratsAte = 0;
               lblRats.Text = "Rats ate 0 bushels";
               
           }

           // new population total
           population = population + arrivals - plague - starved;

           // randomised number for trading
           Random random3 = new Random();
           trading = random.Next(17, 27);

           // calculating the amount of acres that are left
           acres = acres + int.Parse(txtBuySell.Text);

           //randomised number of bushels harvested per acre
           Random random1 = new Random();
           harvested = random.Next(1, 6);


           // calculates the amount of bushels harvested and stores it in a variable

           bushelsHarvested = harvested * int.Parse(txtSeed.Text);

           bushels = bushels + bushelsHarvested  - ratsAte - int.Parse(txtFeeding.Text) - int.Parse(txtSeed.Text);

           


           // resets the textboxes
           txtBuySell.Text = ""; 
           txtFeeding.Text = "";
           txtSeed.Text = "";

           // changing the lables to show the new information remaining labels
           lblBushels.Text = "You now have " + bushels;
           lblNewPeople.Text = arrivals + " people came to the city.";
           lblHarvest.Text = "You harvested " + harvested + " bushels per acre.";
           lblPopulation.Text = "The city population is now " + population;
           lblTrading.Text = "land is trading at" + trading + " bushels per acre.";
           lblYear.Text = "In Year " + year + ", " + starved + " people starved.";
           lblRemaining.Text = bushels + " Remaining";



       }

       private void txtBuySell_Leave(object sender, EventArgs e)
       {
           // buy/sell calculation
           if (int.Parse(txtBuySell.Text) < 0)
           {
               bushelsTrading = Math.Abs(int.Parse(txtBuySell.Text) * trading);
           }
           else if (int.Parse(txtBuySell.Text) >= 0)
           {
               bushelsTrading = -int.Parse(txtBuySell.Text) * trading;
           }

           bushels = bushels + bushelsTrading;

           // calculating the amount of acres that are left
           acres = acres + int.Parse(txtBuySell.Text);

           lblAcres.Text = "The city now owns " + acres + " acres.";

           lblRemaining.Text = bushels + " Bushels Remaining";
       }

       private void txtFeeding_Leave(object sender, EventArgs e)
       {
           // warning user they dont have enough bushels
           if (int.Parse(txtFeeding.Text) > bushels)
           {
               MessageBox.Show("You do not have enough bushels in store");
               return;
           }

           lblRemaining.Text = (bushels - int.Parse(txtFeeding.Text)) + " Bushels Remaining";
       }

       private void txtSeed_Leave(object sender, EventArgs e)
       {
           // tells user that they can not seed more than 10 seed per person
           if (int.Parse(txtSeed.Text) > (10 * population))
           {
               MessageBox.Show("You can only Plant a max of 10 seeds per person");
               return;
           }
           if (int.Parse(txtSeed.Text) > acres)
           {
               MessageBox.Show("you can only plant a max of 1 bushel per acre");
               return;
           }
           

           lblRemaining.Text = (bushels - int.Parse(txtFeeding.Text)) + " Bushels Remaining";

This post has been edited by andrewsw: 21 January 2019 - 02:22 AM
Reason for edit:: added missing [code][/code] tags


Is This A Good Question/Topic? 0
  • +

Replies To: using arrays

#2 andrewsw   User is offline

  • Stealth IT
  • member icon

Reputation: 6743
  • View blog
  • Posts: 27,758
  • Joined: 12-December 12

Re: using arrays

Posted 21 January 2019 - 02:24 AM

Your title is "using arrays" but you haven't attempted, as far as I can see, to create an array, or other collection type, in your code.

If you want to store or persist values then, yes, you need an array or a List of some kind, or you would perhaps write values to a file.

What is your question about using arrays?



Please also provide any future code within code tags.
Was This Post Helpful? 0
  • +
  • -

#3 rowlanda38   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 21-January 19

Re: using arrays

Posted 21 January 2019 - 02:46 AM

i did try but other parts of the code stopped working so i deleted it
basically i want to add an array to it so that it collects and stores the amount of people starved after each year(click of the button) and then after the 10th year i want to display the average per year of the starved

thanks

This post has been edited by andrewsw: 21 January 2019 - 03:10 AM
Reason for edit:: removed previous quote, use the Reply button

Was This Post Helpful? 0
  • +
  • -

#4 andrewsw   User is offline

  • Stealth IT
  • member icon

Reputation: 6743
  • View blog
  • Posts: 27,758
  • Joined: 12-December 12

Re: using arrays

Posted 21 January 2019 - 03:13 AM

You need to show your attempt or ask a specific question about what is confusing you. Otherwise, we have nothing to go on and you are effectively just asking us either to teach you about arrays (from scratch) or to write code for you.
Was This Post Helpful? 0
  • +
  • -

#5 rowlanda38   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 21-January 19

Re: using arrays

Posted 21 January 2019 - 03:42 AM

thats what ive tried so far with no luck

    // array
            int[] averageDeaths = new int[10];
            int averageDeaths0 = starved;
            int averageDeaths1 = starved;
            int averageDeaths2 = starved;
            int averageDeaths3 = starved;
            int averageDeaths4 = starved;
            int averageDeaths5 = starved;
            int averageDeaths6 = starved;
            int averageDeaths7 = starved;
            int averageDeaths8 = starved;
            int averageDeaths9 = starved;


            int average, sum = 0;

            for (int i = 0; i < 10; i++)
            {

                sum = sum + averageDeaths[i];

            }
            average = sum / 10;

            if (year > 10)
            {
                lblArray.Text = average.ToString();
            }  

This post has been edited by andrewsw: 21 January 2019 - 04:02 AM
Reason for edit:: fixed failed [code][/code] tags

Was This Post Helpful? 0
  • +
  • -

#6 rowlanda38   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 21-January 19

Re: using arrays

Posted 21 January 2019 - 04:09 AM

https://hastebin.com/lerazefixi.cs

right so seems to be working to the point where it adds the total amount of starved each year together and displays that but doesnt actually work out the average
Was This Post Helpful? 0
  • +
  • -

#7 andrewsw   User is offline

  • Stealth IT
  • member icon

Reputation: 6743
  • View blog
  • Posts: 27,758
  • Joined: 12-December 12

Re: using arrays

Posted 21 January 2019 - 06:08 AM

Post your updated code directly here in the forum, not just as an external link.

On a quick look, though, your average will be 0 because all the array elements are assigned the value 0.
Was This Post Helpful? 1
  • +
  • -

#8 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 6767
  • View blog
  • Posts: 23,073
  • Joined: 05-May 12

Re: using arrays

Posted 21 January 2019 - 06:55 AM

Copying code from that external site (It's blocked from my work address, but not by my phone):
  private void Form1_Load(object sender, EventArgs e)
        {

        }
        // variables
        int year = 1;
        int arrivals = 0;
        int population = 100;
        int acres = 1000;
        int harvested = 0;
        int rats = 5;
        int trading = 18;
        int ratsAte = 0;
        int bushels = 2800;
        int bushelsHarvested = 0;
        int bushelsTrading = 0;
        int plague = 0;
        int starved = 0;
        double  average, sum = 0;



        private void btnAllocate_Click(object sender, EventArgs e)

        {
            // array
            int[] averageDeaths = new int[10];
            averageDeaths[0] = starved;
            averageDeaths[1] = starved;
            averageDeaths[2] = starved;
            averageDeaths[3] = starved;
            averageDeaths[4] = starved;
            averageDeaths[5] = starved;
            averageDeaths[6] = starved;
            averageDeaths[7] = starved;
            averageDeaths[8] = starved;
            averageDeaths[9] = starved;

            for (int i = 0; i < 10; i++)
            {

                sum = sum + averageDeaths[i];

            }

            average = sum / 10;

            if (year == 10)
            {
                lblArray.Text = average.ToString();
            }



As noted above, please post code here rather some external site.

Now regarding that code code, You'll likely want to move your array declaration into your class rather just scoped in the method. This is so that each time you have a new year come up (presumably in response to a timer that denotes a year elapsing or a button press to move to the next year), then you would store the number who have starved into the next entry in the array.

Now regarding the original code that you posted:
- It's really a poor idea to create multiple random number generator instances. It's better to create just one for the entire application (or class if need some isolation) and then just keep asking that single instance for the next random number that you need.
- It looks like you are trying to do some validation when the focus leaves the text box. This is the right approach when you are using Javascript, but since you are writing code in WinForms, the more appropriate event to use is the Validating event.

And lastly: Why are you using WinForms? WinForms is at end of life. You should be using WPF or Xamarin.Forms. Other than using a more current platform whose concepts and ideas are more transportable to other GUIs, if you use WPF and Xamarin the way they are meant to be used, you will have a good separation between the UI, your data, and your program logic. With your that kind of separation, it'll be clearer to you that your array will have to live in a scope that persists through each yearly cycle.
Was This Post Helpful? 1
  • +
  • -

#9 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 202
  • View blog
  • Posts: 1,129
  • Joined: 05-December 13

Re: using arrays

Posted 21 January 2019 - 03:14 PM

Your project looks like a jolly good fun project, but sadly I don't have loads of time to play with this, so here is something I've quickly wrote up in 15 mins. Try this class instead for getting and setting your variables. What you're doing is pretty straight forward, and so why not throw everything into a static class?

While this works fine as pseudo code, and if used; you may want to extend on to the conditional logic to add additional checks for different values to make it a bit more random.

As for your array. I don't see why you need it, and so I removed it. If you want to calculate averages, you are on the right track by calculating and dividing, but even still, there is no need for an array that I can see. I was thinking of adding one to gather some data as each year is elapsed, but I think you should get to know classes and working with classes before you even consider that step.

Try implementing a similar class to this, as it'll make the handling of your variables easier to maintain and by right; this is how you should be doing it. btnAllocate_Click demonstrates how to work with the class. It is only pseudo stuff, so you do need to edit and tweak it to your liking.

It currently outputs something like this ::
Population is currently 100 inhabitants
1 Years has past
We now have 2 new inhabitants
We now have a population of 102 inhabitants
You were hit by a plague, some of your settlement died. You now have a population of 54
You starved 39 of your settlement


Hope it helps!

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAllocate_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Population is currently " + Vars.HasPopulation + " inhabitants" );
            if (Vars.IsYear >= 0 && Vars.IsYear <= 9) //Should we limit years to 10 years?
            { Vars.IsYear++; }
            Console.WriteLine(Vars.IsYear + " Years has past");
            Vars.NextRandomInhabitants = Vars.NextRandomInhabitants; Console.WriteLine("We now have " + Vars.NextRandomInhabitants + " new inhabitants");
            Vars.HasPopulation += Vars.NextRandomInhabitants; Console.WriteLine("We now have a population of " + Vars.HasPopulation + " inhabitants");
            //Start a plague
            Vars.NextRandomPlague = Vars.NextRandomPlague;
            if (Vars.TotalInPlague <= 30) { Vars.HasPopulation = Vars.HasPopulation - Vars.TotalInPlague; } // See ' NextRandomPlague ' to set these values for the desruction of your population
            else if (Vars.TotalInPlague >= 30 && Vars.TotalInPlague <= 60) { Vars.HasPopulation = Vars.HasPopulation - Vars.TotalInPlague; }
            else if (Vars.TotalInPlague >= 60 && Vars.TotalInPlague <= 90) { Vars.HasPopulation = Vars.HasPopulation - Vars.TotalInPlague; }
            Console.WriteLine("You were hit by a plague, some of your settlement died. You now have a population of " + Vars.HasPopulation);
            //Ok who gets fed? 
           int fednow = -1; bool parsed = int.TryParse(txtFeeding.Text, out fednow); //Changed int parse to try parse. Don't use parse unless you wrap it in try catch blocks.

               if (fednow != -1 && fednow >= Vars.HasPopulation && Vars.HasPopulation > 0)
               { Console.WriteLine("Everyone got a good meal, your settlement is happy with " + Vars.WasStarved + " inhabitants starved"); }
               else if (fednow != -1 && fednow <= Vars.HasPopulation && Vars.HasPopulation > 0)
               { Vars.WasStarved = Vars.HasPopulation - fednow; Console.WriteLine("You starved " + Vars.WasStarved + " of your settlement"); }
               else { Console.WriteLine("You don't have a settlement to feed. Your population is " + Vars.HasPopulation + " inhabitants"); }
            //Start a rat infestation 
               Vars.NextRandomRatInfestation = Vars.NextRandomRatInfestation;
               if (Vars.HadRats >= 1)
               {
                   //Do your calculations for how many bushels they eat
               }
            //Get the new population was already done by subtracting those we lost. Get new value of population by calling
               var howManyRemain = Vars.HasPopulation;
            // Add randomised number for trading

            //Calculating the amount of acres that are left by using the new functions from the Vars class

            //Randomised number of bushels harvested per acre by using the new functions from the Vars class

            //Calculates the amount of bushels harvested and stores it in a variable by using the new functions from the Vars class

            //Resets the textboxes - I recommend you add a class for resetting stuff

            //Changing the lables to show the new information remaining labels by using the new functions from the Vars class
        }
    }
    public static class Vars
    {
        private static Random random = new Random();
        private static int[] averageDeaths = new int[10];
        private static int year;
        private static int arrivals = 0;
        private static int population = 100;
        private static int acres = 1000;
        private static int harvested = 0;
        private static int rats = 5;
        private static int trading = 18;
        private static int ratsAte = 0;
        private static int bushels = 2800;
        private static int bushelsHarvested = 0;
        private static int bushelsTrading = 0;
        private static int plague = 0;
        private static int starved = 0;
        private static int fed;
        private static double average, sum = 0;

        //Start Random Event Generations
        public static int NextRandomTrade
        {
            get { return trading; }
            set { trading = random.Next(17, 27); }
        }
        public static int NextRandomRatInfestation
        {
            get { return rats; }
            set { rats = random.Next(1, 11); }
        }
        public static int NextRandomInhabitants
        {
            get { return arrivals; }
            set { arrivals = random.Next(1, 16);  }
        }
        public static int NextRandomPlague
        {
            get { return plague; }
            set { plague = random.Next(15, 90); } //Play with these values to adjust the devistation a plague has on a population. 
        }
        public static int NextRandomHarvest
        {
            get { return harvested; }
            set { harvested = random.Next(1, 6); }
        }
        //End Random Generations Of Randomw Events (Using one random generator)
        //Get Set for variables. These should be used directly to ascertain the new values aftrer a random event. 
        public static int[] AverageDeaths
        {
            get { return averageDeaths; }
            set { averageDeaths = value; }
        }
        public static int IsYear
        {
            get { return year; }
            set { year = value; }
        }
        public static int WereFed
        {
            get { return fed; }
            set { fed = value; }
        }
        public static int HasArrivals
        {
            get { return arrivals; }
            set { arrivals = value; }
        }
        public static int HasPopulation
        {
            get { return population; }
            set { population = value; }
        }
        public static int TotalAcres
        {
            get { return acres; }
            set { acres = value; }
        }
        public static int HadHarvested
        {
            get { return harvested; }
            set { harvested = value; }
        }
        public static int HadRats
        {
            get { return rats; }
            set { rats = value; }
        }
        public static int HadTraded
        {
            get { return trading; }
            set { trading = value; }
        }
        public static int RatsAte
        {
            get { return ratsAte; }
            set { ratsAte = value; }
        }
        public static int HadBushels
        {
            get { return bushels; }
            set { bushels = value; }
        }
        public static int TotalBushelsHarvested
        {
            get { return bushelsHarvested; }
            set { bushelsHarvested = value; }
        }
        public static int TradingBushels
        {
            get { return bushelsTrading; }
            set { bushelsTrading = value; }
        }
        public static int TotalInPlague
        {
            get { return plague; }
            set { plague = value; }
        }
        public static int WasStarved
        {
            get { return starved; }
            set { starved = value; }
        }
        public static double EstAverage
        {
            get { return average; }
            set { average = value; }
        }
        public static double TotalSum
        {
            get { return sum; }
            set { sum = value; }
        }
    }


Also, don't forget when a plague hits, it will probably send your population into negative values. In which case, you will need to make a check and see if population is less than zero and then set the population to equal zero. ;)

This post has been edited by Sheepings: 21 January 2019 - 03:29 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1