Click here to Skip to main content
14,733,890 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i was trying to run my code but it isn't working at all and so much error


#include <iostream>
#include <stack>
#include <list>
#include <queue>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <vector>
#include"state.h"
using namespace std;

int main(){
   srand(time(0));
   Game game;
   game.getIntBoard();
   game.playGame();


   return 0;
}
<pre>#ifndef STATE_H_INCLUDED
#define STATE_H_INCLUDED
using namespace std;

const int MAX_BOARD_INDEX = 2;
const int MAX_STATES = 100;
const int BOARDSIZE = 3;
const int NUM_OF_BLOCKS = 6;

class Action{
private:
int source;
int destination;
int heuristic;

public:
    Action(){};
    Action(int s,int d):source(s),destination(d){};

    bool operator < (const Action a) const{
    if(heuristic < a.heuristic){
        return true;
        }else{
            return false;
            }
    }
    bool operator==(const Action a)const{
    if(source==a.source){
        return true;
        }else{
            return false;
            }
    }

    int getHeuristic(){return heuristic;}

    void setHeuristic(int h){heuristic = h;}

    void printAction()const{
    cout << "(" << source << "," << destination << ")" << endl;
    }

    void printActionInfo()const{
    cout << "(" << source << "," << destination << "),H:" << heuristic << endl;
    }

    void setAction(int s, int d){source = s; destination = d;}

    int getSource(){
    return source;
    }

    int getDestination(){
    return destination;
    }
};

class Board:public State{

private:
    vector<int>blocks;

public:
    void generateIntlState() {
        int bIndex = 0;
        intializeBlocks();

    for(int r = 0; r < BOARDSIZE; r++){
        for(int c = 0; c < BOARDSIZE; c++){
            setVal(r,c blocks[bIndex]);
            bIndex ++;
        }
    }
    pushBlockDown();

    void intializeBlocks(){
    int zeroCount = 1;

    for (int i = 1; i < 9; i ++){
        blocks.push_back(i);
        if(zeroCount<=3){
            blocks.push_back(0);
            }
            zeroCount++;
        }
    for( int i = 8; i > 0; i--){
        int num=rand()% i;
        int temp = blocks[i];
        blocks[i] = blocks[num];
        blocks[num] = temp;
        }
}

    void findActHeuristic(priority_queue<Action>&actions, Goal g){
    Action a;
    vector<Action>actions_vec;
    vector<State> states;
    int h = 0;

    for(int r = 0; r < BOARDSIZE; r++){
        for(int c = 0; c < BOARDSIZE; c++){
          if((r != c)&&(isFull(r))&&(isEmptu(c))){
            a.setAction(r,c);
            actions_vec.push_back(a);
            }
        }
    }
    for(int i = 0; i <actions_vec.size(); i++){
        State newState = nextState(actions_vec[i]);
        states.push_back(newState);
        if(newState.getVal(g.getRow(),g.getColumn()) == g.getVal()){
            h = 100;
        }else if(newState.isOnTop(g.getVal())&&(newState.isColumnEmpty(g.getColumn()))){
            h = 95;
        }else if(newState.isOnTop(g.getVal())&&(newState.isBlockEmpty(g.getColumn()))){
            h = 85;
        }else if(newState.isBlockEmpty(g.getRow(),g.getColumn())){
            h = 65;
        }else if(newState.isColumnEmpty(g.getColumn()))&&(getRowPos(g.getVal()) > g.getRow()){
            h = 55;
        }else if(newState.isColumnEmpty(g.getColumn())){
            h = 50;
        }else if(newState.isOnTop(ggetVal())){
            h = 40;
        }else if(newState.isColumnFull(g.getColumn())){
            h = 1;
        }else{
            h = 5;
        }
        actions_vec[i].setHeuristic(h);
        actions.push(actions_vec[i]);
    }
}

    template<typename T>void priority_queueQ(priority_queue<T>q){
    while(!q.empty()){
        q.top().printGoal();
        q.pop();
        }
        cout << endl;
    }
};

class Game{

private:
State state;
Board board;
SolverHD solverHD;

public:
    Game(){};

