You are here:

C++/Help turning psuedo code into c++ code

Advertisement


Question
Alright I am trying to write a program that will play Dots and Boxes, the common paper and pencil game. I have wrote a psuedo code algorithm for this program. My problem is that I do not know where to begin with the the "Game" function and was wondering if you could help me out? I know that to print grid, you have to create a set of 2-d arrays, one called rows and the other called columns but could you guide me on how to write to function into c++ code. Thanks very much.

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int preGame();
void Game();
void postGame();

int main(int argc, char *argv[])
{
preGame();
//This function will ask the user to input a number and returns a grid size for that input if the number is legal.
Game();
//This function will print the current grid and score after each turn. It will also obtain and apply the move.
postGame();
//This function will print the finish grid score, final score, and the farewell message.
system("PAUSE");
return EXIT_SUCCESS;
}

int preGame ()
{
  int input;

  while(input < 2 || input > 9)
  {
    cout << "What size grid would you like? (2..9) ";
    cin >> input;
    
    if( input < 2 || input > 9)
    cout << "\nTry again" << endl << endl;
    else
    break;
     
  }//end of while loop
    return input;
}

void Game()
{
int input;

while (game is not finished)
{
Printing the grid
Priniting the score
//Obtaining the move
cout << "\nEnter your next move";
cin >> input;
remove non-alphanumeric characters from move
//Applying the move
Check if the move is llegal
 if(Both dots are one edge apart with that edge is open && is within legal range of grid)
  if ( move =='Q')
    break to postgame phase
  else if(letter is first)
   apply vertical move
  else
   apply horizontal move
}
}

void postGame()
{
Print finished grid
Print final score
//Print farewell message
 if(Human score > Computer score)
 {
  cout << "\nCongratulations!" << endl;
  return EXIT_SUCCESS;
 }
 else if(Human score < Computer score)
 {
  cout << "\nBetter luck next time." << endl;
  return EXIT_SUCCESS;
 }
 else
 {
  cout << "\nI think we need a rematch." << endl;
  return EXIT_SUCCESS;
 }
}

Answer
Unfortunately "Dots and Boxes, the common paper and pencil game" is not one I know of - so it may be more common in your locale than mine (SE UK).

However, assuming Dots and Boxes is like other board games you will require a game grid that maintains the state of the cells in the game. If like many games a cell can be empty or occupied by some piece or another then maybe you should define these some how - e.g. using a enumerated type:

   enum CellState { Empty, Dot, Box };

(the above is a suggestion only as I do not know what valid states for cells are in this game)

You then require a grid array. If the grid were of fixed size this would be easy:

   CellState gameGrid[NumberOfRows][NumberOfColumns];

This would be defined in the Game function local to the Game function on the stack.

However you allow the user to determine the size of the grid. In such cases we would usually have to define the grid dynamically on the free store using new [] - and delete it when done using delete []. However there is a problem in that dynamic arrays can only vary dynamically in _one_ dimension all others must have a size that is constant and known at compile time. There are ways around this but as the maximum size of the grid is not very large (9*9 or 81 cells if I read the code correctly) it seems simpler in this case if you define the grid array to be the largest possible size and only use the section needed for the size the user requested:

   const unsigned int MaxGridDimensionValue(9);

   ...

   CellState gameGrid[MaxGridDimensionValue][MaxGridDimensionValue];

Note that like all local automatic (stack) objects (variables) local automatic array elements are default constructed which for simple built in and enumeration types does nothing so such array elements are _not_ initialised to any specific value - i.e. they contain random junk. Hence you will have to clear the grid array elements to some appropriate value - such as empty, or maybe go through a procedure to set the pieces in their initial cell positions (as in chess and draughts/checkers) and set the other cells to be empty.

You can access individual cells using the row and column index values - remember C and C++ arrays have index values in the range [0, dimension_size - 1], so a 3 by 3 grid would have cell index values [0][0], [0][1], ..., [1][0], [1][1], ..., [2][1],[2][2].

To iterate over all cells in a grid you would use a pair of nested loops:

   for (unsigned int row=0; row<grid_size; ++row )
   {
       for (unsigned int col=0; col<grid_size; ++col )
       {
         // do stuff with grid[row][col]
       }
   }

You can use the enumeration value names in switch case statements:

   switch ( grid[row][col] )
   {
   case Empty:
       cout << ' ';
       break;

   case Dot:
       cout << '.';
       break;

   ...

   default:
       // All cell states should be accounted for so take appropriate error condition action
   };

That should be enough to move you forward if you use your brain to piece together the example fragments I have shown you. Do not be afraid to get things a bit wrong at first. Do not be afraid to have several C++ references available (books, notes, online pages etc.)and open while you are implementing you game.

You should review your function usage and parameters - for example you return a value from pre_game but do _not_ store it in main:

   preGame();

You do not pass this information on to the Game function.

DO NOT rely on global variables to pass such information around - this s very bad design.

Maybe the code should look more like so:

   int grid_size( preGame() );
   //This function will ask the user to input a number and returns a grid size for that input if the number is legal.

   Game( grid_size );

Do not be afraid to split other complex functions into smaller, simpler, easy to understand, implement and _test_ functions. I am thinking of the Game function here - it has the potential to become long, complex and messy.

Hope this moves you forward - have fun writing your game.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.