lundi 17 octobre 2016

Nested if statements, while also removing options

first post and noob programmer, so please bare with me. I am currently attempting an assignment doing the "Wa-Tor Simulation" assignment in C++. Its still early in the course so were not at the graphical part of the assignment, but rather the movements and functions of the Fish and Shark. If you don't know the Wa-Tor simulation, I don't think that matters to my question.

What I'm trying to accomplish is:

I have a two dimensional array that consists of empty, fish, and shark.

A shark moves either up, down, left, or right randomly. If the shark moves left of the array when at the farthest left point, it will appear on the right side(as well as up, down, and right). If the shark moves to a location with empty of a fish, it will overtake the location, but if it encounters another shark, it will try to move in another location relative to its first location.

If the shark is surrounded by other sharks, it will not move.

What I have done so far, is create a temp array that will move sharks so that while running the for loop, sharks don't move twice.

Thus my code looks like :

 for (int i = 0; i < MAX_X; i++) {
    for (int j = 0; j < MAX_Y; j++) {

        if (myOcean[i][j] == SHARK) {
            int randNum = (rand() % 4 + 1);

            switch (randNum) {
            case 1:
 //This is where I don't know how to properly code to make my function work, so bare with me while I make fake code..
 //if(myOcean[i+1][j] == SHARK){ GO BACK AND FIND A NEW RANDOM NUMBER, BUT THIS TIME REMOVE CASE 1. THUS NOT ALLOWING AN ATTEMPT TO MOVE [i+1]
                if ((i + 1) == MAX_X) { tempArray[0][j] = SHARK; }
                else { tempArray[i + 1][j] = SHARK; }
                tempArray[i][j] = EMPTY;
                break;
            case 2:
 // Same as above. Remove Case 2 if it doesnt work.
                if ((i - 1) < 0) { tempArray[MAX_X - 1][j] = SHARK; }
                else { tempArray[i - 1][j] = SHARK; }
                tempArray[i][j] = EMPTY;
                break;

            case 3:
 // Same as above. Remove Case 3 if it doesnt work.
                if ((j + 1) == MAX_Y) { tempArray[i][0] = SHARK; }
                else { tempArray[i][j + 1] = SHARK; }
                tempArray[i][j] = EMPTY;
                break;
            case 4:
 // Same as above. Remove Case 4 if it doesnt work.
                if ((j - 1) < 0) { tempArray[i][MAX_Y - 1] = SHARK; }
                else { tempArray[i][j - 1] = SHARK; }
                tempArray[i][j] = EMPTY;
                break;
            default:
  // No cases worked, thus the shark remains still.
                tempArray[i][j] = myOcean[i][j];

            }
        }
    }
}

Thus ends my problem. I dont know how to go back and remove specific case's. Hopefully I explained my problem well enough, as I am still very new to coding. Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire