Thread: Help with Variables & updating Variables

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    5

    Help with Variables & updating Variables

    Hi guys,

    Bit of a long winded one this so please bare with me!

    I am fairly new to C programming, I've been doing it at College now for about 6 - 7 months and I'm just picking up the basics. I've worked with PHP before I went to college, but I'm still considered a novice.

    What I am trying to do:

    I am working on a C based text game which works on the principle of buying stocks and shares. A player has 100 turns in which to wheel and deal to make the biggest profit before the end of the game.


    The problems:

    I am having real trouble passing information generated via arguments in functions back to variables to update them.
    For example, I have a buyShares function which asks at which comodity a user wishes to purchase and how much. The results of that information are to be used to calculate how much X ammount of stock at X price will cost. It should then deduct that value from a bank balance variable which is held in the function playGame.

    Now, while I can pass most variable information into the functions, I fall down when it comes to updating the variables with new information and I can't for the life of me work out how to do it.


    Not to be lazy, I spent many an hour over a hot google yesterday but I can't find anything that I can make sense of to use as an example.
    The closest thing I can find which seems like it is what I want is with passing by reference or pointer but I don't understand how to do it. All the examples are a little complicated.

    Here is my code in its entirity... Please note that it is still very much in protototype stage.
    The function which deals with all the game play is called playGame and the function giving me all the grief passing results back and forth is buyShares.

    You will notice there are lots of nested functions going on and so it seems to me, the deeper into the levels of code structure the information I want to get out of an argument or function is, the harder it is to get back out!

    Code:
    //Header Files
    #include<stdio.h>
    #include<time.h>
    #include<string.h>
    #include<stdlib.h>
    #include<conio.h>
    #include<windows.h>
    
    //Function Prototypes - First declaration
    void instructions();
    void playGame();
    void highRollers();
    void quitGame();
    
    //BETA FUNCTION PROTOTYPES - Testing Purposes!!!!
    float sharePrices();
    float buyShares(float oilPrice, float coalPrice, float gasPrice, float electricityPrice, float cottonPrice, float sugarPrice, int turnCount, int numberofUnits, float bankBalance);
    
    
    
    
    
    int main()
    {
        //BETA VARIABLES
    
        
        
        
        
        //----------------------------------------------------------------------------------\\
        // Top Level Menu Construction - From here, all relevant top level choices are made \\
        //----------------------------------------------------------------------------------\\
        
        //Variable for storing mainMenu option selection
        char mainMenu;
        
        //Clear the screen before displaying options
        system("cls");
        
        //Display mainMenu options
        printf(" ______________________\n");
        printf("|                      |\n");        
        printf("|       MAIN MENU      |\n");
        printf("|______________________|\n\n");
             
        printf("\nPlease choose an option: \n\n");
        printf(" 1. Instructions\n\n");
        printf(" 2. Play Game\n\n");
        printf(" 3. High Rollers\n\n");
        printf(" 4. Quit Game\n");
        printf("\n\n");
        
        //Get user selection
        scanf("%c", &mainMenu);
        _flushall();
        
        ///Switch for deciding which option was selected - Compares the value held in the mainMenu variable
        switch(mainMenu)
        {
            case '1':                          
                 instructions();
                 break;
            
            case '2':
                 playGame();
                 break;
                 
            case '3':          
                 highRollers();
                 break;
            
            case '4':
                 quitGame();
                 break;
                 
           default:
                   printf("Invalid Entry");
                   break;     
        
        }
        //--------------------\\
        // End Top Level Menu \\
        //--------------------\\
        
        
    return 0;            
    }//End Main
    
    
    //--------------------------------------------------------------------------------------------
    // A simple menu function for showing the instructions and a means to return to the main menu 
    //--------------------------------------------------------------------------------------------
    void instructions()
    {
        
        //Variable for storing instructionMenu option selection
        char instructionMenu;
        
        //Clear the screen before displaying options
        system("cls");
        
        //Display instructional information - To be completed!!!
        printf("Instructional Stuff\n\n");
        
        //Display instructionMenu options
        printf("Press 1 followed by <ENTER> to return to the main menu\n\n");
        
        //Get user selection
        scanf("%c", &instructionMenu);
        _flushall();
        
        ///Switch for deciding which option was selected by the user - Compares the value held in the instructionMenu variable
        switch (instructionMenu)
        {
            case '1':
                 main();
                 break;   
            default:
                 system("cls");
                 printf("An Error Has Occoured\n\n");
                 system("pause");
                 main();      
                 break;
        }
        
         
    }
    
    
    //---------------------------------------------------------------------------------------------------------
    // This is going to be the core of the "Game Engine..." All gameplay will end up running via this function 
    //---------------------------------------------------------------------------------------------------------   
    void playGame()     
    {
         
         //Turn Counter - All Game play must go within the do loop.. Once a "turn" has been completed, +1 to turnCount
         //This constitutes the overall counter and control of how many turns a player has to make their max profits       
         int turnCount = 0;
         do
         {
             //Adds an incremental value of 1 to the turnCount variable at the start of each itteration of the do loop
             turnCount++;
             
             //Game play coding here - Will poss need to pass data between the function calls that will exist here
             
             
             
    //BETA AREA!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!------------------------------------------------------
                 
                     //Store Game Data Variables
                     
                     //Stores buy or sell option selection
                     char buySell;
                     
                     //Player Name - Store current players name - to be used with high score data later
                     char playerName[20];
                     
                     //Bank Balance @ start will not hold updated balance - just used to hold initial starting figure..   
                     float bankBalance = 500;
                     
                     
                     //Number of Individual Shares Owned
                     int oilSharesOwned = 0;
                     int coalSharesOwned = 0;
                     int gasSharesOwned = 0;
                     int electricitySharesOwned = 0;
                     int sugarSharesOwned = 0;
                     int cottonSharesOwned = 0;
                     
                     //Total number of shares owned
                     int numberofUnits = 0; 
                     
                     //Get random share prices and assign them to each commodity as a float variable
                     float oilPrice = sharePrices(); 
                     float coalPrice = sharePrices(); 
                     float gasPrice = sharePrices();
                     float electricityPrice = sharePrices();
                     float sugarPrice = sharePrices();
                     float cottonPrice = sharePrices();
                     
                     
                     //Clear the screen before displaying Data
                     system("cls"); 
                     
                     
                     //Build Play Screen Layout Demo Here
                     
                     //printf("Please type in Your Name followed by <ENTER>:\n\n");
                     //Obtain the input through the keyboard
                     //fgets(playerName, sizeof(playerName), stdin);
                    // _flushall();
        
                     
                     
                     system("cls");
                     printf("Your Current Balance is: %.2f\n\n", bankBalance);
                     
                     //Find a way of setting start date and count days and then display day and date - add realism..?
                     
                     printf("Todays Share Prices Are As Follows:\n\n");
                     
                     printf("%i. Oil Price $%.2f\n", turnCount, oilPrice);
                     printf("%i. Coal Price: $%.2f\n", turnCount, coalPrice);
                     printf("%i. Gas Price: $%.2f\n", turnCount, gasPrice);
                     printf("%i. Electricity Price: $%.2f\n", turnCount, electricityPrice);
                     printf("%i. Sugar Price: $%.2f\n", turnCount, sugarPrice);
                     printf("%i. Cotton Price: $%.2f\n", turnCount, cottonPrice);
                     
                     //Display Buy Sell Menu
                     printf("\n\nWould you like to (B)uy or (S)ell?\n\n");
                     scanf("%c", &buySell);
                     _flushall();
                     
                     switch (buySell)
                     {
                         case 'b':
                              buyShares(oilPrice, coalPrice, gasPrice, electricityPrice, cottonPrice, sugarPrice, turnCount, numberofUnits, bankBalance);
                              break;
                              
                         case 's':
                              printf("Sell some ........ function");
                              break;
                              
                         default:
                              printf("Some ........ is broken waffle here");
                              break;                
                            
                            
                     }
                     
                     
                 
    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!---------------------------------------------
                 
                 
                 
                 
                 
                 
                 
                 
                 //Temporary while testing "Game Engine" - Currently halts the program so you can see stuff
                 system("pause");
                         
         }while(turnCount < 100);//While condition used to specify the amount of maximum turns for the game
         
         
         //Temporary End Game Message
         system("cls");
         printf("Thank you for playing, your score was ......... Don't give up your day job!\n\n");
         
         //Temporary while testing "Game Engine" - Currently halts the program so you can see stuff
         system("pause");
         
    }
    
    
    //-----------------------------------------------------------------------------------------------------
    // A simple function for writing high scores to a file to be read back later when scores are displayed 
    //-----------------------------------------------------------------------------------------------------    
    void highRollers()
    {
         
         
    }
    
    
    //----------------------------------------------------------------------------------------------------------------------
    // A function devised to allow users to exit the game at any time using the press of a single designated key or similar 
    //----------------------------------------------------------------------------------------------------------------------    
    void quitGame()
    {
         
         
         
    }     
    
    
    //BETA FUNCTIONS - Functions created for testing purposes
    
    //Generate random prices for shares
    float sharePrices()
    {
        //Needs to be more random & accurate to within a given price range eg $1.00 - $200.00
        float i = (float)rand() / (float)100;
        return i;  
    }
    
    
    //Buy function - Value of the generated coalPrice variable is passed into this function! Will need to add all comodities to this function
    float buyShares(float oilPrice, float coalPrice, float gasPrice, float electricityPrice, float cottonPrice, float sugarPrice, int turnCount, int numberofUnits, float bankBalance)
    {
        system("cls");
        
        char buySharesOption;
        char unitsOption;
        //Test Variable is passed
        //printf("The price of coal is still: $%.2f\n\n", coalPrice);
        
        
        //Not decided how best to develop this area... May need a switch if it allows me to pass data deep enough
        //If not a bunch of ifs and else --
        //First menu here on in will be to discover which comodity is being purchased.
        //THe second menu will establish the quantity being purchased.
        //Once the quantity and comodity is established, we can then check to see if the number of stocks attempting to be purchased
        //will exceed the maximum stock level one play may hold at one time.. Currently 100 shares.
        //We can use if statements for this purpose.
        //Then we can move on to do the maths and worry about updating the bank balance & sharesowned variables
        //Rememeber to store the number of purchased comodity within the apropriate variable for that comodity.
        
        printf("Which comodity would you like to purchase today\n\n");
        
        printf(" 1. Oil\n\n");
        printf(" 2. Coal\n\n");
        printf(" 3. Gas\n\n");
        printf(" 4. Electricity\n\n");
        printf(" 5. Cotton\n\n");
        printf(" 6. Sugar\n\n");
        printf(" 7. Back to Shares\n\n");
        
        scanf("%c", &buySharesOption);
        _flushall();
        
        printf("\nNow please enter the number of shares you wish to buy:\n\n");
        printf("You currently own %i shares\n\n", numberofUnits);
        
        scanf("%c", &unitsOption);
        _flushall();
        
        if(buySharesOption == '1')
        {
           float bankBalance = bankBalance - (oilPrice * unitsOption);
           //numberofUnits+unitsOption;
           return bankBalance;     
        }//Etc,...
        
        
        //Do some clever maths here after finding out which comodity is being purchased & in what quantity
        
        //  bankBalance= bankBalance - (sharePrice * noUnits);
        
        
        
              
    }
    The best example of what I want to do is shown just above with that little bit of mathematics.....
    The function buyShares, as you can see, has all this information which comes in.
    Now I want to for example, update the variable bankBalance with the results of that sum above, but I want to update the version of bankBalance located in playGame() where all my game play data variables are intitally declared.
    I've been told when I very first started my C programming module that Globals are a bad idea so that's that out, I'm not supposed to use them and so we are encouraged not to use them.

    Does anyone have a simple example which will allow me to do what I need, preferably demonstrated based around my scenario so I can relate to it?

    I would ask my lecturer but he has been off ill in the week and I can't usually get hold of anyone on a weekend.

    This is a personal project by the way to help me develop my knowledge and not an assignment so I'm not cheating! Just stuck lol


    Thanks guys, sorry for the length but in my experience, I've learned to give as much info as possible
    Last edited by DrC; 01-29-2011 at 04:14 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Accessing Variables
    By vileoxidation in forum C++ Programming
    Replies: 10
    Last Post: 10-05-2009, 07:58 AM
  2. Protected / Private Variables accessable.
    By +Azazel+ in forum C++ Programming
    Replies: 19
    Last Post: 09-08-2009, 07:39 PM
  3. Remotely Creating Variables
    By Rajin in forum C++ Programming
    Replies: 1
    Last Post: 04-26-2005, 11:20 PM
  4. Declaring an variable number of variables
    By Decrypt in forum C++ Programming
    Replies: 8
    Last Post: 02-27-2005, 04:46 PM
  5. hwnd and variables in them
    By underthesun in forum Windows Programming
    Replies: 6
    Last Post: 01-16-2005, 06:39 PM