### Stuck at 4 in a row game, checking who is the winner

(First of all I am sorry for any miss spelled in my writting)
Hello, I have been programming the little mini game 4 in a row, where i have 6 colums and 7 Row Tabel(variable Tabel[6][7]) . There are only two players with their game "Stones" one being 'X' and the other being 'O'. The game stars with player one and then goes on to player two. The console gives out a small recreation of the 4 in a row table, and the player has to decide in which Row from 0-6 he wants to "throw" his Stone. The programm also check that if one Array space has already an 'X' or a 'O' it moves the stone to one higher. But my problems begins here, I am stuck at how to check who is the winner of the game. I don't know how to make the programm check if there are 4 'X' or 'O' in a Row (void CheckWinner(void) ). I have only tried with 'X' but i can't see to get the winner.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120`` ``````//4 in a row using namespace std; #include #include class FourWins { public: struct Player { string name; char Stone[2]={'X','0'}; }Player[2]; public: int K=1; public: int L; public: char Tabel[6][7]={}; public: void PlayerNameInput(void) { for(int x=0; x<2; x++) { cout<<"Please Player"<>Player[x].name; } } public: void TableOutput(void) { for (int i=5; i>=0; i--) { for(int x=0; x<7; x++) { cout<<"|"<>a; while(c<=1) { if(Tabel[b][a]==0) { Tabel[b][a]=Player[L].Stone[L]; c=c+1; cout<
Last edited on
Hello Nickoblack.

- What is the game your trying to make ?
- What are the rules ?

A few tips when asking this website:
1) Write a more descriptive title because
 Stuck at 4 in a row game
doesn't describe the problem you have.
2) Describe the problem in details.
3) Paste only the code that is relevant - all commented code should be discarded if it doesn't have anything to do with your question.

A few tips for structuring a program:
1) Each variable, function, class or struct should have a meaningful name (And in English).
2) Code should be separated into .h and .cpp files.
3) Don't use comments to describe what your code does unless it's and algorithm and even that you will need to explain fully what the algorithm does.
Last edited on
Hello globaltourist,

I have edit the post, hopefully it is more clear that it used to be.
I appreciate your advices that i will keep in mind for future post.
I think i understand what your trying to achieve.
I will recreate it and post my version here, also I'l comment why I did it the way I do.
NOTE: I will give you a few tips when writing games so you wont run into this problem in the future.
checkwinner should only check the most recent move to see if it created a winning move. Computers are fast enough that it does not matter if you check the whole board every time, but this sort of thing is critical for more complex games.
@jonnin Im rewriting it with the MVC pattern and i comment it heavily so he can easily understand it for when he wants to move on to larger projects, I also add tips and resources for him to visit and learn from because most of his practices currently are plain wrong.
@Nickoblack im about to finish my rework for your program i just wanted to point out that you confused rows and cols, your program checks for 4 stones in a col and you called it a row
Firstly I would recommend you the following resources for getting more knowledge of the language:
http://www.cplusplus.com/forum/articles/10627/
https://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm
http://www.learncpp.com/

Secondly I will recommend you to use https://www.hackerrank.com/domains/algorithms/warmup
for exercise.

Now for the code i wrote for you.
Iv'e used the MVC (model-view-controll) pattern to decouple the code as much as possible and I recommend you google it and learn more.
Also visit https://sourcemaking.com/, it is a great resource to learn code architecture from and it has plenty of examples and explanations.

game_view.h:
 ``123456789101112131415161718192021222324252627282930313233`` ``````#ifndef GAME_VIEW_H #define GAME_VIEW_H #include //prefer std::array to raw arrays #include #define ROWS 7 #define COLS 6 //using namespace std; <-- *DONT EVER USE THIS* using std::string; //<--explicitly state what your using instead using std::array; //<--explicitly state what your using instead class GameView final { public: //allways pass std:: objects by const& if you don't intend on changing their content, //standard types such as: int, short, char, long etc.. should be passed by value unless you want to change their values //in which case you can by by & (without const) //go to: http://www.learncpp.com/ and read chapters 7.1 to 7.4a (ideally read all of the guide). //I wont do it here because it might be a bit more advanced but you should mark all functions that dont //modify member variables as const. void printStones(array, ROWS> const& table); void printPlayerTurn(string const& player_name); void printWinner(string const& name); void askPlayerName(int player_num); void printEndMessage(); void printGameBoard(); void printTie(); }; #endif ``````

