One of my friends, Maadhavan, got inspired by me and decided he would learn c++ and make a game. I have to say- he has such a strong determination, he learnt c++ in about two weeks (or should I say- learnt whatever is possible in two weeks) and started coming up with games he tried to make from scratch. Sadly, none of his games worked, but I told him not to loose hope at all, and came up with an idea about doing a tutorial on making the simplest game with c++ for him.(Thats nice, isn't it? He got inspired by me and I got inspired by him!) Maadhavan, this one is for you.
Go on! Play around with it for a while!
Here is the source code straight away!
#include <iostream> using namespace std; char Matrix[9] = {'1','2','3','4','5','6','7','8','9'}; char Player = 'X'; void Draw() { system("cls"); cout<<"\t\t-----T I C - T A C - T O E----- \t\t by Anurup Dey.\n\n"; cout<<"\n\t\t\t -------------\n"; for (int i = 0; i<3; ++i) { cout<<"\t\t\t"; for (int j = 0; j<3; ++j) { cout<<" | "<<Matrix[(i*3)+j]<<""; } cout<<" |\n\t\t\t -------------\n"; } } void TogglePlayer( ) { if (Player=='X') Player = 'O'; else Player = 'X'; } bool PlayTurn(int cell) { if (cell < 1 || cell > 9) return false; if (Matrix[cell-1]!='X'||Matrix[cell-1]!='O') { Matrix[cell-1] = Player; return true; } else return false; } int There_is_a_winner( ) { //Simple checking. for (int i = 0; i<3; i += 3) { //first we check the rows. if (Matrix[i]=='X' && Matrix[i+1]=='X' && Matrix[i+2]=='X') { return 1; } if (Matrix[i]=='O' && Matrix[i+1]=='O' && Matrix[i+2]=='O') { return 2; } } for (int j = 0; j<3; ++j) { //we check the colunms if (Matrix[(0*3)+j]=='X' &&Matrix[(1*3)+j]=='X' &&Matrix[(2*3)+j]=='X') return 1; if (Matrix[(0*3)+j]=='O' &&Matrix[(1*3)+j]=='O' &&Matrix[(2*3)+j]=='O') return 2; } return 0; } int main( ) { bool endGame = false; while (!endGame) { Draw( ); cout<<"\nIt is "<<Player<<"'s chance.\n\n\n" <<"Enter the number of the cell you want to aquire.\n(or enter 0 to quit)\n\n>> "; int cell; cin>>cell; if (cell==0) break; if (PlayTurn(cell)) { TogglePlayer( ); if (There_is_a_winner( )) { Draw( ); cout<<" THERE IS A WINNER!\n\n"; system("pause"); endGame = true; } } else { cout<<"Invalid move, try again.\n"; system("pause"); } } }
This will make a tic-tac-toe game.
I was actually thinking about getting you through each line of code out here, but at this stage that is too much for me to write, as to tell you what this does at each line is like tell a three year old how the economy of a country works- there is simply too much there to write.
Hope you enjoy playing my game though. Most of you know some programming already, so I would recommend you write out each line of code by yourself and don't copy paste the whole code from here just like that.
No comments:
Post a Comment