    void getIntBoard(){
        board.generateIntlState();
        cout <<  "Intial State:" << endl;
        board.printBoard();
    }

    void playGame(){
        priority_queue<Goal>goals;
        getUserGoal(goals);
        solverHD.searchForGoal(board,goals);
    }

    void getUserGoal(priority_queue<Goal>&goals){
    bool added = false;
    int v , r , c;
    string enterMore;
    vector<Goal>goal_vec;
    vector<int>usedBlocks;
    bool blockUsed = false;

    list<int> val = {1,2,3,4,5,6};
    do{
       cout << "Input a goal:" << endl;
    do{
        cout << "Block(1-6):";
        cin >> v;
    }while(v < 1 || v > 6);
    do{
        cout << "Row(0-2):";
        cin >> r;
    }while (r < 0 || r > 2);
    do{
        cout << "Column(0-2):";
        cin >> c;
    }while (c < 0 || c > 2);

    for(int i = 0; i < usedBlocks.size(); i++){
        if(usedBlocks[i] == v){
            cout << "\nA goal of this block has already bbeen added" << endl;
            blockUsed = true;
            break;
        }else{
        blockUsed = false;
        }
    }
    usedBlocks.push_back(v);
    val.remove(v);

    if(!blockUsed){
        Goal g;
        g.setGoal(v ,r, c);
        goal_vec.push_back(g);
        goals.push(g);
        cout << "\nGoal (" << v << ", " << r << ", " << c << ") added\n";
    }
    cout << "\nPress y to enter another goal, otherwise press any key to quit" << endl;
    cin >> enterMore;
    while (enterMore == "y" || enterMore == "Y");

    while(!added){
        int valToUse;
        for(int i = 0; i < goal_vec.size(); i++){
            if(goal_vec[i].getRow() > 0 ){
                for(int r = 0; r <goal_vec[i].getRow(); r++){
                    valToUse = val.front();
                    val.pop_front();

                    Goal g;
                    g.setGoal(valToUse , r , goal_vec[i].getCol());
                    goals.push(g);
                }
            }
        }
       added = true;
    }
    cout << "Searching for the following conjunctive goals:\n"; board.printPriorityQ(goals);
};

class Goal{

private;
int val;
int row;
int col;

public:
    Goal(){};
    Goal(int v , int r , int c){val = v; row = r; col = c;}

    bool operator<(const Goal g)const{
        if(row > g.row ||(row == g.row&&col > g.col)||(row == g.row && g.col&&val > g.val)){
            return true;
        }else {
            return false;
        }
    }

    void printGoal() const{
        cout << "(" << val <<", " << row << ", " << col << ")" << endl;
    }

    void setGoal(int v , int r , int c){
    val = v; row = r; col = c;
    }

    int getVal(){
        return val;
    }
    int getRow(){
        return row;
    }
    int getCol(){
        return col;
    }
};

class SolverHD{

private;
bool goalFound;

public:
    bool searchForGoal(Board b , priority_queue<Goal>&goals){
    vector<State>usedStates;
    vector<Goal>goalsAchieved;
    int generatedStates = 0;
    goalFound = false;

    usedStates.push_backk(b);

    while(generatedStates < MAX_STATE){
     if(goals.size() == 0){
        cout << "All goals have been satisfied!\n" << endl;
        return false;
     }
     while(goals.size() > 0){
        Goal g = goals.top();
        if(b.getValue(g.getRow(),g.getCol()) == g.getVal()){
            cout << "Goal(" << g.getVal() << "," << g.getRow() << "," << g.getCol() << ") was achieved\n" << endl;

        goalsAchieved.push_back(g);
        goals.pop();
        goalFound = true;
        break;
        }else{
        goalFound = false;
            }

        priority_queue<Action>actions;
        b.findActHeuristic(actions, g);

        if(actions.size() == 0){
            cout << "no actions available" << endl;
            return false;
        }
        while(actions.size() > 0){
            Action action = actions.top();
            actions.pop();

            State newState = b.nextState(action);
            bool flag = false;

            for(int i = 0; i < usedState.size(); i++){
                if(usedState[i] == newState){
                    flag = true;
                    break;
                }
            }
            if(flag){
                continue;
                }
                bool used = false;
                int topVal = b.getTopVal(action.getSource());
                for(int i = 0; i < goalsAchieved.size(); i++){
                    if(goalsAchieved[i].getVal() == topVal){
                        used = true;
                    }
                }
                if(used){
                    continue;
                }
            b.moveBlock(action);
            cout << "Step" << generatedStates+1 << ": Move Back" << "v" << ", from col" << action.getSource() << "to col" <<action.getHeuristic() << "." << endl;

            b.printBoard();
            usedStates.push_back(b);
            generatedState+++;
            break;
            }
        }
    }
    if(!goalFound){
        cout << "Max steps reached & Goal not found" << endl;
    }
    generatedStates = 0;
    return true;
    }
    bool idFound(){
    return goalFound;
    }
};

class State{

private;
int grid[BOARDSIZE][BOARDSIZE];

public:
    State(){
    for(int r = 0; r < BOARDSIZE; r++){
        for(int c = 0; c < BOARDSIZE; c++){
            grid[r][c] = 0;
            }
        }
    }

    State(const State& s){
    for(int r = 0; r < BOARDSIZE; r++){
        for(int c = 0; c < BOARDSIZE; c++){
            grid[r][c] = s.getValue(r,c);
            }
        }
    }

    bool operator == (State s){
    for(int r = 0; r < BOARDSIZE; r++){
        for(int c = 0; c < BOARDSIZE; c ++){
            if(grid[r][c] != s.getValue(r,c)){
                return false;
                }
            }
        }
        return true;
    }

    int getSize(){
    return BOARDSIZE;
    }

    int getNumberOfBlocks(){
    return NUM_OF_BLOCKS;
    }

    int getValue(int r, int c)const{
    return grid[r][c];
    }

    void setValue(int r, int c, int value){
    grid[r][c] = value;
    }

    void getPosition (int value, int& r, int& c);

    bool moveBlock(Action a){
    if(isFull(a.getSource()) && isEmpty(a.getDestination())){
       if(insertBlockTo(a.getDestination(), removeBlockFrom(a.getSource()))){
        return true;
            }
        }
        return false;
    }

    State nextState(Action action){
    State newState(*this);

    if(newState.moveBlockk(action))
        return newState;

    return*this;
    }

    void printBoard(){
    cout << endl;
    for(int r = 0; r < BOARDSIZE; r++){
        cout << " |";
        for(int c = 0; c < BOARDSIZE; c++){
            if(grid[BOARDSIZE - r - 1][c] == 0){
                cout << "l"
                }else{
                    cout << " " << grid[BOARDSIZE-r-1][c] << " |";
                }
            }
            cout << endl;
        }
        for(int c = 0; c < BOARDSIZE; c++){
            cout << " ---";
        }
        cout << endl << endl;
    }

    void pushBlocksDown(){
    for(int c = 0; c < BOARDSIZE; c++){
        queue<int>tempQueue;
        for(int r = 0; r < BOARDSIZE; r++){
            if(grid[r][c] != 0){
                tempQueue.push(grid[r][c]);
                }
            }
            for(int r = 0; r < BOARDSIZE; r++){
                if(!tempQueue.empty()){
                    grid[[r][c] = tempQueue.front();
                    tempQueue.pop();
                }else{
                    grid[r][c] = 0;
                }
            }
        }
    }

    bool isEmpty(int c){
    for(int r = 0; r < BOARDSIZE; r++){
        if(getValue(r,c) == 0 ){
            return true;
            }
        }
        return false;
    }

    bool isFull(int c){
    for(int r = 0; r < BOARDSIZE; r++){
        if(getValeu(r,c) != 0){
            return true;
            }
        }
        return false;
    }

    bool isColumnFull(int c){
    return (get.Value(BOARDSIZE - 1,c) != 0);
    }

    bool isColumnEmpty(int c){
    if(getValue(0,c) == 0){
        return true;
        }
        return false;
    }

    bool isBlockEmpty(int r, int c){
    if(getValue(r,c) == 0){
        return true;
        }
        return false;
    }

    bool isOnTop(int val){
    for(int r = MAX_BOARD_INDEX; r > 0; r--){
        for(int c = MAX_BOARD_INDEX; c > 0; c--){
            if(getValue(r,c) == val){
                if(r < 2 && getValue(r+1,c) != 0){
                    return false;
                }else{
                return true;
                    }
                }
            }
        }
        return false;
    }

    int getTopVal(int c){
    for(int r = MAX_BOARD_INDEX; r >= 0; r--)
    if(grid[r][c] != 0){
        return grid[r][c];
        }
        return -1;
    }

    int getRowPos(int val){
    for(int c = 0; c < BOARDSIZE; c++){
        for(int r =0; r < BOARDSIZE; r++){
            if(getValue(r,c) == val){
                return r;
                }
            }
        }
        return -1;
    }

    int removeBlockFrom(int c){
    int holdBlock;

    for(int r = MAX_BOARD_INDEX; r >= 0; r--){
        if(getValue(r,c) != 0){
            holdBlock = getValue(r,c);
            setValue(r,c,0);
            return holdBlock;
            }
        }
        return -1;
    }

    bool insertBlockTo(int c, int value){
    for(int r = 0; r <= MAX_BOARD_INDEX; r++){
        if(getValue(r,c) == 0){
            setValue(r,c,value);
            return true;
            }
        }
        return false;
    }

    int getRow(int r){
    return r;
    }

    int getColumn(int c){
    return c;
    }

};


#endif // STATE_H_INCLUDED


What I have tried:

i've tried to run it but a lot of error

||1\state.h|66|error: expected class-name before '{' token|
1\state.h|155|error: 'State' does not name a type|
1\state.h|156|error: field 'board' has incomplete type 'Board'|
1\state.h|66|note: forward declaration of 'class Board'|
1\state.h|157|error: 'SolverHD' does not name a type|
1\state.h|174|error: 'Goal' was not declared in this scope|
1\state.h|174|error: template argument 1 is invalid|
1\state.h|174|error: template argument 2 is invalid|
1\state.h|174|error: template argument 3 is invalid|
1\main.cpp|20|error: expected '}' at end of input|
1\main.cpp|20|error: expected unqualified-id at end of input|
1\main.cpp|20|error: expected '}' at end of input|
1\state.h||In member function 'void Board::generateIntlState()':|
1\state.h|74|error: 'intializeBlocks' was not declared in this scope|
1\state.h|78|error: expected ')' before 'blocks'|
1\state.h|78|error: 'setVal' was not declared in this scope|
1\state.h|82|error: 'pushBlockDown' was not declared in this scope|
1\state.h|84|error: a function-definition is not allowed here before '{' token|
1\state.h|150|error: expected '}' at end of input|
1\state.h||In member function 'void Board::Game::playGame()':|
1\state.h|169|error: 'Goal' was not declared in this scope|
1\state.h|169|error: template argument 1 is invalid|
1\state.h|169|error: template argument 2 is invalid|
1\state.h|169|error: template argument 3 is invalid|
1\state.h|171|error: 'solverHD' was not declared in this scope|
1\state.h||In member function 'void Board::Game::getUserGoal(int&)':|
1\state.h|178|error: 'Goal' was not declared in this scope|
1\state.h|178|error: template argument 1 is invalid|
1\state.h|178|error: template argument 2 is invalid|
1\state.h|198|warning: comparison between signed and unsigned integer expressions [-Wsign-compare]|
1\state.h|211|error: expected ';' before 'g'|
1\state.h|212|error: 'g' was not declared in this scope|
1\state.h|213|error: request for member 'push_back' in 'goal_vec', which is of non-class type 'int'|
1\state.h|214|error: request for member 'push' in 'goals', which is of non-class type 'int'|
1\state.h|223|error: request for member 'size' in 'goal_vec', which is of non-class type 'int'|
1\state.h|224|error: invalid types 'int[int]' for array subscript|
1\state.h|225|error: invalid types 'int[int]' for array subscript|
1\state.h|229|error: expected ';' before 'g'|
1\state.h|230|error: 'g' was not declared in this scope|
1\state.h|230|error: invalid types 'int[int]' for array subscript|
1\state.h|231|error: request for member 'push' in 'goals', which is of non-class type 'int'|
1\state.h|238|error: expected 'while' before ';' token|
1\state.h|238|error: expected '(' before ';' token|
1\state.h|238|error: expected primary-expression before ';' token|
1\state.h|238|error: expected ')' before ';' token|
1\state.h|280|error: expected ':' before ';' token|
1\state.h|284|error: the value of 'Goal' is not usable in a constant expression|
1\state.h|178|note: 'Goal' was not declared 'constexpr'|
1\state.h|284|error: type/value mismatch at argument 1 in template parameter list for 'template<class _tp,="" class="" _sequence,="" _compare=""> class std::priority_queue'|
1\state.h|284|note:   expected a type, got 'Goal'|
1\state.h|284|error: template argument 2 is invalid|
1\state.h|284|error: template argument 3 is invalid|
1\state.h||In member function 'bool Board::Game::getUserGoal(int&)::SolverHD::searchForGoal(Board, int&)':|
1\state.h|285|error: 'State' was not declared in this scope|
1\state.h|285|error: template argument 1 is invalid|
1\state.h|285|error: template argument 2 is invalid|
1\state.h|286|error: use of local variable with automatic storage from containing function|
1\state.h|178|note: '<typeprefixerror>Goal' declared here|
1\state.h|286|error: use of local variable with automatic storage from containing f\
Posted
Updated 15-Apr-20 17:42pm
v2
Comments
Patrice T 15-Apr-20 8:48am
   
Show exact error messages
Richard MacCutchan 15-Apr-20 9:18am
   
You have declared main before the classes that it is trying to use. Move it to the end of the source file and try again. But, please, if you get errors then tell us what they are.

Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with. So saying "so much error" without telling us what the error messages are, or what line(s) they are associated with means we know nothing about your problem, and can't help!

But I'll try and help you to help yourself.
There are two types of error: Compile Time, and Run Time.

Compile time errors occur when you try to compile your code and the compiler spits it out with file and line references - these are cause by your code using the wrong syntax (such as a missing close bracket perhaps), or spelling a variable differently in two places, or ... loads of reasons, all related to how your code was written.
These tend to be offered up to you as a list of problems with each having a message which describes what the compiler doesn't like, the file name it is in, and the line number it was found on.
Solution: edit the file, find the line (most editors will allow you to type CTRL+G then a lien number to "jump" to it) and read the line and a few above and below in conjunction with the message to see what the problem is. Repeat until you get a "clean compilation".

Run time errors occur only once you have got a clean compile - until that point the EXE file you need to run isn't built so these errors can;t be found yet!
The occur because you told your code to do something wrong, and the range of errors here is far, far broader that Compile time errors, because there are so many more mistakes you could have made. Sometimes these hava message and your app dies, sometime it just doesn't do what you wanted it to.
Solution: Complicated because compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
   
You should use the debugger to find it out. Here is some outstanding tutorial with debugging chapters so you can kickstart debugging your code.

One reason can be that your code is running, but leaves the app after some milliseconds.

The easiest way is to enclose your code in main in a while loop which checks the input like "Play another game: y/n".
   
Comments
Dave Kreskowiak 16-Apr-20 0:42am
   
The debugger doesn't do you any good if your code won't compile.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900