game_view.cpp:
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129`` ``````#include "game_view.h" #include //for gotoxy function (although you should avoid this library if you want portable code) #include //for std::cout //using namespace std; <-- *DONT EVER USE THIS* using std::cout; //<--explicitly state what your using instead #define TABLE_VIEW_WIDTH 35 #define TABLE_VIEW_HEIGHT 23 #define FIRST_CELL_X 12 #define FIRST_CELL_Y 6 #define WIDTH_PAD 4 #define HEIGHT_PAD 2 #define END_GAME_Y 24 #define END_GAME_X 0 #define STATEBOX_Y 21 #define STATEBOX_X 1 #define TURN_Y 1 #define TURN_X 1 #define BOARD_Y 0 #define BOARD_X 0 namespace details { struct Position { int x; int y; }; struct Dimentions { int height; int width; }; void gotoxy(Position pos) { COORD coord{ static_cast(pos.x), static_cast(pos.y) }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } void loadString(string const& str, Dimentions size, Position pos) { for (int y{}; y < size.height; ++y) { for (int x{}; x < size.width; ++x) { gotoxy({ pos.x + x, pos.y + y }); cout << str[y * size.width + x]; } } } const string game_board { "+---------------------------------+" "| |" "+---------------------------------+" "+---------+---+---+---+---+---+---+" "|ROWS/COLS| 0 | 1 | 2 | 3 | 4 | 5 |" "+---------+---+---+---+---+---+---+" "| 0 | | | | | | |" "+---------+---+---+---+---+---+---+" "| 1 | | | | | | |" "+---------+---+---+---+---+---+---+" "| 2 | | | | | | |" "+---------+---+---+---+---+---+---+" "| 3 | | | | | | |" "+---------+---+---+---+---+---+---+" "| 4 | | | | | | |" "+---------+---+---+---+---+---+---+" "| 5 | | | | | | |" "+---------+---+---+---+---+---+---+" "| 6 | | | | | | |" "+---------+---+---+---+---+---+---+" "+---------------------------------+" "| |" "+---------------------------------+" }; } void GameView::printStones(array, ROWS> const& table) { for (int y{}; y < ROWS; ++y) { for (int x{}; x < COLS; ++x) { details::gotoxy({ x * WIDTH_PAD + FIRST_CELL_X, y * HEIGHT_PAD + FIRST_CELL_Y }); cout << table[y][x]; } } } void GameView::printPlayerTurn(string const& player_name) { details::gotoxy({ TURN_X, TURN_Y }); cout << " "; details::gotoxy({ TURN_X, TURN_Y }); cout << " Player " << player_name << "\'s turn"; } void GameView::printWinner(string const& name) { details::gotoxy({ STATEBOX_X, STATEBOX_Y }); cout << " Player " << name << " won!"; } void GameView::askPlayerName(int player_num) { cout << "Player " << player_num << " please enter your name (18 symbols max): "; } void GameView::printEndMessage() { details::gotoxy({ END_GAME_X, END_GAME_Y }); //use at the end of the game //console will print : "Press any button to continue" by default } void GameView::printGameBoard() { details::loadString(details::game_board, { TABLE_VIEW_HEIGHT, TABLE_VIEW_WIDTH }, {BOARD_X, BOARD_Y}); } void GameView::printTie() { details::gotoxy({ STATEBOX_X, STATEBOX_Y }); cout << " game ended with a tie"; }``````
game_model.h:
 ``123456789101112131415161718192021222324252627282930313233343536`` ``````#ifndef GAME_MODEL_H #define GAME_MODEL_H #include //prefer std::array to raw arrays #include #define ROWS 7 #define COLS 6 #define PLAYERS 2 //using namespace std; <-- *DONT EVER USE THIS* using std::string; //<--explicitly state what your using instead using std::array; //<--explicitly state what your using instead class GameModel final { public: GameModel(); array, ROWS> const& getStoneTable(); std::string const& getCurrentPlayerName(); int addStone(int col, char stone); bool setPlayerName(int player_num); bool hasWon(int row, char stone); bool getCurrentPlayerTurn(); void nextPlayerTurn(); bool checkForTie(); private: bool player_turn_{ false }; array player_; array, ROWS> table_; }; #endif ``````

