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

Discussion Overview

The discussion revolves around implementing a game using classes in C++. Participants are exploring how to structure a game board using a class, including the initialization of the board, placing pieces, and handling player movements. The conversation includes technical aspects of class design, function definitions, and the implications of passing objects by reference versus by value.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant inquires about how to create a board using a class instead of a struct, indicating a transition in their approach.
  • Another participant suggests that variables in the class should be private and functions that need to be accessed should be public.
  • Concerns are raised about the implementation of the moveOpponent function, which is said to make multiple moves in a single call, leading to unintended behavior.
  • There is a suggestion to pass the Board object by reference in the movePlayer and moveOpponent functions to avoid unnecessary copies.
  • Participants discuss the need to pass the win variable by reference in the processException function to ensure the main program receives the correct result.

Areas of Agreement / Disagreement

Participants generally agree on the need for proper encapsulation in class design, but there are differing opinions on the implementation details, particularly regarding function behavior and parameter passing. The discussion remains unresolved regarding the correct implementation of the opponent's movement logic.

Contextual Notes

There are unresolved issues regarding the movement logic for both the player and the opponent, as well as the handling of exceptions. The implications of passing objects by reference versus by value are also under consideration, which may affect performance and functionality.

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 3 ·
Replies
3
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 12 ·
Replies
12
Views
5K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 49 ·
2
Replies
49
Views
12K