My first game

Started by
25 comments, last by TheNobleOne 19 years, 6 months ago
Well I made my first game with C++. I am so happy it works and there are no bugs that I can find. My game is a text tic tac toe game. kinda simple but you have to start somewhere. What I am looking for from you guys is maybe some suggestions that can improve the readability of my code. Also maybe a few alternative ways to the way I did things to lower the amount of code written. Here is my main.cpp file

#include <iostream>
#include <stdlib.h>

using namespace std;

// Prototypes
void DrawCurrentBoardState(char n[]);
void StartGame(char n[]);

int main(void)
{
    // Declarations
    char boardData[9];
    for(int i = 0; i <= 9; i++) // initialize boardData elements
    {
        boardData = ' ';
    }    
    StartGame(boardData);       // start the game     
    system("PAUSE");            // pause at end of game to keep window open
    return 0;
}

void DrawCurrentBoardState(char n[])
{
    for(int i = 0; i <= 9; i++)  // dispaly board data
    {
        if(i%3 != 0)
        {
            cout << n << "|";
        }
        else
        {
            cout << n << "\n";
        }
    }
    cout << "\n";
}

void StartGame(char n[])
{
    bool running = true;
    int possition;
    DrawCurrentBoardState(n);  // display the most current boards data
    while(running)
    {
        cout << "Player X which possition would you like to take 1 - 9" << "\n";
        cin >> possition;
        n[possition] = 'X';
        DrawCurrentBoardState(n);
        
        // check for win
        if(n[1] == 'X' && n[2] == 'X' && n[3] == 'X')
        {
            cout << "Player " << n[1] << " has won the game." << "\n";
            running = false;
        }
        else if(n[4] == 'X' && n[5] == 'X' && n[6] == 'X')
        {
            cout << "Player " << n[4] << " has won the game." << "\n";
            running = false;
        }
        else if(n[7] == 'X' && n[8] == 'X' && n[9] == 'X')
        {
            cout << "Player " << n[7] << " has won the game." << "\n";
            running = false;
        }
        else if(n[1] == 'X' && n[4] == 'X' && n[7] == 'X')
        {
            cout << "Player " << n[1] << " has won the game." << "\n";
            running = false;
        }
        else if(n[2] == 'X' && n[5] == 'X' && n[8] == 'X')
        {
            cout << "Player " << n[2] << " has won the game." << "\n";
            running = false;
        }
        else if(n[3] == 'X' && n[6] == 'X' && n[9] == 'X')
        {
            cout << "Player " << n[3] << " has won the game." << "\n";
            running = false;
        }
        else if(n[1] == 'X' && n[5] == 'X' && n[9] == 'X')
        {
            cout << "Player " << n[1] << " has won the game." << "\n";
            running = false;
        }
        else if(n[3] == 'X' && n[5] == 'X' && n[7] == 'X')
        {
            cout << "Player " << n[3] << " has won the game." << "\n";
            running = false;
        }
        
        cout << "Player O which possition would you like to take 1 - 9" << "\n";
        cin >> possition;
        n[possition] = 'O';
        DrawCurrentBoardState(n);
        
        // check for win
        if(n[1] == 'O' && n[2] == 'O' && n[3] == 'O')
        {
            cout << "Player " << n[1] << " has won the game." << "\n";
            running = false;
        }
        else if(n[4] == 'O' && n[5] == 'O' && n[6] == 'O')
        {
            cout << "Player " << n[4] << " has won the game." << "\n";
            running = false;
        }
        else if(n[7] == 'O' && n[8] == 'O' && n[9] == 'O')
        {
            cout << "Player " << n[7] << " has won the game." << "\n";
            running = false;
        }
        else if(n[1] == 'O' && n[4] == 'O' && n[7] == 'O')
        {
            cout << "Player " << n[1] << " has won the game." << "\n";
            running = false;
        }
        else if(n[2] == 'O' && n[5] == 'O' && n[8] == 'O')
        {
            cout << "Player " << n[2] << " has won the game." << "\n";
            running = false;
        }
        else if(n[3] == 'O' && n[6] == 'O' && n[9] == 'O')
        {
            cout << "Player " << n[3] << " has won the game." << "\n";
            running = false;
        }
        else if(n[1] == 'O' && n[5] == 'O' && n[9] == 'O')
        {
            cout << "Player " << n[1] << " has won the game." << "\n";
            running = false;
        }
        else if(n[3] == 'O' && n[5] == 'O' && n[7] == 'O')
        {
            cout << "Player " << n[3] << " has won the game." << "\n";
            running = false;
        }                              
    }
}            

