2013-11-30 6 views
0

Я работаю над проектом для Научной ярмарки моей школы, в которой участвует C++. Я делаю небольшую симуляцию под названием NANORG, но эта информация на самом деле не нужна.Выполнение операции члену класса

У меня есть несколько файлов, включая main.cpp и bots.h.

У меня проблема с моей функцией moveBot(). Я полностью зациклен на том, как добавить или вычесть значение из члена; что бы я ни пытался, он просто устанавливает это число.

Пример.) Bots [botID] .y_cord = bots [botID] .y_cord - 1; сделает y_cord равным -1.

bot.h:

class Bot 
{ 
     public: 
       int id; 
       int x_cord; 
       int y_cord; 
       int energy; 
       int mutationLevel; 
       int magical; //Used for debugging 
}; 

main.cpp (moveBot находится внизу):

// NANORG SIMULATION 
// CREATED BY *INSERT NAME HERE* FOR THE SCIENCE FAIR (2013) 
// CODED IN C++ 

// MADE TO RUN ON LINUX 

#include <iostream> 
#include <string> 
#include <stdlib.h> 
#include <time.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <cstdlib> 

#include "bot.h" 

using namespace std; 

int map [39][69]; //2D array x first, then y 
int mapBot [39][69]; //If bot is there, 1. If not, 0 This array keeps track if there is a bot in a location 
signed int currentTick = 0; //Signed just in case something goes wrong and goes into the -s 
int maxTick = 1000000; //Should always stay at 1mil 
//signed int totalEnergy = 0; //For some reason, when I add this here, everything breaks. 

Bot bots[50]; 

void setupMap(); 
void tick(); 
void updateTickOutput(); 
void outputMapValue(int x, int y); 
void assignBotID(); 
void setupBot(); 
void moveBot(int botID); 
void mutateBot(int botID, int level, int sT); 
void ckLoc(int botIdent); 
void reassignLoc(int botID); 

int main() { 
    cout << "  ----------------------" << endl; 
    cout << "  NANORG Simulation V1.3.1" << endl; 
    cout << "Created in C++ by *Insert name here*" << endl; 
    cout << "  ----------------------" << endl << endl; 
     srand (time(NULL)); 
    setupMap(); 
    assignBotID(); 
    setupBot(); 
    tick(); 
// mutateBot(5, 2); //Just to test 
    cout << endl << "X before: " << bots[5].x_cord << " Y before: " << bots[5].y_cord << endl; 
    moveBot(5); 
     cout << "X after: " << bots[5].x_cord << " Y after: " << bots[5].y_cord << endl; 
    return 0; 
} 

void setupMap(){ 
// srand (time(NULL)); //Not a good idea to put it here 
    for(int i = 0; i < 40; i++){ 
     for(int j = 0; j < 70; j++){ // We add one extra (70) so it fills the entire array. Same for above 
      map[i][j] = rand() % 2 + 1; // 1==normal 2==toxic 
     } 
    } 
// outputMapValue(5,4); //Debugging purposes 
// outputMapValue(7,9); 
    cout << "Map setup - \033[0;32mSuccessful" << "\033[0m" << endl; 
} 

void outputMapValue(int x, int y){ 
    cout << "The chunk value at (" << x+1 << ", " << y+1 << ") is: "; 
    cout << map[x][y]; //Outputting the value of (x,y) 
    if(map[x][y]==1){ //If (x,y) is == 1, the chunk is fine to eat 
     cout << " | Chunk is not toxic." << endl; 
    } 
    if(map[x][y]==2){ 
     cout << " | Chunk is toxic." << endl; 
    } 
} 

void updateTickOutput() { 
     //cout << "Map Size (x,y): " << " " << mapsizeX << "," << mapsizeY << endl;  This function used to just refresh everything, including map size, which really isn't needed. 
     cout << "Current Tick: " << currentTick << " " << "Max Tick: " << maxTick << endl; //Just outputting currentTick and maxTick 
} 

void tick() { 
     while(true){ 
       if(currentTick < maxTick){ 
         currentTick = currentTick + 1; 
      if(currentTick >= 900000){ //If currentTick is over 900,000: we will begin to output individual ticks. Anything less and we get a seg fault. 
     //  updateTickOutput(); //See above 
      } 
//   cout << "tick!";  This was for debugging, before I made the updateTickOutput() function to make sure that the program actually ticked. 
       } 
       else if((currentTick = maxTick)){ 
         cout << endl << "Done!" << endl; //Report that we are finished with the simulation. 
//   assignBotID(); //Make sure every bot has the proper ID. Moved to main() 
         break; //Kill the loop 
       } 
//    updateTickOutput(); //No real need for this, anymore. 
     } 
} 

