Page 2 of 3 FirstFirst 123 LastLast
Results 11 to 20 of 23

Thread: c++

  1. #11
    Join Date
    Jan 2012
    Beans
    161

    Re: need some c++ help

    Ok, well im doing this based off the book " Jumping into c++". It seems like even after following the book chapter by chapter that the problems at the end are more advanced than what is taught preceeding them. Is there a better way to learn c/c++?

  2. #12
    Join Date
    Jan 2012
    Beans
    161

    Re: need some c++ help

    It stinks because i know nothing about what you guys speak of. indent? debug? AI test functions?

  3. #13
    Join Date
    May 2008
    Location
    UK
    Beans
    1,451
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: need some c++ help

    Quote Originally Posted by wingnut2626 View Post
    It stinks because i know nothing about what you guys speak of. indent? debug? AI test functions?
    Indent - what is being refered to here is a consistent use of spaces at the start of your code lines so you can see easily where the code in a loop or an if actually sits. Your eys find spaces far easier than searching for { and }.

    Debug - This means placing couts (or printfs) in your code at strategic places so you can see what the value of a particular variable is, or even just that the code actually executes the code block you think it does.

    AI - Artifical Intelligence. Here it means code that actually tries to play the game against the human player. The easiest form of AI to code is one that makes random moves.

    test functions - the best way to design and develop is to know what function needs to do before you write it, and then develop a shot program that calls your function with a vaiety of inputs so you can check that it works. Doing this means you can then use that function with confidence in a bigger program becuase you know it works.
    Tony - Happy to try to help.
    Unless otherwise stated - all code posted by me is untested. Remember to Mark the Thread as Solved.
    Ubuntu user number # 24044 Projects : TimeWarp - on the fly Backups

  4. #14
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Re: c++

    Don't worry if this seems difficult. Tictactoe is not a trivial program if it's done well. Maybe you should put this to one side for now and revisit it when you have a few more manageable programs under your belt?

    I think you also need to consider whether you want to continue with C++ or start with C, Python or Java. All are easier IMO. I'm not a C++ programmer by any means but I learned the basics of C++ from:

    http://www.cplusplus.com/doc/tutorial/

    But I already knew C and Java and was learning Python, so all that probably helped.

    Indent is just a program that fixes indentation on source code based on certain standards. You need to install it first, then run it on your source file (which it overwrites after making a backup copy):

    Code:
    $ sudo apt-get install indent
    $ indent -linux myprogram.cpp
    The 'linux' option is just one of several styles that it can apply. The style you use doesn't matter so much as that you apply it consistently. Indentation is a large part of understanding code.

    When I was talking about debug statements, I didn't mean anything much more complex than:

    Code:
    cout << "DEBUG: " << myvariable << endl;

  5. #15
    Join Date
    Oct 2007
    Beans
    1,914
    Distro
    Lubuntu 12.10 Quantal Quetzal

    Re: need some c++ help

    Quote Originally Posted by wingnut2626 View Post
    It stinks because i know nothing about what you guys speak of. indent? debug? AI test functions?
    You should probably forget about what TheFu wrote - that is more advanced stuff. He/she is right in what he/she writes, but it's just more advanced stuff.

    You are on the right track.

    It is part of every programming language learning process to learn how to debug things, i.e., find problem with your code. For example, r-senior gave you some hints.

    Hint a) is about indentation - the amount of leading whitespace in the lines of your code. This leading whitespace helps you to visualize what your code is actually doing. Here is an example from your code:

    Code:
    void playgame()
    {
        do{
            
        taketurn(player1);
        checkwin();
        taketurn(player2);
        checkwin();
    } while (checkwin() != 1);
    }
    Better indentation leads to this:
    Code:
    void playgame()
    {
        do {       
            taketurn(player1);
            checkwin();
            taketurn(player2);
            checkwin();
        } while (checkwin() != 1);
    }
    This increases the readability of your code and thus helps you find bugs.

    Then r-senior suggested to add some debug output to your functions taketurn() and playgame().

    Debug output means that your program will print the contents of the variables that you use in the program solely for the purpose of letting you, the programmer, take a peak of what the program is actually doing. This allows you to compare that against the idea of your program in your head and trace where things go wrong.

  6. #16
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,288
    Distro
    Kubuntu

    Re: c++

    It should also be mentioned that there is a debugger available under Linux. It is called 'gdb'. It's has a CLI, which is not very attractive, but is functional.

    For a sexier debugger, there's 'ddd'. It basically is a front-end GUI to 'gdb'.

    To debug C++ (or C) code, make sure that the -g option is passed to the compiler. Then to debug code, use either one of the following commands:
    Code:
    gdb ./myprog
    
    # or
    
    ddd ./myprog &

  7. #17
    Join Date
    Mar 2010
    Location
    Squidbilly-Land
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: need some c++ help

    Quote Originally Posted by wingnut2626 View Post
    Ok, well im doing this based off the book " Jumping into c++". It seems like even after following the book chapter by chapter that the problems at the end are more advanced than what is taught preceeding them. Is there a better way to learn c/c++?
    I tried to learn from a book, but could never make the leap to understanding OO. I had to go to "church" to get the "OO religion." My church was a local community college - the class was paid by the company.

    I probably have the assignments around somewhere.

    Assignment 1:
    Write a C program that clears the screen and displays a
    menu. Give the user the options of multiplying two floats,
    dividing two floats, and quiting [sic] the program. Write a
    function to multiply two floats and a function to divide
    two floats. The main function should contain a switch
    that calls the appropiate [sic] function or allows the user to
    quit using the exit function - exit(0) . The results
    of the multiplication or division should be displayed to
    the screen in a highly readable form.
    This can work for someone trying to learn C++ too.

    My first post provided hints that will save you hundreds of hours. I'm learning Ruby now and in that class, they teach test driven development, Rails, and git along with Ruby. The language you are learning is only 30% of programming skills.

    If you are brand new to programming - this is your first language, might I suggest Python instead? http://learnpythonthehardway.org/book/ MIT has video lectures online for CompSci 101 based on Python too.

    If you are set on learning C++, follow the selected book carefully and be certain you understand 90% of the concepts in each chapter. Work the exercises - type everything in, do not download the starter code. TYPE IT IN!

    Keep working, it wasn't easy for anyone to learn. I started with BASIC on a TRS80, then Fortran with compile times that took 45 minutes and another 30 to link.
    Last edited by TheFu; February 1st, 2013 at 02:26 PM. Reason: made last sentence understandable.

  8. #18
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Re: c++

    OK, I had a play with this tonight. This is probably how I would start this game. My C++ isn't great so don't rely too much on that. The idea would be to get a Board class nailed down and build around that. So there's the beginnings of a test case for the Board class, methods to check for game over etc. See if that gets you heading in the right direction ...

    board.h
    Code:
    const int ROWS = 3;
    const int COLS = 3;
    
    typedef enum {EMPTY, NOUGHT, CROSS} token_t;
    
    class Board {
        token_t grid[ROWS][COLS];
    public:
        Board();
        void add_token(token_t, int, int);
        bool is_free(int, int);
        bool is_full();
        bool is_game_over();
        void print();
        token_t winning_line();
    };
    board.cpp
    Code:
    #include <iostream>
    #include <cassert>
    
    #include "board.h"
    
    // Forward declarations
    static char display_for(token_t token);
        
    /**
     * Constructor for board. Sets all rows and columns to the empty token.
     */
    Board::Board()
    {
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                grid[row][col] = EMPTY;
            }
        } 
    }
    
    /**
     * Print the current state of the board.
     */
    void Board::print()
    {
        std::cout << " +===+===+===+ " << std::endl;
        for (int row = 0; row < ROWS; row++) {
            std::cout << " | ";
            for (int col = 0; col < COLS; col++) {
                std::cout << display_for(grid[row][col]) << " | ";
            }
            std::cout << std::endl << " +===+===+===+ " << std::endl;
        }    
    }
    
    /**
     * Add a token to the board at a given square.
     * @param token the token to add (NOUGHT or CROSS)
     * @param row the row to add it
     * @param col the column to add it
     */
    void Board::add_token(token_t token, int row, int col)
    {
        assert(is_free(row, col));
        grid[row][col] = token;
    }
    
    /**
     * Check if the board is full of tokens. If there is no winning line
     * this will mean a drawn game.
     * @returns true if there are no empty squares, false otherwise
     */
    bool Board::is_full()
    {
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                if (grid[row][col] == EMPTY) {
                    return false;
                }
            }
        }
        return true;
    }
    
    /**
     * Check if a square is free, i.e. doesn't have NOUGHT or CROSS.
     * @returns true if the square is free, false otherwise
     */
    bool Board::is_free(int row, int col)
    {
        return grid[row][col] == EMPTY;
    }
    
    /**
     * Check if the game is over. Either there is a winner, or the board is full.
     * @returns true if the game is over, false otherwise
     */
    bool Board::is_game_over()
    {
        return is_full() || winning_line() != EMPTY;
    }
    
    /**
     * Check for a winning line on the board. If there is no winning line
     * returns the empty token, otherwise the token that has the line.
     * @returns EMPTY if no winning line, otherwise the winning token
     */
    token_t Board::winning_line()
    {
        /**************************************************************/
        /* NB. This method is incomplete, it does not check diagonals */
        /**************************************************************/
    
        // Check for winning rows
        for (int row = 0; row < ROWS; row++) {
            if (grid[row][0] == grid[row][1] && grid[row][1] == grid[row][2]) {
                if (grid[row][0] != EMPTY) {
                    return grid[row][0];
                }
            }
        }
        
        // Check for winning columns
        for (int col = 0; col < COLS; col++) {
            if (grid[0][col] == grid[1][col] && grid[1][col] == grid[2][col]) {
                if (grid[0][col] != EMPTY) {
                    return grid[0][col];
                }
            }
        }
    
        return EMPTY;
    }
    
    // HELPER FUNCTIONS
    
    /**
     * Return the display character for a given token, e.g. 'X', 'O'
     * @param token the token that needs to be displayed
     * @returns a single character for display on the board
     */
    static char display_for(token_t token)
    {
        switch (token) {
            case EMPTY: return ' ';
            case NOUGHT: return 'O';
            case CROSS: return 'X';
        }
        return ' ';
    }
    testboard.cpp
    Code:
    #include <cassert>
    #include <iostream>
    
    #include "board.h"
    
    using namespace std;
    
    void check_row(Board *board)
    {
        board->add_token(NOUGHT, 1, 0);
        board->add_token(NOUGHT, 1, 1);
        assert(!board->is_game_over());
        assert(board->winning_line() == EMPTY);
    
        board->add_token(NOUGHT, 1, 2);
        assert(board->is_game_over());
        assert(board->winning_line() == NOUGHT);
        board->print();
        cout << "check_row passed" << endl;
    }
    
    void check_col(Board *board)
    {
        board->add_token(CROSS, 0, 1);
        board->add_token(CROSS, 1, 1);
        assert(!board->is_game_over());
        assert(board->winning_line() == EMPTY);
    
        board->add_token(CROSS, 2, 1);
        assert(board->is_game_over());
        assert(board->winning_line() == CROSS);
        board->print();
        cout << "check_col passed" << endl;
    }
    
    int main()
    {
        Board *board = new Board();
        check_row(board);
        delete board;
            
        board = new Board();
        check_col(board);
        delete board;
    
        return 0;
    }
    Makefile
    Code:
    CXX=g++
    CPPFLAGS=-Wall -Wextra -pedantic
    CC=g++
    LDFLAGS=
    
    OBJS = board.o testboard.o
    
    all: testboard
    
    testboard: ${OBJS}
    
    board.o: board.cpp board.h
    testboard.o: testboard.cpp board.h
    
    clean:
    	rm -fv *.o testboard
    
    rebuild: clean all
    And a sample compile and run ...

    Code:
    $ make
    g++  -Wall -Wextra -pedantic  -c -o testboard.o testboard.cpp
    g++  -Wall -Wextra -pedantic  -c -o board.o board.cpp
    g++   testboard.o board.o   -o testboard
    $ ./testboard
     +===+===+===+ 
     |   |   |   | 
     +===+===+===+ 
     | O | O | O | 
     +===+===+===+ 
     |   |   |   | 
     +===+===+===+ 
    check_row passed
     +===+===+===+ 
     |   | X |   | 
     +===+===+===+ 
     |   | X |   | 
     +===+===+===+ 
     |   | X |   | 
     +===+===+===+ 
    check_col passed

  9. #19
    Join Date
    Mar 2010
    Location
    Squidbilly-Land
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: c++

    Golf clap for the Board class. Very nice C++. OTOH, doing someone's homework, not good.

    The Makefile CCOPTS should probably get a -ggdb too, correct? Oops, sorry, that should be CPPFLAGS with that option. It enabled debugging symbols to be added to the objs. For the "clean:" target in the Makefile - the following line **must** start with a tab character. That is true for all targets, so if a generic .c.o: target was used in the file, then the following line that tells the compiler how to build each .o would need to begin with a tab too.

    I love Makefiles. They are simple, smart, and can perform extremely complex builds while only building things that have been touched, nothing more. I've been reusing the same basic Makefile since 1993. It is self-modifying to automatically find and append dependencies for all code in the project.

    Nice post on the Board class. It is better than I would have done myself in the same time period. I might have gotten bogged down using an interactive session to enter moves and/or allowing a control file to be play a complete game - think of it as a test harness.

    I must admit that my "Chicken" class - you've all seen where a chicken plays tic-tac-toe, right - would have sucked and used brute force to find the shortest moves to winning based on the count of used squares. Lots-o-options.

    Be sure to check in the code! :O
    Last edited by TheFu; January 31st, 2013 at 07:41 PM.

  10. #20
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Re: c++

    Quote Originally Posted by TheFu View Post
    OTOH, doing someone's homework, not good.
    I agree, but if it was a homework assignment and the OP wanted an easy way out, there are dozens of complete solutions floating around on various C++ forums.

    Mostly procedural too. What do they teach in C++ programming classes?

Page 2 of 3 FirstFirst 123 LastLast

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •