How to Implement a Game Using Class in C++?

  • C/C++
  • Thread starter FallArk
  • Start date
  • Tags
    Class
In summary, the program creates a game board with a specified number of rows and columns, initializes it, and places pieces for the player and opponent. The game continues until the player either falls off the board or is hit by the opponent. The player and opponent can move in four directions (N/S/E/W) and the opponent will continue to move randomly until it reaches the player's position. The game ends when the player either wins or loses, and the board is shown after each move.
  • #1
FallArk
127
0
Main is posted below and cannot be modified. Still need to fill out the functions needed, only this time I need to use class.
Code:
int main() {
    int uRow = 0, uCol = 0;
    int oRow = NUMROWS - 1, oCol = NUMCOLS - 1;
    bool win = true;
    int move = 0;
    Board board;
    board.initialize();
    board.placePiece(uRow, uCol, 'U', move);
    board.placePiece(oRow, oCol, 'X', move);
    board.showBoard(move);

while (true) {
    move++;
    try {
    movePlayer(board, uRow, uCol, move);
    moveOpponent(board, oRow, oCol, move);
    board.showBoard(move);
    }
    catch (runtime_error &excpt) {
        processException(excpt, win);
        break;
    }
}

board.showBoard(move);
if (win)
    cout << "*** YOU WIN! ***" << endl;
else
    cout << "*** YOU LOSE! ***" << endl;

string tmp; getline(cin, tmp); // optional
}

What I have done(still working on it, will update as I go on):
Code:
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;

const int NUMROWS = 7;
const int NUMCOLS = 12;
const int TAILLENGTH = 3;

class Board {
public:
    struct _cell {
        int moveNumber;
        char marker;
    };
    _cell board[NUMROWS][NUMCOLS];
    void initialize(){
        for (int r = 0; r < NUMROWS; r++) {
            for (int c = 0; c < NUMCOLS; c++) {
                board[r][c].marker = '_';
                board[r][c].moveNumber = 0;
		}
	}
    }

    void placePiece(int currRow, int currCol, char playerPos, int move){
        board[currRow][currCol].marker = playerPos;
        board[currRow][currCol].moveNumber = move;
    }

    void showBoard(int move){
        for (int r = 0; r < NUMROWS; r++) {
            for (int c = 0; c < NUMCOLS; c++) {
                if ((board[r][c].marker != '_') && (move - board[r][c].moveNumber > TAILLENGTH))
                    board[r][c].marker = '_';
                cout << board[r][c].marker << " ";
		}
		cout << endl;
	}
    }

    void BoardPosUser(int currRow, int currCol, int move) {
        if ((currRow < 0) || (currRow > NUMROWS) || (currCol < 0) || (currCol > NUMCOLS)) {
            throw runtime_error("YOU FELL OFF THE BOARD!");
	}
        if (board[currRow][currCol].marker != '_') {
            throw runtime_error("BANG! You're dead!");
	}
    }

    void BoardPosOppo(int &oRow, int &oCol, int move){
        if ((oRow > 0) && (board[oRow - 1][oCol].marker == '_')) {
            oRow--;
            placePiece(oRow, oCol, 'X', move);
	}
        if ((oRow < NUMROWS-1) && (board[oRow + 1][oCol].marker == '_')) {
            oRow++;
            placePiece(oRow, oCol, 'X', move);
	}
        if ((oCol > 0) && (board[oRow][oCol-1].marker == '_')) {
            oCol--;
            placePiece(oRow, oCol, 'X', move);
	}
        if ((oCol < NUMCOLS-1) && (board[oRow][oCol+1].marker == '_')) {
            oCol++;
            placePiece(oRow, oCol, 'X', move);
	}
    }
};void movePlayer(Board board, int &currRow, int &currCol, int move) {
	board.placePiece(currRow, currCol, 'u', move);
	cout << "Enter direction (N/S/E/W): ";
	char direction;
	cin >> direction;

	if (direction == 'N')
		currRow--;
	if (direction == 'S')
		currRow++;
	if (direction == 'W')
		currCol--;
	if (direction == 'E')
		currCol++;

	board.BoardPosUser(currRow, currCol, move);

	board.placePiece(currRow, currCol, 'U', move);
}

void moveOpponent(Board board, int &oRow, int &oCol, int move) {
	board.placePiece(oRow, oCol, 'x', move);

    board.BoardPosOppo(oRow, oCol, move);

	throw runtime_error("OPPONENT LOSES");
}

void processException(runtime_error excpt, bool win){
    win = (excpt.what() == string("OPPONENT LOSES"));
}
There are a few things I don't really get, in the previous assignment I used struct to create the board, but this time how would I create a board using class?

Update:
A few more questions:
1. Do I need a private: in my class?
2. Which variable should be public? I'm thinking marker and moveNumber
3. Since I need to create a board elsewhere, how should I let the other functions use it without making it a parameter?
 
Last edited:
Technology news on Phys.org
  • #2
Updated code:
Code:
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;

const int NUMROWS = 7;
const int NUMCOLS = 12;
const int TAILLENGTH = 3;

class Board {
public:
    struct _cell {
        int moveNumber;
        char marker;
    };
    _cell board[NUMROWS][NUMCOLS];
    void initialize(){
        for (int r = 0; r < NUMROWS; r++) {
            for (int c = 0; c < NUMCOLS; c++) {
                board[r][c].marker = '_';
                board[r][c].moveNumber = 0;
		}
	}
    }

