The game does not want to exit/close. Somebody enlighten me as to what I've missed? Also, do you think i have coded the game properly?
Source code:
#include<iostream>
#include<iomanip>
using namespace std;
void drawBoard(char board[][3]);
char checkWinner3by3(char board[][3]);
int main()
{
char board[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
int row;
int column;
bool is_move;
bool is_row;
bool is_column;
cout<<"********** TIC TAC TOE ************\n";
{
is_move = false;
is_row = false;
is_column = false;
drawBoard(board);
cout << "Player ";
if(player == 'X')
{
cout << 1;
}
else
{
cout << 2;
}
cout << "'s turn:" << endl;
is_move = false;
while(!is_move)
{
while(!is_row)
{
cout << "Row: ";
cin >> row;
if(row == 1 || row == 2 || row == 3)
{
is_row = true;
}
else
{
cout << endl << "Invalid row!" << endl;
}
}
/
is_column = false;
while(!is_column)
{
cout << "Column: ";
cin >> column;
if(column == 1 || column == 2 || column == 3)
{
is_column = true;
}
else
{
cout << endl << "Invalid column!" << endl;
}
}
Irrelevant stuff here.
if(board[row-1][column-1] == ' ')
{
board[row-1][column-1] = player;
is_move = true;
if(player == 'X')
{
player = 'O';
}
else
{
player = 'X';
}
}
else
{
cout<<"The selected space is occupied!" << endl;
cout << "Select a different space:" << endl << endl;
drawBoard(board);
}
}
cout << endl;
Checking the winner
winner = checkWinner3by3(board);
if(winner == 'X' || winner == 'O')
{
drawBoard(board);
cout<<"Congratulations! Player ";
if(winner == 'X')
{
cout << 1;
}
else
{
cout << 2;
}
cout<<" is the winner!"<<endl;
}
else if(winner == 'T')
{
drawBoard(board);
cout << "It's a tie!" << endl;
}
}
system("pause");
return 0;
}
Board is here.
void drawBoard(char board[][3])
{
char print[][3] = {{' ',' ',' '},
{' ',' ',' '},
{' ',' ',' '}};
cout << " 1 2 3" << endl;
cout << " +---+---+---+" << endl;
cout << " 1" << " | " << print[0][0] << " | " << print[0][1] << " | "
<< print[0][2] << " | " << endl;
cout << " +---+---+---+" << endl;
cout << " 2" << " | " << print[1][0] << " | " << print[1][1] << " | "
<< print[1][2] << " | " << endl;
cout << " +---+---+---+" << endl;
cout << " 3" << " | " << print[2][0] << " | " << print[2][1] << " | "
<< print[2][2] << " | " << endl;
cout << " +---+---+---+" << endl;
}
char checkWinner3by3(char board[][3])
{
for(i=0; i<3; i++)
{
if(board[i][0]==board[i][1] && board[i][0]==board[i][2])
{
return board[i][0];
}
}
for(i=0; i<3; i++)
{
if(board[0][i]==board[1][i] && board[0][i]==board[2][i])
{
return board[0][i];
}
}
if(board[0][0]==board[1][1] && board[1][1]==board[2][2])
{
return board[0][0];
}
if(board[0][2]==board[1][1] && board[1][1]==board[2][0])
{
return board[0][2];
}
return ' ';
}
This is the entire source code - i wanted to make a game and i honestly think this is the best way to start by knowing what i can do to improve it.
You have not declared the variable "player" & "winner" yet have initialized them...but this could be because the full code is not displayed.
you have system("pause") before return... why did you put that there?
...now that I look further its all screwed up
I made a Tic-Tac-Toe once and it's kinda similar to what your trying to do apart from selection via 2d array, you should consider using parts of it to correct your code.
#include <iostream>
#include <iomanip>
using namespace std;
char* cBox{ new char[9]{ '1', '2', '3', '4', '5', '6', '7', '8', '9' } }; // cBox are tic tac toe squares
char* PcBox{ nullptr }; // PcBox will be pointers to cBox squares
bool EndGame{ true }, VailidMove{ true }, WinGame{ true }; // Global bool varibles are initially set to true to test for validity
size_t PlayerMove{ 1 };
int Move;
int score(size_t PlayerMove); /********************************/
void Board(); /* */
void error(); /* Function Prototypes */
void GameOver(); /* */
int scoreboard(int score1, int score2); /********************************/
int main() {
int score1{}, score2{};
int sum{};
int winner{};
int const total{ 756 };
char PlayerIcon;
// do while loop
do {
// print scoreboard
scoreboard(score1, score2);
// Print board
Board();
// This conditional forces the first Player to be 'X'... Player2 'O'
(PlayerMove == 1) ? PlayerIcon = 'X' : PlayerIcon = 'O';
// Time for the player to move
cout << endl << setw(51) << "Player" << PlayerMove << "'s move:";
cin >> Move;
VailidMove = false; // ValidMove is assigned to false within the "do loop"...it will remain false until a valid key is entered..
//... it's conditionally tested within the while loop until the player's move is true(valid)
// Loop until we get a valid move
while (!VailidMove) {
system("CLS"); // Clear the screen
(PcBox = &cBox[Move - 1]); // For our move selection, point PcBox to the address of the array cBox[index] on the free store
if (!(*PcBox == 'X' || *PcBox == 'O') && (cin) && Move != 0) // this checks the location for PlayerIcons...as one cannot place a new playericon where one already resides...
// ...also tests whether a legit key input..aka not a "letter" or a "0"
{
VailidMove = true;
*PcBox = PlayerIcon; // A valid playericon is placed in a free box on the board
}
else
{
error(); // Anything else other than a valid selection will throw an error and return to the beginning of the block...
return main(); // ...querying the player for a valid selection until one is entered
}
};
EndGame = false; // Again like "VailidMove" we set EndGame to false to test against the following conditions
// This is a combintion of seperate win conditions... 3 the same, across or diagonal over entire board
if (cBox[0] == cBox[1] && cBox[1] == cBox[2])
GameOver();
if (cBox[0] == cBox[4] && cBox[8] == cBox[4])
GameOver();
if (cBox[1] == cBox[4] && cBox[7] == cBox[4])
GameOver();
if (cBox[2] == cBox[4] && cBox[6] == cBox[4])
GameOver();
if (cBox[2] == cBox[8] && cBox[5] == cBox[8])
GameOver();
if (cBox[3] == cBox[0] && cBox[6] == cBox[0])
GameOver();
if (cBox[3] == cBox[4] && cBox[5] == cBox[4])
GameOver();
if (cBox[6] == cBox[8] && cBox[7] == cBox[8])
GameOver();
// If the board is full and no one wins then it is a tie...this piece just sums up all the player icons as ascii integers...
// ...if the board is full of them, then the sum is 756 and it is a tie.
sum += (*PcBox); // add player icon to sum...Ascii to int
if ((sum == total) && !EndGame) // if sum of playericon for entire board = 756...no win
{
EndGame = true;
WinGame = false;
sum = 0; //reset sum to zero
scoreboard(score1, score2);
}
// End/Win game conditions
if (EndGame) { // game over? test choices
if (WinGame) { // We nest this here soley if EndGame & WinGame is true... else if just WinGame is true its a draw
if (PlayerMove == 1) { score1 = score(PlayerMove); }
if (PlayerMove == 2) { score2 = score(PlayerMove); }
scoreboard(score1, score2);
winner = PlayerMove;
}
Board();
if (WinGame)
cout << "\n" << setw(51) << "PLAYER " << winner << " WINS!" << endl;
cout << endl << setw(57) << "Game Over!!!" << endl;
cout << endl << setw(59) << "Play again y/n?"; // Query the player for another game
char PlayAgain;
cin >> PlayAgain;
// This resets the board, if the player wants another game, it uses a for loop to increment simultaneously it's "ascii integer", along side it's "int" equivalent...
//... overwriting & reseting the board from 1-9 with the original characters
if (PlayAgain == 'y' || PlayAgain == 'Y') {
EndGame = false;
for (int i = 0, j = 49; i < 9 && j <= 57; i++, j++) // ASCII int 49 = char '1'... to 57 = char '9'
{
(cBox[i] = (char)j); // Clear the board
}
sum = 0; // Reset sum to zero
system("CLS"); // Clear the screen
}
PlayerMove = 1;
if (PlayAgain == 'n') {
EndGame = true;
}
}
else
{
(PlayerMove == 1) ? PlayerMove = 2 : PlayerMove = 1;
}
} while (!EndGame);
delete[] cBox; // Free up memory...
cBox = nullptr;
cout << "\n\t\t\t\t\t";
return 0;
}
// Function definiton to print game board
inline void Board() {
{
cout << endl << '\n' << '\n' << endl;
cout << setw(50) << cBox[0] << "|" << cBox[1] << "|" << cBox[2] << endl;
cout << setw(54) << "-+-+-" << endl;
cout << setw(50) << cBox[3] << "|" << cBox[4] << "|" << cBox[5] << endl;
cout << setw(54) << "-+-+-" << endl;
cout << setw(50) << cBox[6] << "|" << cBox[7] << "|" << cBox[8] << endl;
}
}
// Function definiton to keep score
int score(size_t PlayerMove)
{
int static score1{ 1 };
int static score2{ 1 };
if (PlayerMove % 2)
return score1++;
else
return score2++;
}
// Function definiton to print scoreboard
int scoreboard(int score1, int score2)
{
cout << endl << setfill(' ') << setw(47) << "PLAYER 1: " << score1 << " " << "PLAYER 2: " << score2;
return(score1, score2);
}
// Function definiton to throw an error
void error() {
{
cout << setfill(' ') << setw(64) << "Invalid Move. Try again." << endl;
cin.clear(); //clear the error flags.
cin.ignore(); //sync up the stream in case the user entered white space
}
}
// Function definiton to end game
void GameOver()
{
EndGame = true;
}
Related
So im working on a project for school and i just cant get this to work. everything else seems to run but when i input the users choice for q, s, z10, z25,z5,z1 it loops indefinetly. i cant figure out why it keeps running the function over and over. im not quite sure if im just typing something wrong or what but this is the only thing im really stuck on currently. Here is the code
#include<iostream>
#include<string>
using namespace std;
struct Inventory
{
int Pack_25oz;
int Pack_10oz;
int Pack_5oz;
int Pack_1oz;
};
void show_Menu();
void initialize (Inventory& I);
void add_25OZ (Inventory& I, int P25);
void add_10OZ (Inventory& I, int P10);
void add_5OZ (Inventory& I, int P5);
void add_1OZ (Inventory& I, int P1);
void Place_Order(Inventory& I, int amount);
void show (Inventory& I);
int main(){
Inventory I;
string choice;
int nop= 0;
initialize(I);
show_Menu();
cout << "Dear User! please make a choice from above menu : " << endl;
getline(cin,choice);
while(choice!="q" or choice != "Q"){
if(choice == "s"|| choice == "S"){
show(I);
}
else if(choice == "z25" || choice == "Z25"){
cout << "Enter the number of packages : \n";
cin >> nop;
add_25OZ(I, nop);
}
else if(choice == "z10" || choice == "Z10"){
cout << "Enter the number of packages : \n";
cin >> nop;
add_10OZ(I, nop);
}
else if(choice == "z5"||choice == "Z5"){
cout << "Enter the number of packages : \n";
cin >> nop;
add_5OZ(I, nop);
}
else if(choice == "z1"|| choice == "Z1"){ // choice equal to "z1" or "Z1"
cout << "Enter the number of packages : \n" ; // prompt for number of packages
cin >> nop ; // accept user input
add_1OZ( I, nop);// call add_1OZ function
}
else if(choice == "o"||choice == "O") {
cout << "Enter the number of ounces : ";// prompt for number of ounces
int noun; // noun stands for number of ounces
cin >> noun;// accept user input
Place_Order( I, noun);
}
else if (choice == "q" || choice == "Q"){ // Output final message that the program has ended
cout << "The program has ended.";
break;
}
else
cout << "invalid comand" << endl;
};
return 0;
}
void show_Menu(){
cout << "S - Show Inventory" << endl;
cout << "Z25 - Add 25 oz packages"<< endl;
cout << "Z10 - Add 10 oz packages"<< endl;
cout << "Z5 - Add 5 oz packages"<< endl;
cout << "Z1 - Add 1 oz packages "<< endl;
cout << "O - Place order"<< endl;
cout << "Q - End"<< endl;
}
void show (Inventory& I)
{
cout << "The Inventory comprises of the following:\n 1. Pack_25oz : " << I.Pack_25oz << "\n 2.
Pack_10oz : " << I.Pack_10oz << "\n 3. Pack_5oz : " << I.Pack_5oz << "\n 4. Pack_1oz : " <<
I.Pack_1oz <<endl ;
}
void initialize (Inventory& I) {
int var = 0 ;
I.Pack_25oz = var;
I.Pack_10oz = var;
I.Pack_5oz = var;
I.Pack_1oz = var;
}
void add_25OZ (Inventory& I, int P25) {
I.Pack_25oz += P25;
}
void add_10OZ (Inventory& I, int P10) {
I.Pack_10oz += P10;
}
void add_5OZ (Inventory& I, int P5) {
I.Pack_5oz += P5;
}
void add_1OZ (Inventory& I, int P1) {
I.Pack_1oz += P1;
}
void Place_Order(Inventory& I, int amount) {
int subtract;
subtract = amount / 25;
if (I.Pack_25oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_25oz -= subtract; }
amount = amount % 25;
subtract = amount / 10;
if (I.Pack_10oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_10oz -= subtract; }
amount = amount % 10;
subtract = amount / 5;
if (I.Pack_5oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_5oz -= subtract; }
amount = amount % 5;
subtract = amount / 1;
if (I.Pack_1oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_1oz -= subtract;
cout << "Order Fufilled" << endl;
}
}
It seems you call getline outside of the loop. so choice is never updated.
So, to further explain my question, when I fill my whole board in tic tac toe with "X" and "O" and there is no winner, the game keeps on playing even when the spaces are filled. It just keeps saying enter a row and column still. It doesn't know when to stop. I'm not sure whats wrong with my code.
Problems where I think it is: I think my problem lies in my checkWinner function because my bool winner = false is suppose return my statement "Its a tie" if every space on my board is filled but it doesn't output that. It also may be my main function.
How do I fix this problem because I've been stuck trying to figure it out. So if anyone can help, I appreciate it. Thanks!
#include <iostream>
#include <string>
using namespace std;
const int ROWS = 3; // For the number of rows.
const int COLS = 3; // For the number of columns.
void showBoard(char[][COLS], int); // Shows the board.
void playerChoice(char[][COLS], char); // shows the player choice.
bool checkWinner(char[][COLS], string&); // check the winner.
char board[ROWS][COLS] = { { '*', '*', '*' }, { '*', '*', '*' }, { '*', '*', '*' } };
int main()
{
char board[ROWS][COLS] = { { '*', '*', '*' }, { '*', '*', '*' }, { '*', '*', '*' } }; // displays
whats inside the board.string gwinner = " "; // holds the winner until there is a winner.
bool winner;
int counter = 1;
showBoard(board, 3); // displays the board.
playerChoice(board, 'X');
showBoard(board, 3);
while (counter) {
playerChoice(board, 'O');
showBoard(board, 3);
if (winner = checkWinner(board, gwinner))
break;
playerChoice(board, 'X');
showBoard(board, 3);
if (winner = checkWinner(board, gwinner))
break;
}
cout << gwinner;
}
void showBoard(char arr[][COLS], int SIZE) // Displays the board.
{
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++)
cout << '|' << arr[row][col];
cout << '|' << endl;
}
}
void playerChoice(char arr[][COLS], char name) // what row and column the user wants.
{
int row, columns; // for the user to enter the row and column.
int occupied;
do {
cout << "What row would you like?\n";
cout << "Row: ";
cin >> row;
while (row < 1 || row > 3) // input validation.
{
cout << "Error please pick a row between 1 and 3.\n";
cout << "Row: ";
cin >> row;
cout << endl;
}
cout << "What column would you like?\n";
cout << "Column: ";
cin >> columns;
while (columns < 1 || columns > 3) // input validation.
{
cout << "Error,please pick a column between 1 and 3.\n";
cout << "Column: ";
cin >> columns;
cout << endl;
}
if (arr[row - 1][columns - 1] == '*') // checks to see if * is empty
{
arr[row - 1][columns - 1] = name; // diplays either X or O
occupied = 1;
}
else {
cout << "\nThis space is occupied.\n";
cout << "Please select again\n";
occupied = 0;
}
} while (occupied == 0);
}
bool checkWinner(char arr[][COLS], string& gwinner) // Check if the winner met the right conditions
{
bool winner = false;
if ((arr[0][0] == arr[0][1]) && (arr[0][1] == arr[0][2]) && (arr[0][1] != '*')) // checks row
{
winner = true;
cout << "The winner is:" << arr[0][0] << endl;
}
else if ((arr[1][0] == arr[1][1]) && (arr[1][1] == arr[1][2]) && (arr[1][1] != '*')) // checks row
{
winner = true;
cout << "The winner is:" << arr[1][0] << endl;
}
else if ((arr[2][0] == arr[2][1]) && (arr[2][1] == arr[2][2]) && (arr[2][1] != '*')) // checks row
{
winner = true;
cout << "The winner is:" << arr[2][0] << endl;
}
else if ((arr[0][0] == arr[1][0]) && (arr[1][0] == arr[2][0]) && (arr[1][0] != '*')) // checks columns
{
winner = true;
cout << "The winnner is:" << arr[0][0] << endl;
}
else if ((arr[0][1] == arr[1][1]) && (arr[1][1] == arr[2][1]) && (arr[1][1] != '*')) // checks
columns
{
winner = true;
cout << "The winnner is:" << arr[0][1] << endl;
}
else if ((arr[0][2] == arr[1][2]) && (arr[1][2] == arr[2][2]) && (arr[1][2] != '*')) // checks
columns
{
winner = true;
cout << "The winnner is:" << arr[0][2] << endl;
}
else if ((arr[0][0] == arr[1][1]) && (arr[1][1] == arr[2][2]) && (arr[1][1] != '*')) // checks
diagonal
{
winner = true;
cout << "The winnner is:" << arr[0][0] << endl;
}
else if ((arr[2][0] == arr[1][1]) && (arr[1][1] == arr[0][2]) && (arr[1][1] != '*')) // checks
diagonal
{
winner = true;
cout << "The winnner is:" << arr[2][0] << endl;
}
else {
gwinner = "It's a Tie."; // else if the winner is a tie.
winner = false;
}
return winner; // returns the winner
}
This is a simple tic-tac-toe game as I'm sure you've seen, the code is incomplete. I don't need somebody to look over all of it, just how to format the 2-D character array before '.empty' so that I know how to access it as a reference. If you can take a look at inside the "int get_row()", that'd be great.
I've already tried everything that my textbook and C++ tutorials tell me, and I"m pretty sure none of them have 2-D arrays as part of the exercises. I mean, I can't find it, if you can send a link that'd be nice.
#include <iostream>
#include <string>
#include <array>
using namespace std;
char board[3][3];
void print_board(char board[3][3])
{
cout << " 0 1 2 " << endl;
cout << "0 " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " " << endl;
cout << " -----------" << endl;
cout << "1 " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " " << endl;
cout << " -----------" << endl;
cout << "2 " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " " << endl;
}
void clear_board(char board[][3])
{
}
int get_row(char board[][3], char player)
{
int row;
cout << "Please enter the row move for player " << player << endl;
cin >> row;
if (board.empty())
return row;
}
int get_column(char board[][3], char player)
{
int column;
cout << "Please enter the column move for player " << player << endl;
cin >> column;
return column;
}
bool check_win(char board[][3], char player)
{
return true;
}
bool board_full(char board[][3])
{
return true;
}
bool square_occupied(char board[][3],int row,int column)
{
return true;
}
void get_move(char board[3][3], char player)
{
do
{
do {
int row, column;
get_row(board, player);
get_column(board, player);
square_occupied(board, row, column);
} while (square_occupied);
board_full(board);
} while (!board_full);
}
int main()
{
string play_again = "Y", answer;
int row, column;
char player = 'X';
cout << "Welcome to tic-tac-toe!" << endl;
cout << "Please, use the coordinates for rows and columns to record moves." << endl;
do {
do {
print_board(board);
board_full(board);
get_move(board, player);
check_win(board, player);
if (player == 'X')
{
player = 'O';
}
else
{
player = 'X';
}
} while (!check_win);
cout << "Would you like to play again? (Y/N)";
cin >> answer;
}while (answer == play_again);
return 0;
}
I just want to be able to check if the array container at [row] is going to be empty or not. I really just can't use reference arrays, that's all.
If you declare a C-array, it's never empty (and also it doesnt have aempty` member function).
char board[3][3]; //Never empty - always has 9 values
Of course, a Tic Tac Toe board can be empty. The array representing the board isn't empty, but the values in the array are probably set to either 0 or some other value that indicates that they're empty.
We can write a small class to represent the board, and give it a empty function:
struct Board {
char board[3][3];
Board() : board() {}
bool empty() const {
char* data = &board[0][0];
for(int i = 0; i < 9; i++) {
if(data[i] != 0) return false;
}
return true;
}
bool rowEmpty(int row) const {
return board[row][0] == 0 && board[row][1] == 0 && board[row][2] == 0;
}
bool colEmpty(int col) const {
return board[0][col] == 0 && board[1][col] == 0 && board[2][col] == 0;
}
void putX(int row, int col) {
board[row][col] = 'X';
}
void putO(int row, int col) {
board[row][col] = 'O';
}
// This function returns a reference so you can modify it if you want
char& getSquare(int row, int col) {
return board[row][col];
}
};
By creating a class to represent the board, you can add whatever functionality and member functions you want!
This is the function of a larger program. This function just figures out how many characters are in an alphanumeric word. Weird thing is, it counts apostrophes when running it in Xcode, but not after compiling and running it in Terminal. Any suggestions?
#include <iostream>
#include <iomanip>
#include <ctype.h>
using namespace std;
int WordLength();
void DisplayTable(int WF[]);
int main()
{
int WordFrequency[16]={0};
int TempLengthStorage=0;
TempLengthStorage=WordLength();
while (TempLengthStorage!=0)
{
if (TempLengthStorage==1)//skipping subscript 0 - not using it
++WordFrequency[1];
else if (TempLengthStorage==2)
++WordFrequency[2];
else if (TempLengthStorage==3)
++WordFrequency[3];
else if (TempLengthStorage==4)
++WordFrequency[4];
else if (TempLengthStorage==5)
++WordFrequency[5];
else if (TempLengthStorage==6)
++WordFrequency[6];
else if (TempLengthStorage==7)
++WordFrequency[7];
else if (TempLengthStorage==8)
++WordFrequency[8];
else if (TempLengthStorage==9)
++WordFrequency[9];
else if (TempLengthStorage==10)
++WordFrequency[10];
else if (TempLengthStorage==11)
++WordFrequency[11];
else if (TempLengthStorage==12)
++WordFrequency[12];
else if (TempLengthStorage==13)
++WordFrequency[13];
else if (TempLengthStorage==14)
++WordFrequency[14];
else if (TempLengthStorage>=15)
++WordFrequency[15];
TempLengthStorage=WordLength();
}
DisplayTable(WordFrequency);
}
int WordLength()
{
int LetterCount=0;
int EndOfWord=0;
char Input;
char NextChar;
cin.get(Input);
while (EndOfWord!=1 && !cin.eof())
{
if (Input==' ' || Input=='\n' || Input=='.' || Input=='!' || Input=='?' || Input==',')
{//do nothing if whitespace or punctuation, essentially skips over them
}
else if (Input=='-')
{
NextChar=cin.peek();
if ((isalpha(NextChar)) || (isnumber(NextChar)))//this includes the hyphen in words that have hyphens (refer to funtion notes)
++LetterCount;
if (NextChar=='\n')//for cases where the hyphen doesn't add to word length (refer to function notes)
{
cin.get(Input);//dont count it and get next character
}
}
else if (Input=='\'')
++LetterCount;
else if ((isalpha(Input)) || (isnumber(Input)))
{
++LetterCount;
NextChar=cin.peek();
if (NextChar==' ' || NextChar=='\n' || NextChar=='.' || NextChar=='!' || NextChar=='?' || NextChar==',' || NextChar==')')//included ) as a condition to end words for cases such as (219)
{
EndOfWord=1;
}
}
cin.get(Input);
}
return LetterCount;
}
void DisplayTable(int WF[])
{
int TotalWords=0;
float TotalLetters=0;//made a float for float based masth later on when finding average
float Average=0;
cout << endl;
cout << "Word Length Frequency" << endl;
cout << "----------- ---------" << endl;
for (int i=1; i<=15; ++i)
{
/*This portion of the loop displays the table*/
cout << " ";
cout << setw(2) << i;
cout << " ";
cout << WF[i] << endl;
/*this portion of the loop does the calculations needed to find the average word length*/
TotalWords += WF[i];
TotalLetters += (i * WF[i]);
}
cout << "\nTotal Words = " << TotalWords << endl << endl;
cout << "Total Letters = " << TotalLetters << endl << endl;
Average = TotalLetters/TotalWords;
cout << "Average Word Length: " << Average << endl;
}
I used "Ain't" in both situations, just for testing purposes.
Hello i am making a tic tac toe game in console.
What's wrong with my code?
I Got linker settings set as console.
code:
// Tic tac Toe
// Plays a tic tac toe game against a npc
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// global constants
const char X = 'X';
const char O = '0';
const char EMPTY = ' ';
const char TIE = 'T';
const char NO_ONE = 'N';
//function prototypes
void instructions();
char askYesNo(string question);
int askNumber(string question, int high, int low =0);
char humanPiece();
char opponent(char piece);
void displayBoard(const vector<char>& board);
char winner(const vector<char>& board);
bool isLegal(const vector<char>& board, int move);
int humanMove(const vector<char>& board, char human);
int computerMove(const vector<char>& board, char computer);
void announceWinner(char winner, char computer, char human);
int main()
{
int move;
const int NUM_SQUARES = 9;
vector<char> board(NUM_SQUARES, EMPTY);
instructions();
char human = humanPiece();
char computer = opponent(human);
char turn = X;
displayBoard(board);
while (winner(board) == NO_ONE)
{
if (turn == human)
{
move = humanMove(board, human);
board[move] = human;
}
else
{
move = computerMove(board, computer);
board[move] = computer;
}
displayBoard(board);
turn = opponent(turn);
}
announceWinner(winner(board), computer, human);
return 0;
}
void instructions()
{
cout << "Welcome to the ultimate man-machine showdown: Tic Tac Toe.\n";
cout << "--I'm gonna cut you in half like a knife and butter like a lightsaber and steel!!!\n\n";
cout << "make your move now by entering a number, 0-8. The number\n";
cout << "corresponds to the desired board position , as illustrated: \n\n";
cout << " 0|1|2 \n";
cout << " ------- \n";
cout << " 3|4|5 \n";
cout << " ------- \n";
cout << " 6|7|8 \n\n";
cout << "Prepare yourself human, the battle is about to begin.\n\n";
}
char askYesNo(string question)
{
char response;
do
{
cout << question << "(y\n): ";
cin >> response;
}while (response != 'y' && response != 'n');
return response;
}
int askNumber(string question, int high, int low)
{
int number;
do
{
cout << question << "(" << low << "-" << high << "): ";
cin >> number;
}while (number > high || number < low);
return number;
}
char humanPiece()
{
char go_first = askYesNo("Do you require the first move?");
if (go_first == 'y')
{
cout << "\n Then take the first move. You will need it.\n";
return X;
}
else
{
cout << "Then I will make the first move.\n";
return 0;
}
}
char opponent(char piece)
{
if (piece == 'X')
{
return X;
}
else
{
return 0;
}
}
void displayBoard(const vector<char>& board)
{
cout << "\n\t" << board[0] << "|" << board[1] << "|" << board[3];
cout << "\n\t" << "-------";
cout << "\n\t" << board[3] << "|" << board[4] << "|" << board[5];
cout << "\n\t" << "-------";
cout << "\n\t" << board[6] << "|" << board[7] << "|" << board[8];
cout << "\n\n";
}
char winner(const vector<char>& board)
{
// all possible winning rows
const int WINNING_ROWS[8][3] = {{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}};
const int TOTAL_ROWS = 8;
// if any winning row has three values wich are the same(and not EMPTY)
// then we have a winner
for (int row = 0; row < TOTAL_ROWS; ++row)
{
if ((board[WINNING_ROWS[row][0]] != EMPTY) && (board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) && (board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]]))
{
return board[WINNING_ROWS[row][0]];
}
}
//since nobody has won check for a tie (no empty squares left)
if (count(board.begin(), board.end(), EMPTY) == 0)
{
return TIE;
}
//since nobody has won and it isn't a tie, the game ain't over
return NO_ONE;
}
inline bool isLegal(int move, const vector<char>& board)
{
return (board[move] == EMPTY);
}
int humanMove(const vector<char>& board, char human)
{
int move = askNumber("Where will you move?", (board.size() - 1));
while (!isLegal(move, board))
{
cout << "\n That square is already occupied, foolish human.\n" << endl;
int move = askNumber("Where will you move?", (board.size() - 1));
}
cout << "Fine....\n";
return move;
}
int computerMove(vector<char> board, char computer)
{
unsigned int move = 0;
bool found = false;
//if the pc can win on next move I will take that move
while (!found && move < board.size())
{
if (isLegal (move, board))
{
board[move] = computer;
found = winner(board) == computer;
board[move] = EMPTY;
}
if (!found)
{
++move;
}
}
// otherwise if the human can win with the next move that's the move I will make
if (!found)
{
move = 0;
char human = opponent(computer);
while (!found && move < board.size())
{
if (isLegal(move, board))
{
board[move] = human;
found = winner(board) == human;
board[move] = human;
}
if (!found)
{
++move;
}
}
}
// otherwise i'll be moving to the next best square
if (!found)
{
move = 0;
unsigned int i = 0;
const int BEST_MOVES[] = {4,0,2,6,8,1.3,5,7};
// pick best open square
while (!found && i < board.size())
{
move = BEST_MOVES[i];
if (isLegal(move, board))
{
found = true;
}
++i;
}
}
cout << "I shall take square number" << move << endl;
return move;
}
void announceWinner(char winner, char computer, char human)
{
if (winner == computer)
{
cout << winner << "has won!\n";
cout << "As I predicted human, I am triumphant once more!\n";
}
else if (winner == human)
{
cout << winner << "has won" << endl;
cout << "no, no it cannot be! Somehow you tricked me Human!\n";
}
else
{
cout << "It's just a tie, I'll beat you next time! \n";
cout << "You cannot beat me though!";
}
}
The forward declaration of -
int computerMove(const vector<char>& board, char computer);
is different from the actual implementation. ( Misses the const part )
int computerMove(vector<char> board, char computer)