My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
Advertisement
looks pretty good. only thing I'd suggest is using a few more blank lines between sub-sections of code. something like:

    bool running = true;    int possition;    DrawCurrentBoardState(n);  // display the most current boards data    while(running)    {    ...


instead of:

    bool running = true;    int possition;    DrawCurrentBoardState(n);  // display the most current boards data    while(running)    {    ...


It just puts a bit of seperation between logically disconnected areas of the code (in this case, seperating variable declaration, drawing, and input). Only other minor thing is that's general policy to initialize your vars (int position = 0), else you get garbage values ;)

Looks good, though, almost identical to my coding conventions ;)
"Game Programming" in an of itself does not exist. We learn to program and then use that knowledge to make games.
Quote:Original post by TheNobleOne
Well I made my first game with C++. I am so happy it works and there are no bugs that I can find.
My game is a text tic tac toe game. kinda simple but you have to start somewhere.


Welcome to the Club.Congrats on making thus far and taking you place on the exclusive[smile] succesful game maker's club.[grin]

Your coding style is close to perfectly crystal clear, but remmeber to put in spaces in places like Instruo said.

  void DrawCurrentBoardState(char n[]);  void StartGame(char n[]);


it's better to declare them like this (standard style)
  void DrawCurrentBoardState(char *n);  void StartGame(char *n);


Also seperate your declarations in the funtions from the working code with about say 2 lines.You coding style is fine otherwise.


NEXT STEP
Move on to pixel based graphics, and Mode13h is the simplest and best to start on. Search on google, the best search engine on the planet.

Also read this,Thoughts on a Project for a begginner, there are some links to Mode13h tuts and other resources for begginers.
______________________________________________________________________________________________________
[AirBash.com]
I have to agree, your code is clean and very readable.
When you start to develop larger programs you may need to print out the source code, or if you need to submit it ( in school or to an empoyeer ). A little tip is to figure out what is the maximum characters you can have on a line and do not exceed that. You can break up lines of code into multiple lines. Ex.
cout << "Player X which possition would you like to take 1 - 9"      << "\n";

or its common to have more than one parameter for a function so I tend to use this convention:
void intthisIsMyFunction( int param1,                  int param2,                  char param3 ){...}


Good code though...
-=Carnage=-Let the carnage begin...
Your code is nice and readable :)

I've reworked a little bit of your code.. You may look at it but it will spoil the fun of doing it yourself.

First a little hint :) The 'chech for win' parts are really similair to eachother. Try extracting them and create a seperate function for it.

You also need to check if a place has already been filled(so if you prece 4 twice the second one should be ignored).

Below is some code that splits your code into a CheckForWin and PlayerHasWon function :)