    void placePiece(int currRow, int currCol, char playerPos, int move){
        board[currRow][currCol].marker = playerPos;
        board[currRow][currCol].moveNumber = move;
    }

    void showBoard(int move){
        for (int r = 0; r < NUMROWS; r++) {
            for (int c = 0; c < NUMCOLS; c++) {
                if ((board[r][c].marker != '_') && (move - board[r][c].moveNumber > TAILLENGTH))
                    board[r][c].marker = '_';
                cout << board[r][c].marker << " ";
		}
		cout << endl;
	}
    }

    bool BoardPos(int Row, int Col){
        if (board[Row][Col].marker == '_') {
            return true;
        }
        else {
            return false;
        }
    }
};void movePlayer(Board board, int &currRow, int &currCol, int move) {
	board.placePiece(currRow, currCol, 'u', move);
	cout << "Enter direction (N/S/E/W): ";
	char direction;
	cin >> direction;

	if (direction == 'N')
		currRow--;
	if (direction == 'S')
		currRow++;
	if (direction == 'W')
		currCol--;
	if (direction == 'E')
		currCol++;

	if ((currRow < 0) || (currRow > NUMROWS) || (currCol < 0) || (currCol > NUMCOLS)) {
            throw runtime_error("YOU FELL OFF THE BOARD!");
	}
    if (board.BoardPos(currRow, currCol)) {
            throw runtime_error("BANG! You're dead!");
	}

	board.placePiece(currRow, currCol, 'U', move);
}

void moveOpponent(Board board, int &oRow, int &oCol, int move) {
	board.placePiece(oRow, oCol, 'x', move);

    if ((oRow > 0) && (board.BoardPos(oRow - 1,oCol))) {
            oRow--;
            board.placePiece(oRow, oCol, 'X', move);
	}
    if ((oRow < NUMROWS - 1) && (board.BoardPos(oRow + 1, oCol))) {
            oRow++;
            board.placePiece(oRow, oCol, 'X', move);
	}
    if ((oCol > 0) && (board.BoardPos(oRow, oCol - 1))) {
            oCol--;
            board.placePiece(oRow, oCol, 'X', move);
	}
    if ((oCol < NUMCOLS - 1) && (board.BoardPos(oRow, oCol + 1))) {
            oCol++;
            board.placePiece(oRow, oCol, 'X', move);
	}

	throw runtime_error("OPPONENT LOSES");
}

void processException(runtime_error excpt, bool win){
    win = (excpt.what() == string("OPPONENT LOSES"));
}

The board is now displaying normally and also the marker for player and opponent.
But they are not moving, and whatever the input is, the program just returns you win.
 
  • #3
Hey FallArk! ;)

Variables should be private, functions you need to call should be public.

Your moveOpponent() isn't quite correct yet.
As it is now, a single call actually typically makes 4 moves and then always throws the exception that the opponent has lost. (Worried)

Oh, and we should pass Board to movePlayer() and moveOpponent() by reference (that is, use &).
Otherwise a copy of the entire board is made and discarded with every move.

Similarly, we should pass win by reference (&) as well to processException().
Otherwise a copy of win is made when the function is called, which is discarded when the function returns.
So the main program won't get the result it needs.
 
  • #4
I like Serena said:
Hey FallArk! ;)

Variables should be private, functions you need to call should be public.

Your moveOpponent() isn't quite correct yet.
As it is now, a single call actually typically makes 4 moves and then always throws the exception that the opponent has lost. (Worried)

Oh, and we should pass Board to movePlayer() and moveOpponent() by reference (that is, use &).
Otherwise a copy of the entire board is made and discarded with every move.

Similarly, we should pass win by reference (&) as well to processException().
Otherwise a copy of win is made when the function is called, which is discarded when the function returns.
So the main program won't get the result it needs.

Ah, I see about the variable part. Hmm, but the moveOpponent part is suppose to work since that is one of the correct solution before adding class
 
  • #5
FallArk said:
Ah, I see about the variable part. Hmm, but the moveOpponent part is suppose to work since that is one of the correct solution before adding class

Well... I don't think it worked before - at least not to actually play a game of snakes... (Thinking)
 
  • #6
I like Serena said:
Well... I don't think it worked before - at least not to actually play a game of snakes... (Thinking)

How would I make it work then?:confused:
make the other three if to else if?
 
  • #7
FallArk said:
How would I make it work then?:confused:
make the other three if to else if?

Yup.
And finish with an else, so the exception is only thrown if none of the 4 if's is satisfied.
 

FAQ: How to Implement a Game Using Class in C++?

How do I declare a class in C++?

To declare a class in C++, use the class keyword followed by the name of the class and a set of curly braces. For example: class MyClass { // class body }

How do I define member functions in a class?

To define member functions in a class, use the scope resolution operator (::) after the class name and before the function name. For example: void MyClass::myFunction() { // function body }

How do I access class members?

To access class members, use the dot operator (.) after an object of the class. For example: MyClass myObject; myObject.myMember;

Can I have multiple constructors in a class?

Yes, you can have multiple constructors in a class. This is known as constructor overloading. Each constructor should have a unique set of parameters.

How do I create an object of a class in C++?

To create an object of a class in C++, use the new keyword followed by the class name and a set of parentheses. For example: MyClass* myObject = new MyClass();

Similar threads

Replies
22
Views
4K
Replies
5
Views
2K
Replies
1
Views
1K
Replies
75
Views
5K
Replies
2
Views
2K
Replies
2
Views
3K
Back
Top