I have this program that is supposed to simulate fish and sharks moving around on a grid of any given size, but I'm running into an infinite loop in my fish's move function.
the program isn't consistent on when the looping occurs because when I run it sometimes it gets stuck on turn 0, but it could also happen on turn 3; this is possible because of my randomness attached to it
here's my fish_class.cpp where the problem occurs, I've marked where the infinite loop happens. hope anyone could help.
#include "fish_class.h"
#include "world.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
void FishT::SetFishBreed(int fishBreedRate)
{
fishBreed = fishBreedRate;
//return fishBreed;
}
int FishT::GetFishBreed()
{
return fishBreed;
}
int FishT::IncreaseMoves()
{
if (moveCount == fishBreed) //just incase for unlimited breeding
{
moveCount = 0;
}
moveCount++;
return moveCount;
}
void FishT::Move(WorldT& world)
{
bool HasMoved = false;
srand (time (NULL)); //initialize random seed
//generate a number from 1 to 4 (north, south, east, west) to move to on the world grid
int PlaceToMove = static_cast<int>(rand() % 4 + 1);
while (HasMoved == false)
{
if (PlaceToMove == 1 and world.IsInBoundry(x, y - 1) and world.IsEmpty(x, y - 1)) //checking if north is empty and in bounds
{
//cout << "moving fish north" << endl;
//update fish's position
world.SetEmpty(x, y);
world.SetFishPlacement(x, y - 1);
y = y - 1;
HasMoved = true;
Turn(world); //increase our move tracker
}
else if (PlaceToMove == 2 and world.IsInBoundry(x, y + 1) and world.IsEmpty(x, y + 1)) //checking if south is empty and in bounds
{
//cout << "moving fish south" << endl;
//update fish's position
world.SetEmpty(x, y);
world.SetFishPlacement(x, y + 1);
y = y + 1;
HasMoved = true;
Turn(world);
}
else if (PlaceToMove == 3 and world.IsInBoundry(x + 1, y) and world.IsEmpty(x + 1, y)) //checking if east is empty
{
//cout << "moving fish east" << endl;
//update fish's position
world.SetEmpty(x, y);
world.SetFishPlacement(x + 1, y);
x = x + 1;
HasMoved = true;
Turn(world);
}
else if (PlaceToMove == 4 and world.IsInBoundry(x - 1, y) and world.IsEmpty(x - 1, y)) //checking if west is empty
{
//cout << "moving fish west" << endl;
//update fish's position
world.SetEmpty(x, y);
world.SetFishPlacement(x - 1, y);
x = x - 1;
HasMoved = true;
Turn(world);
}
else
{
// *** this is where the loop problem occurs ***
//cout << "updating fish's placetomove" << endl;
PlaceToMove = PlaceToMove % 4 + 1;
}
}
if (PlaceToMove == 1 and moveCount == fishBreed)
{
//cout << "in reproduce north" << endl;
//cout << "fish breed is: " << GetFishBreed() << endl;
//cout << "move count is: " << moveCount << endl;
Reproduce(x, y + 1, world);
}
else if (PlaceToMove == 2 and moveCount == fishBreed)
{
//cout << "in reproduce south" << endl;
//cout << "fish breed is: " << GetFishBreed() << endl;
//cout << "move count is: " << moveCount << endl;
Reproduce(x, y - 1, world);
}
else if (PlaceToMove == 3 and moveCount == fishBreed)
{
//cout << "in reproduce east" << endl;
//cout << "fish breed is: " << GetFishBreed() << endl;
//cout << "move count is: " << moveCount << endl;
Reproduce(x - 1, y, world);
}
else if (PlaceToMove == 4 and moveCount == fishBreed)
{
//cout << "in reproduce west" << endl;
//cout << "fish breed is: " << GetFishBreed() << endl;
//cout << "move count is: " << moveCount << endl;
Reproduce(x + 1, y, world);
}
}
void FishT::Reproduce(int x, int y, WorldT& world)
{
//cout << "in reproduce function" << endl;
world.SetFishPlacement(x, y);
world.AddNewFish(x, y);
}
void FishT::Turn(WorldT& world)
{
IncreaseMoves(); //keep track of move turns
}
void FishT::Die(WorldT& world)
{
world.FishDie(x, y);
}
Related
Could anyone tell me what is wrong with my code:
int Partition(vector<string>& userIDs, int i, int k) {
int pivot = (i + (k - i) / 2);
string temp;
while(i<k) {
cout << "pivot:" << pivot << endl;
while (userIDs.at(i).compare(userIDs.at(pivot))<0) {
cout << "1. i:"<<i<<" UserIDs.at(i):" << userIDs.at(i) << " UserID.at(pivot): " << userIDs.at(pivot) << endl;
i += 1;
}
while (userIDs.at(pivot).compare(userIDs.at(k))<0) {
cout << "2. k:" << k << " UserIDs.at(k):" << userIDs.at(k) << " UserID.at(pivot): " << userIDs.at(pivot) << endl;
k -= 1;
}
if(i<k){
cout << "3. i:" << i << " k:"<<k<<" UserIDs.at(i):" << userIDs.at(i) << " UserID.at(k) : " << userIDs.at(k) << endl;
temp = userIDs.at(i);
userIDs.at(i) = userIDs.at(k);
userIDs.at(k) = temp;
i++;
k--;
}
cout << "4. i:" << i << " k:" << k << endl;
}
cout << " 5. k:" << k << endl;
return k;
}
void Quicksort(vector<string>& userIDs, int i, int k) {
cout << "Quicksort i:" << i << " k:" << k << endl;
if (i >= k) {
return;
}
int lowEndIndex = Partition(userIDs, i, k);
cout << "Quicksort lowEndIndex:" << lowEndIndex << endl;
Quicksort(userIDs, i, lowEndIndex);
Quicksort(userIDs, lowEndIndex+1, k);
}
When I input this list:
BigBen
GardenHeart
GreyMare
TeenPunch
WhiteSand
LifeRacer
Doom
AlienBrain
I get:
AlienBrain
BigBen
GreyMare
GardenHeart
Doom
LifeRacer
TeenPunch
WhiteSand
Why is Doom not in the correct place?
#include <bits/stdc++.h>
using namespace std;
int Partition(vector<string>& userIDs, int i, int k) {
int pivot = i;
string pivotValue = userIDs[pivot];
string temp;
int leftIndex = i;
int rightIndex = k;
while(i<k) {
while (userIDs[i].compare(pivotValue)<=0) {
i++;
if(i >= rightIndex) break;
}
while (pivotValue.compare(userIDs[k])<=0) {;
k--;
if(k <= leftIndex) break;
}
if(i<k){
temp = userIDs[i];
userIDs[i] = userIDs[k];
userIDs[k] = temp;
}
}
// swap
userIDs[pivot] = userIDs[k];
userIDs[k] = pivotValue;
return k;
}
void Quicksort(vector<string>& userIDs, int i, int k) {
if (i >= k) {
return;
}
int lowEndIndex = Partition(userIDs, i, k);
Quicksort(userIDs, i, lowEndIndex - 1);
Quicksort(userIDs, lowEndIndex + 1, k);
}
int main() {
vector<string> userIDs = {"BigBen", "GardenHeart", "GreyMare", "TeenPunch",
"WhiteSand", "LifeRacer", "Doom", "AlienBrain" };
Quicksort(userIDs, 0, userIDs.size() - 1);
for(auto& c: userIDs) cout << c << " ";
cout << endl;
return 0;
}
Fixed the code and tested. Now it works. What were the problems?
As far as I noticed, firstly you didn't put break() statements within the while loops in case i or k exceeds the boundaries of the vector. I've changed the pivot from middle element to first element, but it's just my preference, you can implement the quicksort algorithm with your pivot in the middle, not a big deal. I've called first Quicksort() with lowEndIndex - 1 rather than lowEndIndex. I've used [] operator rather than at(), but again it's my preference. I guess the main problems were that break stuff and calling the quicksort method with lowEndIndex rather than lowEndIndex - 1.
Output:
AlienBrain BigBen Doom GardenHeart GreyMare LifeRacer TeenPunch WhiteSand
So I am making a textbased RPG and I wanted to have multiple enemy encounter at once. So I modified my function that determines whether an object of the class Monster, to fill in the Monster(s) into an array of the class monster and set the objects bool to true, as you can see here:
Monster * Map::checkRandomEncounter()
{
Monster* monster = new Monster[3];
for (int i = 0; i < 3; i++)
{
int roll = Random(0, 20);
if (roll <= 5)
{
//No encounter
return 0;
}
else if (roll > 6 && roll < 10)
{
monster[i] = Monster();
monster[i].giveID("Orc", 10, 8, 200, 100, 1, "Short Sword", 2, 7);
monster[i].isFilled();
std::cout << "You encounter an Orc!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
else if (roll >= 11 && roll <= 15)
{
monster[i] = Monster();
monster[i].giveID("Goblin", 6, 6, 100, 75, 0, "Dagger", 1, 5);
monster[i].isFilled();
std::cout << "You encounter a Goblin!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
else if (roll >= 16 && roll <= 19)
{
monster[i] = Monster();
monster[i].giveID("Ogre", 20, 12, 500, 200, 2, "Club", 3, 8);
monster[i].isFilled();
std::cout << "You encounter an Ogre!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
else if (roll == 20)
{
monster[i] = Monster();
monster[i].giveID("Orc Lord",
25,
15,
2000,
1000,
5,
"Two Handed Sword",
5,
20);
monster[i].isFilled();
std::cout << "You encounter an Orc Lord!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
}
return monster;
}
The function above will be called in my main function, which looks like this:
int main()
{
srand(time(0));
Map gameMap;
Player mainPlayer;
mainPlayer.createClass();
//Beginn adventure
bool done = false;
while (done == false)
{
// Each Loop Cycle outputs player pos and selection menu
gameMap.printPlayerPos();
int selection = 1;
std::cout << "1) Move 2) Rest 3) View Stats 4) Quit: ";
std::cin >> selection;
Monster* monster = 0;
switch (selection)
{
case 1: // Move the player
gameMap.movePlayer();
if (gameMap.getPlayerXPos() == 2
&& gameMap.getPlayerYPos() == 3)
{
std::cout << "You see a store nearby !" << std::endl;
}
if (gameMap.getPlayerXPos() == 2
&& gameMap.getPlayerYPos() == 4)
{
Store store;
store.enter();
store.showInventory(mainPlayer);
}
//Check for a random encounter
//returns a null pointer if no encounter happened
monster = gameMap.checkRandomEncounter();
//'monster' not null, start battle script
if (monster != 0)
{
//Loop until a break statement
for (int i = 0; i < 3; i++)
{
//Display Hitpoints
mainPlayer.displayHitPoints();
monster[i].displayHitPoints();
std::cout << std::endl;
//Players turn to attack first
**bool runAway = mainPlayer.attack(monster, mainPlayer);** // Crash happening in this area
if (runAway) // Player flees
{
break;
}
if (monster[i].isDead())
{
mainPlayer.victory(monster->getXPReward(),
monster->getGoldReward());
mainPlayer.levelUp(mainPlayer);
}
break;
//Monster attacks
monster[i].attack(mainPlayer);
if (mainPlayer.isDead())
{
mainPlayer.gameOver();
done = true;
break;
}
}
//Pointer to Monster must destroy created instance of Monster
//to make sure that there is no Memory leak
}
delete monster;
monster = 0;
break;
case 2: // resting
mainPlayer.rest();
monster = gameMap.checkRandomEncounter();
//'monster' not null, start battle script
monster = gameMap.checkRandomEncounter();
//'monster' not null, start battle script
if (monster != 0)
{
//Loop until a break statement
for (int i = 0; i < 3; i++)
{
//Display Hitpoints
mainPlayer.displayHitPoints();
monster[i].displayHitPoints();
std::cout << std::endl;
//Players turn to attack first
bool runAway = mainPlayer.attack(monster, mainPlayer);
if (runAway) // Player flees
{
break;
}
if (monster[i].isDead())
{
mainPlayer.victory(monster->getXPReward(),
monster->getGoldReward());
mainPlayer.levelUp(mainPlayer);
}
break;
//Monster attacks
monster[i].attack(mainPlayer);
if (mainPlayer.isDead())
{
mainPlayer.gameOver();
done = true;
break;
}
}
//Pointer to Monster must destroy created instance of Monster
//to make sure that there is no Memory leak
}
delete monster;
monster = 0;
break;
case 3: // viewing stats
mainPlayer.viewStats();
break;
case 4: // quitting
done = true;
break;
}
}
return 0;
}
and finally the last puzzle piece, the function where the player attacks the Monster(s):
bool Player::attack(Monster Monster[], Player& Player)
{
int ArmorBefore = 0;
int Roll = 0;
int selection = 1;
int i;
if (Monster[0].isFilled() == true)
{
i = 0;
}
else if (Monster[1].isFilled() == true)
{
i = 1;
}
else if (Monster[2].isFilled() == true)
{
i = 2;
}
if (Monster[i].isFilled() == true)
{
std::cout << "1) Attack 2) Run 3) Cast Spell 4) Use Item: ";
std::cin >> selection;
std::cout << std::endl;
switch (selection)
{
case 1: // Player fights
std::cout << " You attack an " << Monster[i].getName()
<< " with a " << mWeapon.mName << std::endl;
if (Random(0, 20) < mAccuracy) // Player hits Monster
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - Monster[i].getArmor();
if (totalDamage <= 0) // Armor is equal or higher than player atk
{
std::cout << "Your attack failed to penetrate "
<< Monster[i].getName() << "'s armor !"
<< std::endl;
return false;
}
else // Attack is higher than Monsters armor
{
std::cout << "You hit " << Monster[i].getName()
<< " for " << totalDamage << " damage !"
<< std::endl;
// Subtract dmg from Monsters hp
Monster[i].takeDamage(totalDamage);
return false;
}
}
else // Player Misses
{
std::cout << "You miss !" << std::endl;
}
std::cout << std::endl;
return false;
break;
case 2: // Player runs with a 25% chance
Roll = Random(1, 4);
if (Roll == 1) // Success
{
std::cout << "You run away !" << std::endl;
return true; // <- Return out of the function
}
else
{
std::cout << "You failed to escape !" << std::endl;
return false;
}
case 3: // Casting Spell
{
int SpellSelect;
// Spells for the Fighter
if (Player.mClassName == "Fighter")
{
std::cout << std::endl;
std::cout << "1) Shield 2) Mighty Blow: ";
std::cin >> SpellSelect;
if (SpellSelect == 1)
{
if (Player.mMagicPoints >= 10) // checks for player mana
{
std::cout << "You cast a mighty shield!"
<< std::endl;
ArmorBefore = Player.mArmor;
Player.shield(Player);
Player.mMagicPoints -= 10;
}
else
{
std::cout << "Not enough Mana" << std::endl;
break;
}
}
else
{
if (Player.mMagicPoints >= 5) // casting Mighty Blow
{
int damage = Random(mMightyBlow.mDamageRange);
std::cout
<< "You strike with all your might ! and Deal "
<< damage << " damage !" << std::endl;
Monster[i].takeDamage(damage);
Player.mMagicPoints -= 5;
return false;
}
else
{
std::cout << "Not enough Mana" << std::endl;
return false;
}
}
}
//Spells for the Wizard
else if (Player.mClassName == "Wizard")
{
std::cout << "1) Fireball";
std::cin >> SpellSelect;
if (Player.mMagicPoints >= 45)
{
int damage = Random(mFireball.mDamageRange);
std::cout << "You cast a Fireball and deal " << damage
<< " damage !" << std::endl;
Monster[i].takeDamage(damage);
Player.mMagicPoints -= 45;
return false;
}
else
{
std::cout << "Not enough Mana" << std::endl;
return false;
}
}
// Spells for the Cleric
else if (Player.mClassName == "Cleric")
{
std::cout << "1) Magic Missile";
std::cin >> SpellSelect;
if (Player.mMagicPoints >= 35)
{
int damage = Random(mMagicMissile.mDamageRange);
std::cout << "You cast a Magic Missile and deal "
<< damage << " damage !" << std::endl;
Monster[i].takeDamage(damage);
Player.mMagicPoints -= 35;
}
else
{
std::cout << "Not enough Mana" << std::endl;
return false;
}
}
}
case 4: // using Item
int invSlot;
std::cout << "1) HP Potion: ";
std::cin >> invSlot;
if (invSlot == 1) // Potion slot
{
if (mHPot.mAmount.size() > 0)
{
std::cout << "You used a Potion and healed for 5 HP !"
<< std::endl;
int currentSize = mHPot.mAmount.size();
mHPot.mAmount.resize(currentSize - 1);
Player.mHitPoints += 5;
if (Player.mHitPoints > Player.mMaxHitPoints)
{
Player.mHitPoints = Player.mMaxHitPoints;
}
return false;
}
else
{
std::cout << "You have no Potions!" << std::endl;
return false;
}
}
else // wrong slot
{
std::cout << "No Item found!" << std::endl;
return false;
}
}
// Clearing stat boosts
if (Player.shield(Player) == true)
{
Player.mArmor = ArmorBefore;
}
}
return false;
}
When I run the game, I sometimes have the problem, that after filling in a Monster in a slot of the array, no battle will be triggered. And if a battle will be triggered, I get a crash with an error report every time, which says:
_CrtlValidHeadPointer(block)
I guess that something with my pointer is not functioning well.... but since I am a beginner I am pretty much stuck. I would be very grateful for some enlightenment :)
This place can potentially call undefined behavior and crash:
int i;
if (Monster[0].isFilled() == true)
{
i = 0;
}
else if (Monster[1].isFilled() == true)
{
i = 1;
}
else if (Monster[2].isFilled() == true)
{
i = 2;
}
/*else // one of solutions
break;*/
//"i" can be unset! and can have any value from INT_MIN to INT_MAX!
if (Monster[i].isFilled() == true) //potentially index over array
{
Also there are memory leaks and undefined behavior with memory management:
Monster* monster = new Monster[3];
...
delete monster
must be delete [] monster
but it is recommended to use smart pointers, vector, array, etc, for memory management
I am trying to return integer from the following method in c++:
int check_for_chef(string str1,string str2,int M,int N)
{
if ( N == -1 )
{
cout << "I am returning 1." <<endl;
return 1;
}
else if ( N > M )
{
cout << " I am returning 0." <<endl;
return 0;
}
else
{
if ( str1[M] == str2[N])
{
location[N] = M;
cout << "location is: "<<location[N]<<endl;
check_for_chef(str1,str2,M - 1, N - 1);
}
else
{
check_for_chef(str1,str2,M - 1, N);
}
}
}
But, what I am getting while returning is :
Returned value is: 35668224
Whole code is here:
#include <iostream>
#include <string>
using namespace std;
int location[4];
int check_for_chef(string str1,string str2,int M,int N)
{
if ( N == -1 )
{
cout << "I am returning 1." <<endl;
return 1;
}
else if ( N > M )
{
cout << " I am returning 0." <<endl;
return 0;
}
else
{
if ( str1[M] == str2[N])
{
location[N] = M;
cout << "location is: "<<location[N]<<endl;
check_for_chef(str1,str2,M - 1, N - 1);
}
else
{
check_for_chef(str1,str2,M - 1, N);
}
}
}
int main()
{
int count = 0;
string original_string;
cin >> original_string;
string chef = "CHEF";
int M = original_string.size();
int N = 4;
while ( 1 )
{
cout << "Returned value is: " << check_for_chef(original_string,chef,M - 1, N - 1);
cout << " i am in while."<<endl;
count++;
original_string.erase(location[3],1);
cout << "the original_string : " << original_string <<endl;
original_string.erase(location[2],1);
cout << "the original_string : " << original_string <<endl;
original_string.erase(location[1],1);
cout << "the original_string : " << original_string <<endl;
original_string.erase(location[0],1);
cout << "the original_string : " << original_string <<endl;
cout << "the original_string : " << original_string <<endl;
M = original_string.size();
cout << "size is :" << M <<endl;
if ( M < N )
break;
}
cout << count <<endl;
}
Please help me to solve this problem.
I don't see two more return in the code
I have added in the commented lines below:
int check_for_chef(string str1,string str2,int M,int N)
{
if ( N == -1 )
{
cout << "I am returning 1." <<endl;
return 1;
}
else if ( N > M )
{
cout << " I am returning 0." <<endl;
return 0;
}
else
{
if ( str1[M] == str2[N])
{
location[N] = M;
cout << "location is: "<<location[N]<<endl;
return check_for_chef(str1,str2,M - 1, N - 1); // here 1st RETURN
}
else
{
return check_for_chef(str1,str2,M - 1, N); // here 2nd RETURN
}
}
}
Your code does not return anything expicitly in the else branch.
Values in x84 usually are returned via EAX register, so if you do not return anything - it behaves like an uninitialized variable.
So the problem I'm having is this: When a win condition is met the program should stop the while loop and just display the win/lose/draw message, but instead it allows the X and O of the game to take one more turn and I'm rather at a loss as to why. Any help would be greatly appreciated.
#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
#include <ctime>
const int yCoordMax = 6;
const int xCoordMax = 2;
int xCoord;
int yCoord;
int square = 0;
const char PLAYER1 = 'X';
const char COMPUTER = 'O';
const int MAXTURN = 9;
char playerChar ; //the current turn's player's symbol
const std::string WIN = "You won! How nice.\n";
const std::string LOSE = "You lost.\n";
const std::string DRAW = "It's a draw.\n";
const std::string PLAY = "You will be the X's against the computer O's\n\n";
const std::string INSTRUCTIONS = "Enter the number of the square you wish to mark\nwith 1 being top left and 9 being bottom right.\n\n";
const std::string INVALIDSQUARE = "Please enter a correct square number between 1 and 9.\n";
const std::string SQUAREISFULL = "That square is already marked. Choose another.\n";
bool gameOver = false;
bool isGameDraw = false;
char boardChoices[3][3] = {{'1', '2', '3'},{'4', '5', '6'},{'7', '8', '9'}};
void drawBoard(void);
void playGame(void);
bool checkForWinner(void);
void isMoveValid(void);
int main()
{
std::srand(time(0)); //sets the seed for computer only once
std::cout << PLAY;
std::cout << INSTRUCTIONS;
playerChar = PLAYER1;
while(!gameOver)
{
drawBoard();
playGame();
isMoveValid();
gameOver = checkForWinner();
}
if (playerChar == 'O' && !isGameDraw)
{
drawBoard();
std::cout << std::endl << std::endl << "Player 1 [X] Wins! Game Over!\n";
}
else if (playerChar == 'X' && !isGameDraw)
{
drawBoard();
std::cout << std::endl << std::endl << "Player 2 [O] Wins! Game Over!\n";
}
else
{
drawBoard();
std::cout << std::endl << std::endl << "It's a draw! Game Over!\n";
}
return 0;
}
void drawBoard()
{
std::cout << std::endl << std::endl << "gameover says " << gameOver << std::endl;
std::cout << "+----" << "+----+" << "----+" << std::endl; // 0
std::cout << "| " << boardChoices[0][0] << " " << "| " << boardChoices[0][1] << " |" << " " << boardChoices[0][2] << " |" << std::endl; // 1 input here only [1][0], [1][1], [1][2]
std::cout << "+----" << "+----+" << "----+" << std::endl; // 2
std::cout << "| " << boardChoices[1][0] << " " << "| " << boardChoices[1][1] << " |" << " " << boardChoices[1][2] << " |" << std::endl; // 3 input here only [3][0], [3][1], [3][2]
std::cout << "+----" << "+----+" << "----+" << std::endl; // 4
std::cout << "| " << boardChoices[2][0] << " " << "| " << boardChoices[2][1] << " |" << " " << boardChoices[2][2] << " |" << std::endl; // 5 input here only [5][0], [5][1], [5][2]
std::cout << "+----" << "+----+" << "----+" << std::endl;
}
void playGame()
{
std::cout << std::endl;
if(playerChar == PLAYER1)
{
std::cout << "X's turn :: ";
std::cin >> square;
}
else if(playerChar == COMPUTER)
{
square = rand() % 9 + 1;
std::cout << "O's turn:: " << square << std::endl << std::endl;
}
if (square == 1)
{yCoord = 0;
xCoord = 0;}
if (square == 2)
{yCoord = 0;
xCoord = 1;}
if (square == 3)
{yCoord = 0;
xCoord = 2;}
if (square == 4)
{yCoord = 1;
xCoord = 0;}
if (square == 5)
{yCoord = 1;
xCoord = 1;}
if (square == 6)
{yCoord = 1;
xCoord = 2;}
if (square == 7)
{yCoord = 2;
xCoord = 0;}
if (square == 8)
{yCoord = 2;
xCoord = 1;}
if (square == 9)
{yCoord = 2;
xCoord = 2;}
}
void isMoveValid()
{
if(playerChar == PLAYER1 && boardChoices[yCoord][xCoord] != PLAYER1 && boardChoices[yCoord][xCoord] != COMPUTER)
{
boardChoices[yCoord][xCoord] = playerChar;
playerChar = COMPUTER;
}
else if(playerChar == COMPUTER && boardChoices[yCoord][xCoord] != PLAYER1 && boardChoices[yCoord][xCoord] != COMPUTER)
{
boardChoices[yCoord][xCoord] = COMPUTER;
playerChar = PLAYER1;
}
else
{
if(playerChar == PLAYER1)
std::cout << SQUAREISFULL;
}
}
bool checkForWinner()
{
std::string victoryOrDefeat;
if(playerChar == COMPUTER)
{
victoryOrDefeat = LOSE;
}
else if(playerChar == PLAYER1)
{
victoryOrDefeat = WIN;
}
if(boardChoices[0][0] == playerChar && boardChoices[0][1] == playerChar && boardChoices[0][2] == playerChar) // Horizontal
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[1][0] == playerChar && boardChoices[1][1] == playerChar && boardChoices[1][2] == playerChar) // Horizontal
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[2][0] == playerChar && boardChoices[2][1] == playerChar && boardChoices[2][2] == playerChar) // Horizontal
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[0][0] == playerChar && boardChoices[1][0] == playerChar && boardChoices[2][0] == playerChar) // Vertical
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[0][1] == playerChar && boardChoices[1][1] == playerChar && boardChoices[2][1] == playerChar) // Vertical
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[0][2] == playerChar && boardChoices[1][2] == playerChar && boardChoices[2][2] == playerChar) // Vertical
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[0][0] == playerChar && boardChoices[1][1] == playerChar && boardChoices[2][2] == playerChar) // Diagonal
{std::cout << victoryOrDefeat;
return true;}
if(boardChoices[0][2] == playerChar && boardChoices[1][1] == playerChar && boardChoices[2][0] == playerChar) // Diagonal
{std::cout << victoryOrDefeat;
return true;}
for (int i = 0; i < 3; i++)//Check for draw
{
for (int j = 0; j < 3; j++)
{
if (boardChoices[i][j] != 'X' && boardChoices[i][j] != 'O')
{
return false;
}
}
}
isGameDraw = true;
return true;
}
I have got it..You are changing playerChar after each isMoveValid() check as a result when you should be checking with X you are checking with O..simple do this change after checking the winner..that will give correct result.
Initially when player1 gives X position you are checking the win move for giving O and in later cases too this happens.. That's why it's getting the error.
I'm trying to return a value from a function but all it return is the value 1.
It's suppose to have 5 arguments in the computeCivIndex(), even if I hard coded the values the output I receive would still be 1.
Why is this so ?
float LocationData::computeCivIndex()
{
civNum1 = 45.0 / 100;
civNum2 = 20 + 50;
civNum3 = civNum2 / 200;
civNum4 = civNum1 - civNum3;
civNum5 = 5 + 10;
return civNum;
}
//display data
void LocationData::displaydata()
{
cout << "CIV value: " << computeCivIndex << endl;
}
You miss () in cout << "CIV value: " << computeCivIndex() << endl;.
For importance of braces you can check this link.
cout << "CIV value: " << computeCivIndex << endl;
seems to be printing the value of the function (not the return value). You need to put the function brackets in:
cout << "CIV value: " << computeCivIndex() << endl;
//convert sunType to sunTypePercentage
float LocationData::computeCivIndex(string st, int earth, int moons, float particle, float plasma)
{
float sunTypePercent;
if(st == "Type 0")
{
sunTypePercent = 80.0;
}
else if(st == "Type B")
{
sunTypePercent = 45.0;
}
else if(st == "Type A")
{
sunTypePercent = 60.0;
}
else if(st == "Type F")
{
sunTypePercent = 75.0;
}
else if(st == "Type G")
{
sunTypePercent = 90.0;
}
else if(st == "Type K")
{
sunTypePercent = 80.0;
}
else if(st == "Type M")
{
sunTypePercent = 70.0;
}
// calculate CIV Value
float civNum,civNum1,civNum2,civNum3,civNum4,civNum5;
civNum1 = sunTypePercent / 100;
civNum2 = plasma + particle;
civNum3 = civNum2 / 200;
civNum4 = civNum1 - civNum3;
civNum5 = earth + moons;
civNum = civNum4 * civNum5;
return civNum;
}
//display data
void LocationData::displaydata()
{
cout << "suntype: " << sunType << endl;
cout << "earth: " << noOfEarthLikePlanets << endl;
cout << "moons: " << noOfEarthLikeMoons << endl;
cout << "particle: " << aveParticulateDensity << endl;
cout <<"density: " << avePlasmaDensity << endl;
cout << "CIV value: " << computeCivIndex()<< endl;
}
This is the actual code which i'm having problem with. For the computeCivIndex() function it is actually a static under the public LocationData class in my LocationData.h file which look something like this.
static float compute CivIndex(string st, int earth, int moons, float particle, float plasma);
so in order to retrieve the value from the function should I do this instead?
cout << "CIV value: " << LocationData.computeCivIndex() << endl;