user2883073
user2883073

Reputation:

Methodes in Constructor repeats

I want the "BombenGenerieren(anzahlMinen)" only one time, how should I write it, that it doesn't generates new bombs every round?

public Game(int anzahlMinen, int xeingabe, int yeingabe)
{
  _minenArray = new int[5, 5];
  _emptyArray = new int[5, 5];
  _boolArray = new bool[5, 5];
  program = new Program();
  zeichnen = new Draw();

  BombenGenerieren(anzahlMinen);
  FillPlayMap();
  Umdreher(yeingabe, xeingabe);
  zeichnen.OpenField(_minenArray, _boolArray);
  //SeenMap();

}

Upvotes: 0

Views: 59

Answers (2)

Rik
Rik

Reputation: 29243

I'm assuming Game is a constructor and you want to execute BombenGenerieren once and share it between instances.

What you should do, is make BombenGenerieren static and store whatever the effect of BombenGenerieren is in one or more static fields or properties. You should then call Game.BombenGenerieren before instantiating new Game objects, or alternatively create a static constructor as follows:

public static Game()
{
    BombenGenerieren(anzahlMinen);
}

The static constructor will be executed the first time you use the Game type. Note that it does no take parameters, so anzahlMinen will have to be a constant. If that is a problem, go with the regular static method.

Another alternative is to encapsulate the result of the BombenGenerieren method in an object and pass that to the Game constructor, whcih can apply the result to each new class.

Upvotes: 1

KeyNone
KeyNone

Reputation: 9190

Basically, utilize a boolean variable to keep track of the execution of BombenGenerieren.

boolean bombenGeneriert = false;

public Game(int anzahlMinen, int xeingabe, int yeingabe) {
    //...

    BombenGenerieren(anzahlMinen);

    //...
}

public void BombenGenerieren(int minen) {
    if (!bombenGeneriert) {
        bombenGeneriert = true;

        //the rest of your code in this method
    }
}

This will set bombenGeneriert to true the first the method is executed. Now on every execution it checks for !bombenGeneriert which will evaluate to false.

Besides, you should consider rearranging your code. I suspect you call Game() more than once, so you should probably relocate your BombenGenerieren() method, somewhere outside Game().

If Game is your class and Game() a constructor, than bombenGeneriert hast to be static:

static boolean bombenGeneriert = false;

Upvotes: 0

Related Questions