Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
First and foremost, I ask that anyone who is replying consider these factors. Currently I have very-low knowledge in arrays and enumerations, most of the basics are understood such as what you will see below. I have been trying to figure this problem out for 3 days and now I'm asking for help before I keep burning myself out every 45mins-1hr.
Problem: Write a two-player tic-tac-toe game, allowing two humans to play against each other; use
enums when possible to represent the values of the board
#include<iostream>
#include<string>
bool tie = false;
std::string p1, p2;
enum turnbased{token1, token2, empty};
char space[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int row;
int column;
int token;
void board() //producing the required space[][] coordinates to empty squares
{
std::cout << " | | \n";
std::cout <<" "<<space[0][0]<<" | "<<space[0][1]<<" | "<<space[0][2]<<" \n";
std::cout << " ____|____|____\n";
std::cout <<" "<<space[1][0]<<" | "<<space[1][1]<<" | "<<space[1][2]<<" \n";
std::cout << " ____|____|____\n";
std::cout << " | | \n";
std::cout <<" "<<space[2][0]<<" | "<<space[2][1]<<" | "<<space[2][2]<<" \n";
std::cout << " | | \n";
}
void playerswitch()
{
turnbased assignto = token1; //initializing enum type to define token1 for turns to occur
int token = empty; //declaring token to equivalate to enum variable{empty} in position()
if(assignto)
{
std::cout << p1 << " choose slot for - " << token1;
assignto = token2;
}
else(assignto == token2);
{
std::cout << p2 << " choose slot for - " << token2;
assignto;
}
std::cin >> token;
}
void position()
{
if(empty == 1) // positioning array space
{
row = 0;
column = 0;
}
else if(empty == 2)
{
row = 0;
column = 1;
}
else if(empty == 3)
{
row = 0;
column = 2;
}
else if(empty == 4)
{
row = 1;
column = 0;
}
else if(empty == 5)
{
row = 1;
column = 1;
}
else if(empty == 6)
{
row = 1;
column = 2;
}
else if(empty == 7)
{
row = 2;
column = 0;
}
else if(empty == 7)
{
row = 2;
column = 1;
}
else if(empty == 8)
{
row = 2;
column = 2;
}
else(empty < 1 || empty > 9);
{
std::cout << "Invalid!!!" << std::endl;
}
//token check and execution
if(token1 && space[row][column] != token1 && space[row][column] != token2)
{
space[row][column] = token1;
token2;
}
else if(token2 && space[row][column] != token1 && space[row][column] != token2)
{
space[row][column] = token2;
token1;
}
else{
std::cout << "Invalid space!" << std::endl;
position();
}
playerswitch();
board();
}
//win check
bool results()
{
for(int i = 0; i < 3; i++)
{ //checks horizontally and vertically
if(space[i][0] == space[i][1] && space[i][0] == space[i][2] || space[0][i] == space[1][i] && space[0][i] == space[2][i])
return true;
//checks diagonally
if(space[0][0] == space[1][1] && space[1][1] == space[2][2] || space[0][2] == space[1][1] && space[1][1] == space[2][0])
return true;
for(int j = 0; j < 3; j++)
{
if(space[i][j] != token1 && space[i][j] != token2)
{
return false;
}
}
}
tie = true;
return false;
}
int main()
{
std::cout << "Enter the name of the first player: \n";
getline(std::cin, p1);
std::cout << p1 << " is player1 so he/she will play first \n";
std::cout << "Enter the name of the second player: \n";
getline(std::cin, p2);
std::cout << p2 << " is player2 so he/she will play second \n";
while(!results())
{
board();
playerswitch();
position();
results();
}
if(token1 && tie)
{
std::cout << p2 << " wins!" << std::endl;
}
else if(token2 && tie)
{
std::cout << p1 << " wins!" << std::endl;
}
else
{
std::cout << "It's a draw!" << std::endl;
}
}```
I wont fix your code, but I will help you structure it so you can figure it and future problems out yourself.
First, get rid of all global variables. This is important because the way to reason about code is to look at individual parts in isolation. This is the only, the ONLY, way writing code scales.
To do this, define an interface and a clear job for each of your functions. Maybe add structs to keep data together that belongs together.
After you have changed the functions to work only on their input arguments (look up how functions receive arguments and return values), you can test each function on its own. Make sure your function to read in input works. Make sure your function to manipulate the playing field works. Do all this before you plug them together. This is called unit testing.
Once you are convinced, that regardless the data that your function receives it always does a proper job, plug them together and see if the result works. If it doesn't, your first goal is to figure out which function is broken. Go back to unit testing with new test inputs.
Rinse and repeat until your program works correctly.
Related
I'm making a program just to practice vectors and this has me stumped. The point of the program was to make a tournament to help people choose between restaurants.
Here is the code that causes an error:
#include <iostream>
#include <vector>
#include <string>
const int ITEMS_PER_MATCHUP = 2;
using namespace std;
int PromptChoice(string first, string second, string helpMessage = "") {
string input;
while (true) {
cout << "Which restaurant do you prefer, " << first << "(1) or " << second << "(2)? ";
cin >> input; //no need to protect as it is going into a string variable
if (input == "first" || input == "1" || input == "left" || input == "First" || input == "Left") {
return 0;
}
else if (input == "second" || input == "2" || input == "right" || input == "Second" || input == "Right") {
return 1;
}
// if the response was not recognized
else cout << endl << helpMessage << endl << "Please enter 1 or 2" << endl << "Please try again." << endl << endl;
}
}
int main() {
vector<string> list = { "Burger Place", "Italian Place", "Soup And Salad Place", "BBQ Place" };
vector<int> stillInTheRunning;
for (int index = 0; index < list.size(); index++) { //populates an array full of values 0 to the size of the array
stillInTheRunning.push_back(index);
}
int matchupsThisRound = stillInTheRunning.size();
for (int i = 0; i < matchupsThisRound; i += ITEMS_PER_MATCHUP) { //ITEMS_PER_MATCHEP == 2
int choice = PromptChoice(list[stillInTheRunning[i]], list[stillInTheRunning[i + 1]]);
//stillInTheRunning.erase(stillInTheRunning.begin() + i + choice);
stillInTheRunning.pop_back();
}
for (int i = 0; i < stillInTheRunning.size(); i++) { //print the vector
cout << endl << stillInTheRunning[i] << endl;
}
system("pause"); //I know I know don't use system. just for debuging?
}
If I understand the error it usually happens when you try to visit a vector index that is out of range. Something bigger than vector.size() - 1 but in this case it happened when I was trying to use vector.erase()
Thinking perhaps I just mugged the for loop I tried switching to pop_back() because I thought you can't mess that one up. But I still got the error.
Playing around with it I tried commenting out a few things.
Like if I comment out the prompting function:
for (int i = 0; i < matchupsThisRound; i += ITEMS_PER_MATCHUP) { //ITEMS_PER_MATCHEP == 2
//int choice = PromptChoice(list[stillInTheRunning[i]], list[stillInTheRunning[i + 1]]);
//stillInTheRunning.erase(stillInTheRunning.begin() + i + choice);
stillInTheRunning.pop_back();
}
No error
And if I comment out the pop_back():
for (int i = 0; i < matchupsThisRound; i += ITEMS_PER_MATCHUP) { //ITEMS_PER_MATCHEP == 2
int choice = PromptChoice(list[stillInTheRunning[i]], list[stillInTheRunning[i + 1]]);
//stillInTheRunning.erase(stillInTheRunning.begin() + i + choice);
//stillInTheRunning.pop_back();
}
also no error.
What is causing the problem???
I found it!
its here
PromptChoice(list[stillInTheRunning[i]], list[stillInTheRunning[i + 1]])
on the second run of the for loop i = 2;
after poping off one item off the back the vector's size was now 3 instead of 4 so stillInTheRunning[i + 1] was trying to get the item in index 3 which now does not exist.
The problem is when you pop_back, the size of stillInTheRunning decreases, but matchupsThisRound stays the same, so eventually the loop reaches the point where i+1 is out of the stillInTheRunning's range.
Also it's a bit weird that you're increasing i by 2 every cycle, but pop_back only once.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm simply trying to get the user to put in their name/age and verify if it's correct. If not then they get 4 tries before the program will abort. However my while loops don't loop, instead they just continue on to the next loop. I've tried a variation of things inside the while parenthesis (op != 1) (!(op = 1)) etc.
int main() {
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+ 1;
}
if (tries = 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 = 4) {
//abort the programhi
}
}
}
return 0;
}
I'm fairly new to C++ so I'm sorry if it does have a simple answer. But anyway, I've been debugging this for over half an hour and I looked online for 20+ minutes.
if (tries = 4) {
//abort the program
}
Change this to
if (tries == 4) {
//abort the program
}
And
f (op == 2) {
cout << "Please Try Again!";
tries+= 1; // tries+ 1;
}
You can increment value in C++ like this tries+ 1;. Either use tries+= 1; or tries++;
tries+ 1; should be tries += 1; or tries++;
And,
if (tries = 4) {
//abort the program
}
should be:
if (tries == 4) {
//abort the program
}
Your program should look like this:
int main()
{
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+= 1;
}
if (tries == 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 == 4) {
//abort the programhi
}
}
}
You have forget to use = sign at multiple places. tries = 4 should be tries == 4 for comparing variable tries with numeric 4. tries = 4 was reassigning the variable tries to four and your while loop was getting terminated after it's first run. Also, tries + 1 should be tries += 1 or tries++ to increment the value of tries variable by one.
score is an array of 10 scores in ascending order.
scoreName is an array of names associated with with each score.
I need to check if a new score is good enough to enter the the high score table and if so, insert it into the correct position and make sure scoreName is also updated to reflect any changes.
I am having problems with my current code:
//Table
for (int i = 0; i < leaderBoardSize; i++)
{
cout << scoreName[i] << "\t\t" << score[i] << endl;
}
system("pause");
//Check to see if you made the highScore
if (diceTotal >= score[9])
{
cout << "Congrats, you have made the HighScore Table !\nEnter Your Name.";
cin >> playerName;
for (int i = 9; i < leaderBoardSize; i--)
{
if (diceTotal <= score[i])
{
scoreName[i = i + 1] = scoreName[i];
score[i = i + 1] = score[i];
scoreName[i] = playerName;
score[i] = diceTotal;
break;
}
scoreName[i = i + 1] = scoreName[i];
score[i = i + 1] = score[i];
}
}
Here is the entire code:
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int main()
{
//dice game variables
int dice1 = 0;
int dice2 = 0;
int diceTotal = 0;
int round = 0;
string choice;
bool isDone = true;
//Scoreboard
const int leaderBoardSize = 10;
int score[10] = { 40, 33, 29, 24, 22, 19, 15, 12, 11, 9 };
string scoreName[leaderBoardSize] = { "Jason", "Steve", "Bob", "Timberduck", "Eric", "Susan", "Tyler", "Nick", "NinjaDave", "RaidenGunfire" };
string playerName;
//random number seeder
srand((unsigned int)time(NULL));
//Game instructions
cout << "dice game\n---------\nCreated By: Darcy Tellier\n--------------------------\nInstructions:\nRoll 2 dices. Try to get as close to 50 without going over." << endl;
//The Game loop
do
{
//resets game variables
diceTotal = 0;
round = 1;
//in game match loop
do
{
// display round #, current dice total, ask user to quit or re-roll.
cout << "Round\n-----\n " << round << endl;
cout << "current total:" << diceTotal << endl;
cout << "Roll dice (y/n)?";
cin >> choice;
//Checks the users imput for invalid characters
while (choice != "Y" && choice != "y" && choice != "N" && choice != "n")
{
cout << "invalid option. Choose y/n:" << endl;
cin >> choice;
}
if (choice == "Y" || choice == "y")
{
//roll dice
round += 1;
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
diceTotal = diceTotal + dice1 + dice2;
cout << "you have rolled a " << dice1 << " and a " << dice2 << endl;
if (diceTotal > 50)
{
isDone = false;
}
}
else
{
//break was used because "isDone = false" does not work here. The debugger shows that when the variable is set to false, it still ignores it and skips to the next round.
break;
}
} while (isDone == true || diceTotal < 50);
//end of round
if (diceTotal > 50)
{
cout << "\nGameOver" << endl;
cout << "You went over in " << round << " turns. You Lose!!! " << endl;
}
else
{
cout << "You stopped at " << round << " turns. Final score: " << diceTotal << "." << endl;
system("pause");
system("cls");
}
//Table
for (int i = 0; i < leaderBoardSize; i++)
{
cout << scoreName[i] << "\t\t" << score[i] << endl;
}
system("pause");
//Check to see if you made the highScore
if (diceTotal >= score[9])
{
cout << "Congrats, you have made the HighScore Table !\nEnter Your Name.";
cin >> playerName;
for (int i = 9; i < leaderBoardSize; i--)
{
if (diceTotal <= score[i])
{
scoreName[i] = playerName;
score[i] = diceTotal;
break;
}
}
}
//board display #2
for (int i = 0; i < leaderBoardSize; i++)
{
cout << scoreName[i] << "\t\t" << score[i] << endl;
}
system("pause");
//do you want to play again?
cout << "Do you want to play again";
cin >> choice;
while (choice != "Y" && choice != "y" && choice != "N" && choice != "n")
{
cout << "invalid option. Choose y/n:" << endl;
cin >> choice;
}
if (choice == "Y" || choice == "y")
{
system("cls");
isDone = true;
}
else
{
cout << "game over" << endl;
isDone = false;
}
} while (isDone);
system("pause");
return 0;
}
This is a copy of the assignment.
Note: I am not asking for you guys to do my work. I just want to figure out the highScore sorting thing.
The problem: arrays are not a good way to achieve what you want
You are trying to see if a score beat another score, and if so, replace that and move the rest of the scores down. I assume your scores are sorted, and that score is a int[10], but you have several problems:
1.
for (int i = 9; i < leaderBoardSize; i--)
You are attempting to iterate through your scores backwards, so you start at 9 (which I assume is the last index) and work your way down. Assuming leaderBoardSize is the total size of the leaderboard, and likely 10, i will always be less than leaderBoardSize and your for loop will go for a loooong time. You probably meant to say:
for (int i = 9; i >= 0; i--)
2.
scoreName[i = i + 1] = scoreName[i];
score[i = i + 1] = score[i];
This is assigning i to a new value, which will also ruin your for loop. You should only be doing
scoreName[i + 1] = scorename[i];
Trying to swap all the values in an array in cumbersome, and you are trying to do everything manually, so I give you:
The solution: use the standard library!
C++ is a great language, if for no other reason than containing a standard library: a library of functions and classes that solve many basic problems for you.
It is far easier to sort, insert and remove elements by using a standard container. Let's use std::vector:
// Simple class to handle a player score: a name and score
struct PlayerScore
{
std::string name;
unsigned int score;
};
// Create some test scores. I assume you have another means of storing high scores, perhaps in a file, but for this small purpose I am just hard-coding some scores:
std::vector<PlayerScore> hiScores = { {"ABC", 5000}, {"XJK", 10000}, {"FOO", 20000}, {"EGG", 4000}, {"HI", 50000} };
You may keep your scores sorted, but if, like mine they aren't sorted, you can sort them easily with std::sort:
std::sort(hiScores.begin(), hiScores.end(), [](PlayerScore ps1, PlayerScore ps2){ return ps1.score > ps2.score; });
With that out the way, you can proceed to play your game and obtain a name for the player and their score. I haven't bothered, and will just create a value for the score:
auto score = 10123u;
// Check if this score beats any of the current high scores:
auto it = std::find_if(hiScores.begin(), hiScores.end(), [score](PlayerScore ps){ return score > ps.score; });
if (it != hiScores.end())
{
// Yes! We beat a score!
std::cout << "Found score: " << it->score << std::endl;
// Insert this score before the other score
hiScores.insert(it, {"NewScore", score});
// Remove the last score:
hiScores.pop_back();
}
You no longer need to iterate and manually try to manipulate the positions of scores. Standard containers with random access such as std::vector allow you to just insert and access elements as you need to. Your 10 lines of code simply becomes 2 lines. std::vector also manages the size for you, so if you only have 3 high scores initially, it can grow easily to contain 10, 100 or many more scores.
std::find_if can find an element in your container without the need to manually iterate over every element. A predicate is passed in which acts as a find condition, which in our case we pass our score and check if it's greater than any PlayerScore in the container. The first element it's greater than is returned to us, and then we can insert our score in front of it, then remove the last score via pop_back
and if so, insert it into the correct position and make sure scoreName is also updated
This is a poor design. If scores and names need to stay together, you should make them a single entity. Define a struct or class to hold a name and associated score, and then store instances of that entity in a single array.
In one of the c++ books that I am reading, I came across one exercise that proposes me to do a tic-tac-toe game using both linked list and arrays. I decided to try with linked list first, since with arrays is obviously easier. However, I got stuck on how to check if someone won the game. Here's what I have so far:
struct board
{
bool square, circle, empty;
int pos;
board* next;
};
void startGame(int first, board* fullBoard);
board* getBoard(board* fullBoard);
int main()
{
int dice, first;
board* fullBoard = NULL;
cout << "Welcome to Tic-tac-toe DOS Game. (2 Player version)\n\n";
cout << "X is Player 1 and O is Player 2.\nI will decide who is starting in the first match...\n ";
srand(time(NULL));
dice = 1;//rand() % 6 + 1;
cout << dice;
if(dice <= 3)
{
first = 1;
cout << "Player 1 is the first!\n";
}
else
{
first = 2;
cout << "Player 2 is the first!\n\n";
}
system("pause");
system("cls");
startGame(first, fullBoard);
}
void startGame(int first, board* fullBoard)
{
int choice;
bool isPlaying;
for(int i = 1; i <= 9; i++)
fullBoard = getBoard(fullBoard);
bool isGameOn = true;
while(isGameOn == true)
{
board* current = fullBoard;
while(current != NULL)
{
if(current->empty == true)
cout << " " << current->pos;
else if(current->circle == true)
cout << " " << "O";
else
cout << " " << "X";
if( current->pos == 4 || current->pos == 7)
{
cout << "\n";
cout << "-----------------------\n";
}
else if (current->pos == 1)
cout << "\n";
else
cout << " |";
current = current->next;
}
if(first == 1)
{
isPlaying = true;
while(isPlaying == true)
{
cout << "Player 1, please put the number corresponding to the area you want to fill: ";
cin >> choice;
while(choice < 1 || choice > 9)
{
cout << "Invalid choice. Please choose a valid option: ";
cin >> choice;
}
current = fullBoard;
while(current != NULL && current->pos != choice)
current = current->next;
if(current->empty == true)
{
current->empty = false;
current->square = true;
isPlaying = false;
first = 2;
}
else
cout << "The field that you chose is already used...\n";
}
}
else
{
isPlaying = true;
while(isPlaying == true)
{
cout << "Player 2, please put the number corresponding to the area you want to fill: ";
cin >> choice;
while(choice < 1 || choice > 9)
{
cout << "Invalid choice. Please choose a valid option: ";
cin >> choice;
}
current = fullBoard;
while(current != NULL && current->pos != choice)
current = current->next;
if(current->empty == true)
{
current->empty = false;
current->circle = true;
isPlaying = false;
first = 1;
}
else
cout << "The field that you chose is already used...\n";
}
}
system("cls");
}
}
board* getBoard(board* fullBoard)
{
board* newBoard = new board;
newBoard->empty = true;
newBoard->circle = false;
newBoard->square = false;
newBoard->next = fullBoard;
if(newBoard->next != NULL)
newBoard->pos = newBoard->next->pos + 1;
else
newBoard->pos = 1;
return newBoard;
}
As you can see, on my struct Board, I have an int called pos, which I created to keep track of the whole board. The only solution that I can imagine so far, is checking every single position. Ex: compare pos 8 with pos 9, 7, 5 and 2, compare pos 9 with pos 8, 7, 6, 3, 5 and 1. But I think that is way too extensive (and maybe it's hard coding as well?). What other options do you think I have?
Thanks in advance,
Felipe
I need more space to explain the "multiple lists" concept.
Your board:
_ _ _
|_|_|_|
|_|_|_|
|_|_|_|
The lists that represent the possible solutions
D1 A B C D2
_ _ _
E |_|_|_|
F |_|_|_|
G |_|_|_|
Note that each cell will be in at least 2 lists.
Option 1)
You store those lists in a single "list of lists". When a move is done, you iterate that list of lists, and, for each sublist (which would be A, B, etc. from the previous figure), you iterate the cells. If all the cells in a sublist are from the player who moved, you found a winner.
Option 2)
Each cell has a member that is a "list of lists". That "list of lists" holds the lists to check when a move is done in that cell (for example, for cell 1, you would have lists A, E and D1). When a move is done in a cell, you get that list from the cell and check the sublists to see if you got a winner (it is more or less the same than option 1, but limiting the lists that you have to iterate over each time).
Note that in all the cases, we are dealing only with lists (if you add the "pointer to diagonal" and similar the structure no longer is a list). Only that:
there are many lists.
there are lists of cells, and lists of lists of cells.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have some functions that need to be called multiple times, as such
int i;
i = 10;
while (i > 0)
{
selectletter(wordArray);
computerTurn(wordArray);
printGrid(grid);
i--;
}
The function selectletter works fine, and near the end of that function, it calls another function, "claimword". Claimword runs entirely fine, but at the end of the function, the program crashes when it runs out of context, as opposed to it just moving on to computerTurn as it should as shown above. I looked up on SO how to "exit" a function, and everyone said that "return;" would work fine, even in a void function. However, when I try using return, nothing at all happens, except for anything after the return statement is ignored. Can anyone tell me why the return statement doesn't work?
void claimword(Tile grid[7][6], char letter, string wordArray[100])
{
cout << "Would you like to claim a word? (Y/N)" << endl;
char chooseinput;
cin >> chooseinput;
if ((chooseinput == 'y') || (chooseinput == 'Y'))
{
printGrid(grid);
cout << "Please enter the word you would like to claim." << endl;
string input;
cin >> input;
int inthegrid = 0;
int errormessage = 0;
compchecker(grid, input, inthegrid);
int length;
if (inthegrid = 1)
{
for(int i = 0; i < 100; ++i)
{
if (input == wordArray[i])
{
if (input.find(letter) != std::string::npos)
{
string strl;
strl = wordArray[i];
length = strl.length();
cout << "You have claimed the word " << strl << endl;
wordArray[i] = "/";
}
else
{
errormessage = 1;
}
}
else
{
///cout << "Sorry, that word is not in the dictionary." << endl;
errormessage = 2;
}
}
if (errormessage = 1)
{
cout << "Sorry you cannot claim that word." << endl;
}
if (errormessage = 2)
{
cout << "Sorry, that word is not in the dictionary." << endl;
}
if (length == 3)
{
human.humanpoints = human.humanpoints + 1;
wordsthisturn = wordsthisturn + 1;
cout << "You have earned one point!" << endl;
}
if (length == 4)
{
human.humanpoints = human.humanpoints + 2;
wordsthisturn = wordsthisturn + 2;
cout << "You have earned two points!" << endl;
}
if (length == 5)
{
human.humanpoints = human.humanpoints + 4;
wordsthisturn = wordsthisturn + 4;
cout << "You have earned four points!" << endl;
}
if (length == 6)
{
human.humanpoints = human.humanpoints + 8;
wordsthisturn = wordsthisturn + 8;
cout << "You have earned eight points!" << endl;
}
if (length == 7)
{
human.humanpoints = human.humanpoints + 16;
wordsthisturn = wordsthisturn + 16;
cout << "You have earned sixteen points!" << endl;
}
else
{
cout << "Your word was too small to claim any points." << endl;
}
}
}
else
{
cout << "End of Player Turn." << endl;
//return;
}
cout <<"Test1";
return;
cout <<"Test2";
}
Regardless of the input I give it (y/n and such), "Test1" displays, but "Test2" doesn't. My theory is that the program doesn't return all the way, or I'm just simply not using it right.
EDIT:
With an edited statement in the main function,
selectletter(wordArray);
cout << "test11";
computerTurn(wordArray);
What should happen is that the selectletter function should be called. The selectletter function, at the end of it, calls another function, claimWord. claimWord is posted above. At the end of the function, it should end. There should be nothing left for it to do, and after all those if/elses regarding points, and even if no points are scored, or anything in the function happens, the function should end. The program should then display "test11", but it does not.
EDIT2:
void selectletter(string wordArray[100])
{
cout << endl;
cout << "REMAINING LETTERS:" << endl;
cout << human.humanletters << endl;
cout << "Select a letter.";
int length;
length = human.humanletters.size();
char input;
cin >> input;
int column;
int row = 7;
int cinput;
//mght have to change since 0 is the first val
cout << "What column would you like to drop that in? (1-7)";
cin >> cinput;
column = cinput - 1;
//cout << "Test1";
while (row > 0)
{
if (grid[row-1][column].active == true)
{
row--;
//cout << "Test3";
}
else
for(int i = 0; i < length; i++)
{
if(human.humanletters[i] == input)
{
//cout << "Test5";
human.humanletters.erase(std::remove(human.humanletters.begin(), human.humanletters.end(), input), human.humanletters.end());
grid[row-1][column].letter = input;
grid[row-1][column].active = true;
cout << endl;
//cout << "Test6";
claimword(grid, input, wordArray);
//this removes ALL instances of the letter, however
}
break;
//need to add something for if the letter is not in the string
//}
//row = 9999;
}
}
}
Regardless of the input I give it (y/n and such), "Test1" displays, but "Test2" doesn't.
That is what it is supposed to do. You called return after displaying Test1 and before displaying Test2, so the latter was skipped. return is an immediate return to the function that called the current function.
Your while loop has the condition while (row > 0), and you only decrement row when (grid[row-1][column].active == true). If that ever evaluates to false, you won't decrement row and your program runs forever.
Perhaps your break; was meant to break out of the while loop, but all it will do is break out of the for loop. A break statement breaks out of the nearest enclosing loop/switch block.