game_model.cpp:
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586`` ``````#include "game_model.h" #include #define MAX_NAME_LENGTH 18 #define FOUR_IN_A_ROW 4 using std::getline; using std::cin; GameModel::GameModel() : table_ { {{ ' ', ' ', ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ', ' ' }} } { } array, ROWS> const & GameModel::getStoneTable() { return table_; } std::string const & GameModel::getCurrentPlayerName() { return player_[player_turn_]; } int GameModel::addStone(int col, char stone) { for (int row{ ROWS - 1 }; row >= 0; --row) if (table_[row][col] == ' ') { table_[row][col] = stone; return row; } return -1; } bool GameModel::setPlayerName(int player_num) { std::string name; getline(cin, name); if (name.size() > MAX_NAME_LENGTH || name == "") return false; else if (player_[0] == name) return false; player_[player_num] = name; return true; } bool GameModel::hasWon(int row, char stone) { int same_stones{}; for (int col{}; col < COLS; ++col) { if (table_[row][col] == stone) { if (++same_stones == FOUR_IN_A_ROW) return true; } else same_stones = 0; } return false; } bool GameModel::getCurrentPlayerTurn() { return player_turn_; } void GameModel::nextPlayerTurn() { player_turn_ ? player_turn_ = false : player_turn_ = true; } bool GameModel::checkForTie() { for (int row{}; row < ROWS; ++row) for (int col{}; col < COLS; ++col) if (table_[row][col] == ' ') return false; return true; }``````

game_controller.h:
 ``1234567891011121314151617181920212223`` ``````#ifndef GAME_CONTROLLER_H #define GAME_CONTROLLER_H #include "game_model.h" #include "game_view.h" class GameController final { public: GameController(GameModel& model, GameView& view); void execute(); void onLoad(); private: GameModel& model_; GameView& view_; void readPlayerName(int player_num); int getColFromPlayer(); }; #endif ``````

game_controller.cpp:
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162`` ``````#include "game_controller.h" #include #include #include GameController::GameController(GameModel & model, GameView & view) :model_{ model }, view_{ view } { } void GameController::execute() { std::array stones{ 'X', 'O' }; bool gameInProgress{ true }; while (gameInProgress) { view_.printPlayerTurn(model_.getCurrentPlayerName()); int row; do { int col = getColFromPlayer(); row = model_.addStone(col, stones[model_.getCurrentPlayerTurn()]); } while (row == -1); view_.printStones(model_.getStoneTable()); if (model_.hasWon(row, stones[model_.getCurrentPlayerTurn()])) { view_.printWinner(model_.getCurrentPlayerName()); view_.printEndMessage(); gameInProgress = false; } else if (model_.checkForTie()) { view_.printTie(); view_.printEndMessage(); gameInProgress = false; } else model_.nextPlayerTurn(); } } void GameController::onLoad() { int player_num{ 0 }; readPlayerName(player_num++); readPlayerName(player_num); system("cls"); view_.printGameBoard(); } void GameController::readPlayerName(int player_num) { do { view_.askPlayerName(player_num); } while (!model_.setPlayerName(player_num)); } int GameController::getColFromPlayer() { int input; do { input = _getch(); } while (input < '0' || input > '5'); return input - '0'; }``````

source.cpp:
 ``123456789101112131415161718`` ``````#include "game_controller.h" #include "game_model.h" #include "game_view.h" //anyway i wouldn't recomment you to use the native windows.h as a beginner, i will recomment you //ncurses if you use linux and pdcurses if you use windows, and that is only if you want to make //console stuff otherwise learn something like openCV for graphics int main() { GameModel model; //game data GameView view; //the way the data is displayed GameController controller{ model, view }; //acts like an adaptor/glue between view and model controller.onLoad(); //called once controller.execute();//contains game loop return 0; }``````
Topic archived. No new replies allowed.