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

  • Context: C/C++ 
  • Thread starter Thread starter FallArk
  • Start date Start date
  • Tags Tags
    Class
Click For Summary
SUMMARY

This discussion focuses on implementing a game using classes in C++. The main components include a Board class that manages the game state, including player and opponent positions, and methods for initializing the board, placing pieces, and displaying the board. Key issues addressed include the need for proper variable access levels (private vs. public) and passing objects by reference to avoid unnecessary copies. The discussion also highlights the importance of using control structures correctly to ensure the game logic functions as intended.

PREREQUISITES
  • Understanding of C++ class and object-oriented programming concepts
  • Familiarity with exception handling in C++
  • Knowledge of basic game logic and control flow
  • Experience with C++ standard input/output operations
NEXT STEPS
  • Learn about C++ class access specifiers (public, private, protected)
  • Explore C++ exception handling techniques in-depth
  • Investigate passing objects by reference in C++
  • Study game development principles in C++ for better design patterns
USEFUL FOR

Game developers, C++ programmers, and anyone interested in implementing object-oriented designs in game applications.

FallArk
Messages
127
Reaction score
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
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.
 
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.
 
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
 
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)
 
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?
 
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.
 

Similar threads

  • · Replies 33 ·
2
Replies
33
Views
7K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 75 ·
3
Replies
75
Views
6K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 21 ·
Replies
21
Views
3K
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K