1  // Rock, Paper, Scissors              Bill Rubin
   2  using System;
   3  using System.Collections.Generic;
   4  using System.Reflection;
   5  using System.Threading;
   6  using System.Threading.Tasks;
   7  
   8  public enum Gesture { Rock, Paper, Scissors }
   9  public delegate void OtherPlayer(Player player);
  10  
  11  class Program {
  12      static void Main(string[] args) {
  13          try {
  14              // Read N
  15              if (args.Length == 0) throw new Exception("Number of players input is missing.");
  16              int N = Convert.ToInt32(args[0]);
  17              if(N<2) throw new Exception("Number of players must be two or more.");
  18              Console.WriteLine("Begin game with " + N + " players ...");
  19              
  20              Barrier barrier = new Barrier(N);
  21  
  22              // Create players:
  23              List<Player> players = new List<Player>();
  24              // Just assign strategies to players in order:
  25              for (int k = 0; k < N; k++) {
  26                  string strategyName = Strategy.names[k % Strategy.names.Length];
  27                  players.Add(new Player(barrier, k + 1, Strategy.create(strategyName)));
  28                  }
  29  
  30              // All players must know about each other
  31              foreach (Player player in players) player.setPlayers(players);
  32  
  33              // Run the match:
  34              List<Task> otherTasks = new List<Task>();
  35              MethodInfo mi = 
  36                  typeof(Player).GetMethod("playMatch", BindingFlags.Public | BindingFlags.Instance);
  37              OtherPlayer otherPlayer = 
  38                  (OtherPlayer)Delegate.CreateDelegate(typeof(OtherPlayer), null, mi);
  39                  
  40              for (int k = 1; k < N; k++) {
  41                  Player player = players[k];  // Cannot just use players[k] in next line!
  42                  otherTasks.Add(Task.Factory.StartNew(() => otherPlayer(player)));
  43                  }
  44  
  45              otherPlayer(players[0]);
  46              Task.WaitAll(otherTasks.ToArray());
  47  
  48              // Display results:
  49              foreach (Player player in players) player.displayScore();
  50              barrier.Dispose();
  51              }
  52  
  53          catch(Exception x) {Console.Write(x.Message.ToString() + "\n");}
  54      }
  55  }