void setupBot(){ 
    srand(time(NULL)); 
    for(int botNumber=0;botNumber <= 50; botNumber++){ 
//   cout << "debug (botNumber): " << botNumber << endl; //Debug feature 
      bots[botNumber].x_cord = rand() % 39 + 1; 
//   cout << "debug (bot x cord): " << bots[botNumber].x_cord << endl; //Debug feature 
      int bufferX = bots[botNumber].x_cord; 
      bots[botNumber].y_cord = rand() % 69 + 1; 
//   cout << "debug (bot y cord): " << bots[botNumber].y_cord << endl; //Debug feature 
      int bufferY = bots[botNumber].y_cord; 
      if(mapBot[bufferX][bufferY] == 1){ 
       cout << endl <<"A bot already is here!" << endl; 
       reassignLoc(botNumber); 
      } 
      else{ 
       mapBot[bufferX][bufferY] = 1; //Take the bot's cords and make sure everyone knows that a bot is there. 
//    cout<< "debug (map location):"<<mapBot[bufferX][bufferY] << endl ; Just a nice debug feature 
      } 
     // if(botNumber==5){ 
     //  cout << "bot 5 assigned"; //I broke this entire function a while back and I used this to test if I was assigning bots correctly. 
     // } 
    } 

/* cout << endl << "X: " << bots[5].x_cord+1 << endl; //Just some debugging stuff below 
    cout << "Y: " << bots[5].y_cord+1 << endl; 
    // cout << "The value at " << mapBot[bots[5].x_cord]<<","<< mapBot[bots[5].y_cord]<<" is: " << mapBot[bots[5].x_cord][bots[5].y_cord]; //This is a very messed up debug feature, but it still works. 

     cout << endl << "X: " << bots[6].x_cord+1 << endl; 
     cout << "Y: " << bots[6].y_cord+1 << endl; 
    cout << mapBot[6][6]; 
*/ 
    cout << "Bot setup - \033[0;32mSuccessful" << "\033[0m" << endl; 
} 

void assignBotID(){ 
    int botNumber = 0; 
    string botName = "Bot"; 
    string finalName; 

    string buffer; 

    while(botNumber <50){ 
     if(botNumber < 50){ 
      botNumber = botNumber + 1; 
      buffer = to_string(botNumber); 
      finalName = botName + buffer; 
      //finalName.id = botNumber; A very very broken line. 
      bots[botNumber].id = botNumber; 
//   cout << finalName << ":"<< bots[botNumber].id << endl; A super awesome debugging output to make sure the bot's id is correct 
     } 
     else if((botNumber = 51)){ //Redundancy :) 
      break; 
     } 
    } 
} 

void mutateBot(int botID, int level, int sT){ 
    if(sT=2){ 
     bots[botID].mutationLevel = bots[botID].mutationLevel + level; 
    } 
    else if(sT=1){ 
     bots[botID].mutationLevel = bots[botID].mutationLevel - level; 
    } 
// cout << botID << ":" << bots[botID].mutationLevel << endl; //Just a quick debugging feature to make sure it worked 
} 

void ckLoc(int botIdent){ 
    int bufferX; 
    int bufferY; 
    bufferX = bots[botIdent].x_cord; //Just set the buffers. Uses a bit more memory, but that is okay. 
    bufferY = bots[botIdent].y_cord; 
// cout << bufferX << endl << bufferY; 
    if(mapBot[bufferX][bufferY] ==1){ 
     cout << "Bot lives here!"; 
     reassignLoc(botIdent); 
    } 
} 

void reassignLoc(int botID){ 
    bots[botID].x_cord = rand() % 39 + 1; 
    bots[botID].y_cord = rand() % 69 + 1; 
    ckLoc(botID); 
} 

void moveBot(int botID){ 
    int direction = 0; 
    direction = rand() % 4 + 1; 
    if(direction == 1){ //NORTH 
     if(bots[botID].y_cord=0){ 
      //cout << "error moving bot - N "; 
      moveBot(botID); 
     } 
     else{ 
      //cout << "BufferY: " << bufferY; 
      bots[botID].y_cord - 1; 
     } 
    } 
    else if(direction == 2){ //EAST 
     if(bots[botID].x_cord = 39){ 
      //cout << "error moving bot - E"; 
      moveBot(botID); 
     } 
     else{ 
      bots[botID].x_cord + 1; 
     } 
    } 
     else if(direction == 3){ //SOUTH 
       if(bots[botID].y_cord = 69){ 
         //cout << "error moving bot - S "; 
         moveBot(botID); 
       } 
       else{ 
         bots[botID].y_cord + 1; 
       } 
     } 
     else if(direction == 4){ //WEST 
       if(bots[botID].x_cord = 0){ 
         //cout << "error moving bot - W"; 
         moveBot(botID); 
       } 
       else{ 
         bots[botID].x_cord = bots[botID].x_cord - 1; 
       } 
     } 
// cout << endl << "Direction: " << direction << endl; //Debug 
} 

Кроме того, я отдаю себе отчет в петлях в то время. Я должен очистить все, прежде чем я передаю проект в.

+0

Ответ simonc верен, но код в вашем примере перед фрагментом кода 'bots [botID] .y_cord = bots [botID] .y_cord - 1;' также технически корректен. Возможно, вы видели, потому что y_cord на самом деле 0, поэтому вычитание 1 сделало значение -1. – mattp

ответ

2

Все строки формы

if(bots[botID].y_cord=0) 

назначаете bots[botID].y_cord. Вы должны использовать == для проверки равенства

if(bots[botID].y_cord==0) 
//     ^

Кроме того, строки вида

bots[botID].x_cord + 1; 

должен быть

bots[botID].x_cord += 1; 

, если вы хотите, чтобы повлиять на стоимость bots[botID].x_cord

+0

Ничего себе. Не могу поверить, что я это сделал. Это второй раз, когда я перепутал с равными знаками. –

0

Я предлагаю вам использовать инструкцию switch вместо лестница if-else-if.

switch (direction) 
{ 
    case 1: 
    // do stuff 
    break; 
    case 2: 
    // do stuff 
    break; 
    // etc. 
} 

Для вашей программы он будет выглядеть более читабельным и иметь меньше шансов на ошибки.

Смежные вопросы