Home > Blockchain >  Loop for a game that checks if move is legal or not
Loop for a game that checks if move is legal or not

Time:12-08

before I start, I am new to programming and have only been studying IT for a couple weeks so dont go too hard on me :).

I currently need to create a simple game and right now I need to find a function that checks if the move that is being made by the player is "legal" or not.

Ive done this by creating the following function.



bool legal(Game* g, int x, int y) {
     if (out_of_bounds(x,y))
    {
        return false;
    } else 
    if (!out_of_bounds(x,y))
    {
        return (g ->board[x][y] == '_') &&
        (
            legal_dir(g,x,y, 0, -1) ||
            legal_dir(g,x,y, -1, -1) ||
            legal_dir(g,x,y, -1, 0) ||
            legal_dir(g,x,y, 1, -1) ||
            legal_dir(g,x,y, -1, 1) ||
            legal_dir(g,x,y, 1, 0) ||
            legal_dir(g,x,y, 0, 1) ||
            legal_dir(g,x,y, 1, 1)
        );
    }
}

the function out of bounds is already implemented and should work fine. The comment that was given to us is the following.

// Check whether (x,y) is a legal position to place a stone. A position is legal // if it is empty ('_'), is on the board, and has at least one legal direction.

Im sure there has to be a loop for going through these 8 possibilities.

I tried creating the function shown above and it works, but there has to be a more efficient way of implementing it.

CodePudding user response:

You can create an array of coordonnee of this type and iterate throught it

struct Coordonnees
{
    int x; // Abscisses
    int y; // Ordonnées
};
Coordonnees coords[] = {
{-1,-1}, {0,-1}, {1,-1},
{-1, 0},       , {1, 0},
{-1, 1}, {0, 1}, {1, 1},
};
bool hasValidDir = false;
if (g ->board[x][y] != '_') {
 return false;
}
for (int i = 0; i < 8; i  ) {
  if (legal_dir(g, x, y, coords[i].x, coords[i].y) {
    hasValidDir = true;
  }
}
return hasValidDir;

I'm not sure about the c code validity but you can do a loop like this.

CodePudding user response:

great question!

As usual, there are a few approaches possible, but what's probably most standard is to create a nested list of the coordinates of those eight points:

[[0, -1], [-1, -1], ... ]

And then you can loop through that list. Syntax should be reasonably straightforward to do that, but feel free to post for follow ups if you need. Don't want to short-circuit your learning process, going to figure those kinds of things out is a huge part of learning how to be a developer!

Regardless of whether or not you can use it in this example, do a quick search and try to understand what an "iterable" is -- it's a powerful programming concept.

Best of luck, and welcome!

  • Related