7

I am trying to delete all the players that played a turn in a game. The contract is not meant to permanently store a list of players, it simply keeps track of players that have played in the current turn. Player status is held in a struct, however deleting the struct inside a mapping does not work. how do I zero the storage(delete) after each turn. Here is my code:

contract MyGame {
  struct Register {
    bool played;
  }
  mapping (address => Register) players;  
  Register Reg;

  function Play {
    players[msg.sender].played=true;
  }

  function SetUp {
    /*this should zero storage before next game*/
    delete Reg;
  }
}

1 Answers1

6

You could keep a separate list of players, and zero each element in the map (and the array), but you're likely to run into gas limits doing that.

Instead, keep a global "game number", starting at 1, and replace bool played with int lastGame. A player has played in the current game if their lastGame variable equals the current game number variable. At the end of a game, simply increment the game number, and all players are now considered as not having played in the new game.

The result looks something like this:

contract MyGame {
  int currentGame = 1;
  struct Register {
    int gameNumber;
  }
  mapping (address => Register) players;  

  function Play() {
    players[msg.sender].gameNumber = currentGame;
  }

  function HasPlayed() {
    return players[msg.sender].gameNumber == currentGame;
  }

  function NextGame() {
    currentGame++;
  }
}
Nick Johnson
  • 8,144
  • 1
  • 28
  • 35