Like Tree7Likes
  • 5 Post By laserlight
  • 2 Post By oogabooga

What's wrong with my code?

This is a discussion on What's wrong with my code? within the C++ Programming forums, part of the General Programming Boards category; In the book I'm reading it says for extra practice, to use loops and functions to make an advanced player ...

  1. #1
    Registered User GigaRoid's Avatar
    Join Date
    Aug 2011
    Location
    Everywhere
    Posts
    23

    Exclamation What's wrong with my code?

    In the book I'm reading it says for extra practice, to use loops and functions to make an advanced player inventory program. That part I can do, but it says to make user to program commands like in the old game "adventure". It was just too much for me to do apparently since it has multiple problems. I don't know what's wrong, so here's the whole program:


    Code:
    #include <cstdarg>
    #include <iostream>
    #include <iomanip>
    #include <windows.h>
    #include <string>
    
    /* define windows colors...*/
        #define w_dblue 1
        #define w_dgreen 2
        #define w_dcyan 3
        #define w_dred 4
        #define w_dviolet 5
        #define w_dyellow 6
        #define w_dgray 8
        #define w_bule 9
        #define w_green 10
        #define w_cyan 11
        #define w_red 12
        #define w_violet 13
        #define w_yellow 14
        #define w_white 15
        //7 = default
    
    using namespace std;
    
    void setColor(int color) //writes the specific string in the selected color
    {
        // WinApi header
        HANDLE  hConsole;
        hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        SetConsoleTextAttribute(hConsole, color);
    }
    
    //returns fail if answer is not one of the options,
    //bool exact controls whether answer is an option or answer contains an option
    string pickTwo(string answer, string one, string two)
    {
        if (answer!=one && answer!=two)
        return "fail";
        else
        return answer;
    }
    
    void coutWfe(string str)
    {
        cout << str;
        cin.get();
    }
    /* Item Store */
    
    /*COLOR CODE:
    Gray = User input and messages
    Cyan = Important messages
    Red = Danger and alerts
    Violet = Conversation
    */
    
    int main()
    {
        int itemMax=6;
        int item=0;
        bool noGo=0;
        int error=0;
        int subX=0;
        int subY=0;
    
        string name="";
        string choice=""; //the non-command part of the base
        string answer=""; //the command part of the base
        string base=""; //the base for a full command
        string inventory[itemMax]; // leave inventory[0] empty
    
        //commands
        int cmndMax=12;
        int cmndNum=0;
        string command[cmndMax]; //leave command[0] empty
        command[cmndNum++]="drop";
        command[cmndNum++]="take";
        command[cmndNum++]="check inventory";
        command[cmndNum++]="leave";
        cout << "Welcome to Inventory Test\n\n";
        coutWfe("Choose a name...\n\n");
        cin >> name;
        coutWfe("\nYou have been named " + name + " \n\n");
        coutWfe("Chapter 1: I'm just buying something, doesn't really need a chapter...\n\n");
        coutWfe("You are walking through the forest...\n");
        setColor(w_cyan);
        coutWfe("You stumble upon a convinient chest!\n"); setColor(7);
        cout << "What do you do?\n";
        cin >> answer;
    
        while (pickTwo(answer, "open", "ignore")=="fail")
        {
            setColor(w_red);
            cout << "You can't do that...\n";
            setColor(7);
            cin >> answer;
        }
    
        coutWfe("\n\nYou choose to "+answer+" the chest...\n\n");
        if (answer=="ignore")
        {
            setColor(w_cyan);
            coutWfe("You're an idiot!"); setColor(7);
            return 0;
        }
        setColor(w_cyan);
        coutWfe("You found 10 items!\n\n"); setColor(7);
    
        string boxItem[10]; //leave boxItem[0] empty
        int boxNum=0;
        int boxMax=10;
        boxItem[boxNum++]="jewel";
        boxItem[boxNum++]="sheild";
        boxItem[boxNum++]="dagger";
        boxItem[boxNum++]="toy bear";
        boxItem[boxNum++]="orange";
        boxItem[boxNum++]="ring";
        boxItem[boxNum++]="red potion";
        boxItem[boxNum++]="black potion";
        boxItem[boxNum++]="green potion";
        for(int i=0; i < 9; ++i)
        {
            cout << boxItem[i] << endl;
        }
    
        cout << "\nWhat do you do?\n\n";
        cmndNum=0;
        noGo=1;
    
        while (cmndNum!=cmndMax && noGo==1)
        {
            cin >> base;
            for (cmndNum=0; cmndNum < cmndMax; ++cmndNum)
            {
                if (base.find(command[cmndNum])==0)
                {
                    choice=base;
                    answer=base;
                    choice.erase(0, command[cmndNum].length());
                    answer.erase(command[cmndNum].length(), answer.length());
                    break;
                }
                if (cmndNum==cmndMax && base.find(command[cmndNum])!=0)
                {
                    error+=1;
                }
            }
            if (answer==command[1])
            {
                for (item=0; item < itemMax; ++item)
                {
                    if (inventory[item]==choice)
                    {
                        choice=inventory[item];
                        subX=item;
                        inventory[item]="";
                        break;
                    }
                    if (item==itemMax && inventory[item]!=choice)
                    {
                        setColor(w_red);
                        cout << "You don't have that item!"; setColor(7);
                        error+=1;
                    }
                }
                for (int i=subX; i < itemMax; ++i)
                {
                    inventory[i-1]=inventory[i];
                    inventory[i]="";
                }
                if (error==0)
                {
                    setColor(w_cyan);
                    cout << "You dropped your " << choice << "!"; setColor(7);
                    cout << "What else?...";
                    subX=0;
                }
            }
            if (answer==command[2])
            {
                for (boxNum=0; boxNum < boxMax; ++boxNum)
                {
                    if (boxItem[boxNum]==choice)
                    {
                        choice=boxItem[boxNum];
                        boxItem[boxNum]="";
                        subX=boxNum;
                        break;
                    }
                    if (boxNum==boxMax && boxItem[boxNum]!=choice)
                    {
                        error+=1;
                    }
                }
                for (int i=subX; i < boxMax; ++i)
                {
                    boxItem[i-1]=boxItem[i];
                    boxItem[i]="";
                }
    
                for (item=0; item < itemMax; ++item)
                {
                    if (inventory[item]=="");
                    {
                        inventory[item]=boxItem[subX];
                        break;
                    }
                    if (item==itemMax && inventory[item]!="")
                    {
                        setColor(w_red);
                        cout << "You have no room for that!\n"; setColor(7);
                    }
                }
            }
    
            if (error!=0)
            {
                setColor(w_red);
                cout << "You can't do that! There were " << error << " problems.\nTry again...\n\n"; setColor(7);
                noGo=1;
                error=0;
            }
        }
    }
    It doeesn't give any errors. It just has some easily fixable glitches up until I start the loops for the commands. Is it easily fixable, or do I just scrap it and start over? Cuz I don't want to do that.
    Last edited by GigaRoid; 01-31-2012 at 02:44 PM.

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    For non-windows people, simply comment out the #include <windows.h> line and the body of setColor().
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    A couple of points.

    Your main is too big. Split it into functions.
    You don't need to initialize string objects to "". They automatically initialize to an empty string.
    You possibly want to use getline to read user input.

    It would be helpful if you could give a sample run of the program, showing what it does and telling us what you expected it to do.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    Registered User GigaRoid's Avatar
    Join Date
    Aug 2011
    Location
    Everywhere
    Posts
    23
    I was thinking of splitting it up into functions later when I could get it to actually work.

    What it's supposed to welcome you to the game, then ask for your name. It confirms the name and starts the game. You run into a chest and you're supposed to have two options: open or ignore. Ignore would end the game, and open would open the chest and display the items inside of it by using a for loop. If you would ever enter an option that doesn't work, it would give you an error, send you to the beginning of the loop and ask again.
    Then it will give you the option of doing something. Currently I only have programmed drop and take functions. You can enter "drop _____" _____ is one of your items. That item will be erased from your inventory and each item will move down to fill it in. The same thing with take except it's with the boxItems and you get the selected item...

    that's pretty much it.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,914
    Quote Originally Posted by GigaRoid
    I was thinking of splitting it up into functions later when I could get it to actually work.
    It would be easier if you do that earlier: write a function that does one thing, then test it and fix it until it works. Write another function, test and fix. It is easier to test and fix many small functions one at a time than to test and fix one big function that is supposed to do the same thing.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Yeah, I agree with laserlight. There's no reason to leave splitting it up into functions until later. Functions are a thinking tool as well as a programming tool.

    On the other hand, your coutWfe function doesn't make much sense to me. For instance, it eats the first letter of the entered name. pickTwo is kind of useless too. pickFrom, with any number of options, would be more useful.

    So to answer your original question, yes, you should scrap it. Think it over from scratch and think in functions. Consider a high-level structure something like this:
    Code:
    .
                       main
                 _______|________
                /       |        \
             init      game      term
                       loop
                 _______|________
                /       |        \
         display       get        execute
         location      command    command
    Salem and AndrewHunter like this.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  7. #7
    Registered User GigaRoid's Avatar
    Join Date
    Aug 2011
    Location
    Everywhere
    Posts
    23
    Got it, an example of that basic structure would be nice though. From what I understand, it's impossible. But that's just because I understand so little. Would this cover cout waiting for enter each line or something? Because that was the whole point of coutWfe. And I didn't know there was a pickFrom, that's pretty convinient.

    EDIT: Remember, I am a complete C++ noob.
    Last edited by GigaRoid; 02-01-2012 at 01:54 PM.

  8. #8
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Make your own example. I can't understand how you could think it's impossible.

    There is no pickFrom function. You write it yourself.

    coutWfe is pointless.

    Convenient is spelled with an e.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  9. #9
    Registered User GigaRoid's Avatar
    Join Date
    Aug 2011
    Location
    Everywhere
    Posts
    23
    Quote Originally Posted by GigaRoid;
    it's impossible. But that's just because I understand so little.
    I don't know how to have infinite arguments in a function. The tutorials talked about it, but it didn't make a lot of sense to me.

    I wouldn't need it if I could make a program like this, but with a game loop. But I've never worked with game loops ever, that's why I would like an example of how you would make something similar to this so I can atleast understand.
    Convenient is spelled with an e.
    I'll keep that in mind for the next time I don't have time to check my spelling.
    "For every error, there is something wrong with the method, or something wrong the information. If not you just screwed up."

  10. #10
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    I am not sure what book you are using, but take a look at the C++ Tutorials provided by the site. Additionally, game programming is its own beast so you may gain some value from the Game Programming Tutorials offered here.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  11. #11
    Registered User GigaRoid's Avatar
    Join Date
    Aug 2011
    Location
    Everywhere
    Posts
    23
    I've now read everything I need to in my book to make this. I understand the game loop, I just need an example of how to use a game loop in my circumstance, which I am pretty sure it doesn't say many other places. I would just like an example, that's it.
    Last edited by GigaRoid; 02-05-2012 at 05:43 PM.
    "For every error, there is something wrong with the method, or something wrong the information. If not you just screwed up."

  12. #12
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    There are too many variables for me to give you a real example. It depends on all the decisions you must make before you begin to write the program. How are you representing the map? the commands? the player state? the items? the monsters? There are a lot of possibilities and they're all up to you.

    The basic idea of the "game loop" (as we're calling it) is mindlessly simple:

    Code:
    const int CMD_QUIT = 99; // Better would be an enum of all commands.
    
    void gameLoop() {
        int location = 0; // Assuming location is represented by
                          //   an int and 0 is the initial location.
        int cmd = 0;      // Assuming command is represented by an int.
        while (cmd != CMD_QUIT) {
            displayLocation(location);
            cmd = getCommand();
            if (cmd != CMD_QUIT)
                executeCommand(cmd);
        }
    }
    There are more assumptions in the above than noted. E.g., apparently the map and player state are global, or gameLoop is in a class that has access to them. And on and on.

    I don't have time to check my spelling.
    I find that somewhat insulting. Do you expect us to spend time helping you? (And isn't there a bulit-in spell-checker here?) Even your sig has a grammatical error in it. That does not bode well for your success as a programmer. Details matter.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,781
    Quote Originally Posted by oogabooga View Post
    ...(And isn't there a bulit-in spell-checker here?) Even your sig has a grammatical error in it...
    Spell checking is typically built into browsers, not web sites.
    Oh, and if you buy Windows 8, you'll have a system wide spell checker AFAIK.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Jul 2009
    Posts
    18
    I found one of your arrays were going out of bounds, you cant have array[-1] in your code. I wasnt sure what your problem was so I didnt look any further than this.
    Code:
              
      for (int i=subX; i < itemMax; ++i)
                {
    //inventory array is going to -1, this cant happen
                    inventory[i-1]=inventory[i];
                    inventory[i]="";
                }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong with the code ?
    By zap85 in forum Linux Programming
    Replies: 3
    Last Post: 08-08-2008, 12:45 AM
  2. What's wrong with this code?
    By Luciferek in forum C++ Programming
    Replies: 4
    Last Post: 06-21-2008, 12:02 PM
  3. What was wrong with this code??
    By dianazheng in forum C Programming
    Replies: 17
    Last Post: 10-25-2004, 10:36 PM
  4. what's wrong with this code
    By stormbreaker in forum C++ Programming
    Replies: 16
    Last Post: 06-03-2003, 10:29 PM
  5. What is wrong with this code??? Can U help??
    By kickass in forum C Programming
    Replies: 1
    Last Post: 10-31-2002, 02:34 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21