Good luck with programming!
#include <iostream>#include <stdlib.h>using namespace std;// Prototypesvoid DrawCurrentBoardState(char n[]);void StartGame(char n[]);bool CheckForWin(char Symbol, char n[]);void PlayerHasWon(char Symbol); bool running = true;int main(void){    // Declarations    char boardData[9];    for(int i = 0; i <= 9; i++) // initialize boardData elements    {        boardData = ' ';    }        StartGame(boardData);       // start the game         system("PAUSE");            // pause at end of game to keep window open    return 0;}void DrawCurrentBoardState(char n[]){    for(int i = 0; i <= 9; i++)  // dispaly board data    {        if(i%3 != 0)        {            cout << n << "|";        }        else        {            cout << n << "\n";        }    }    cout << "\n";}void StartGame(char n[]){       int possition;    DrawCurrentBoardState(n);  // display the most current boards data    while(running)    {        cout << "Player X which possition would you like to take 1 - 9" << "\n";        cin >> possition;        n[possition] = 'X';        DrawCurrentBoardState(n);        	CheckForWin('X',n);                cout << "Player O which possition would you like to  take 1 - 9" << "\n";        cin >> possition;        n[possition] = 'O';	        DrawCurrentBoardState(n);	CheckForWin('O',n);            }}            bool CheckForWin(char Symbol, char n[]){		for( int x = 1; x <= 3; x++)	{		if(n[x] == Symbol && n[x + 1] == Symbol && n[x + 2] == Symbol)			PlayerHasWon(Symbol);	}	for( int x = 1; x <= 3; x++)	{		if(n[x] == Symbol && n[x + 3] == Symbol && n[x + 6] == Symbol)			PlayerHasWon(Symbol);	}		if(n[1] == Symbol && n[5] == Symbol && n[9] == Symbol)        {		PlayerHasWon(Symbol);        }    	if(n[3] == Symbol && n[5] == Symbol && n[7] == Symbol)        {		PlayerHasWon(Symbol);        }                    	return true;}void PlayerHasWon(char Symbol){	cout << "Player" << Symbol << " has won the game." << "\n";	running = false;	return;}
I disagree, your code has some bad errors.

Firstly and most obviously, your array accesses are incorrect.

char board[9];

The above statement declares a 9 element array, the first element is board[0], the last element is board[8], not board[9].

This means your loops are incorrect, and your function which checks for three in a row is also incorrect. You are overwriting the array bounds, and corrupting the stack.

Change your loops from i <= 9 to i < 9.

Other things to note are the i % 3, a comment there might be helpful, not totally obvious what is happening there to a lot of people.

the stdlib.h header file is also deprecated in C++, it has been replaced with the cstdlib header. using namespace std; is generally not good practice in larger projects, something to be aware of.

system("PAUSE"); is not a portable command.

Other than that.. well done :)
Hi! Fun game! Just the kind of game I like -- one where I can win.

In addition to the others' comments, re. spacing etc.:

1. Pedantic note: possition -> position (one 's') :)
2. Consider a 'CheckForWinner function that returns a. no winner, or the winner, 'X' or 'O'. Based on the result of this function you can then cout Winner is 'X'/'O' once rather than write it repeatedly as you've done it.

Have fun!

jbc.
Hi!
Even when your code is clear, make an habit of adding comments. Comment each function describing what it does, the parameters and the expected output. Try to make simple comments in your loops. That way, when you go back and read to your code 3 years from now, you will remember it kindly.

Luck!
Guimo
Quote:Original post by elementary
I disagree, your code has some bad errors.

Firstly and most obviously, your array accesses are incorrect.

char board[9];

Change your loops from i <= 9 to i < 9.


That's true.We missed that really big one.(rates up;))

Quote:
system("PAUSE"); is not a portable command.


Oh come now, it's his first game[smile].,knowledge never harmed anyone though....[grin]
______________________________________________________________________________________________________
[AirBash.com]
Thanks for the comments. It will help me out greatly.

However, one note if you played the game you see the format of display is as follows (ignore " ' " that is so the spacing works in this window lol

' | |
' | |
' | |

now originally I had my array boardData[8]; however when I went to put in input to add a X or O to boardData[0]; it came out like this

'X
' | |
' | |
' | |

that is why I made it 9 and totally ignored the 0 it was there but never used. it is a small waste in memory anyone know how to fix that. I have a feeling it was in my board drawing calculations. that is the if(i % 3 != 0) part of the code.
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup

This topic is closed to new replies.

Advertisement