Source

ICFP 2011 ICRS / src / Icfp2011.Icrs.Arbiter / Program.cs

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace Icfp2011.Icrs.Arbiter
{
    internal static class Program
    {
        private static readonly string initialFuncText = LtgCards.ICombinator.ToName();

        private static bool lightInterface = false;

        private static LtgSlot[] oldSlotsPlayerA;
        private static LtgSlot[] oldSlotsPlayerB;

        public static int Main(string[] args)
        {
            try
            {
#if DEBUG
                Console.BufferHeight = 0xFFF;
                Console.WindowHeight = 50;
#endif
                Console.Out.NewLine = "\n";

                var optionArgs = args.Where(a => a.StartsWith("-")).ToArray();
                var freeArgs = args.Except(optionArgs).ToArray();

                lightInterface = optionArgs.Contains("-light", StringComparer.InvariantCultureIgnoreCase);

                if (freeArgs.Length == 0)
                {
                    RunMatch();
                }
                else if (freeArgs.Length == 1)
                {
                    RunMatch(args[0]);
                }
                else if (freeArgs.Length == 2)
                {
                    RunMatch(args[0], args[1]);
                }
                else
                {
                    Console.Error.WriteLine(Properties.Settings.Default.MessageNotEnoughArgs);
                    return Properties.Settings.Default.ExitCodeNotEnoughArgs;
                }

                return Properties.Settings.Default.ExitCodeFatalError;
            }
#if !DEBUG
            catch (Exception ex)
            {
                Console.Error.WriteLine(Properties.Settings.Default.MessageFatalError, ex.Message);
                return Properties.Settings.Default.ExitCodeFatalError;
            }
#endif
            finally
            {
#if DEBUG
                Console.WriteLine();
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey(true);
#endif
            }
        }

#if TEST
        // TODO: temp
        public static void RunTestMatch()
        {
            var match = new LtgMatch();
            var propSlots = match.GetProponentSlots();
            var oppSlots = match.GetOpponentSlots();

            propSlots[0].ApplyRight(propSlots, oppSlots, LtgCards.Help);
            propSlots[0].ApplyRight(propSlots, oppSlots, LtgCards.Zero);
            propSlots[0].ApplyLeft(propSlots, oppSlots, LtgCards.KCombinator);
        }
#endif

        public static void RunMatch()
        {
            try
            {
                var match = new LtgMatch();
                StartMatch(match);
                while (true)
                {
                    StartTurn(match);
                    while (true)
                    {
                        try
                        {
                            PerformCardAction(match, Console.In, false);
                        }
                        catch (FormatException)
                        {
                            if (lightInterface)
                                Console.Error.WriteLine("(cannot parse!)");
                            else
                                Console.Error.WriteLine("Error reading input.");
                            continue;
                        }
                        break;
                    }
                    if (!NextTurn(match, false))
                        break;
                }
            }
            catch (PlayerProgramTerminatedException)
            {
                HandlePlayerProcessEnded();
            }
        }

        public static void RunMatch(string playerProgramPath)
        {
            try
            {
                using (var playerAProcess = CreatePlayerProcess(playerProgramPath, 0))
                {
                    var match = new LtgMatch();
                    StartMatch(match);
                    while (true)
                    {
                        StartTurn(match);
                        PerformCardAction(match, playerAProcess.StandardOutput, true);
                        if (!NextTurn(match, false))
                            break;
                    }
                }
            }
            catch (PlayerProgramTerminatedException)
            {
                HandlePlayerProcessEnded();
            }
        }

        public static void RunMatch(string player1ProgramPath, string player2ProgramPath)
        {
            try
            {
                using (var playerAProcess = CreatePlayerProcess(player1ProgramPath, LtgPlayer.PlayerA))
                using (var playerBProcess = CreatePlayerProcess(player2ProgramPath, LtgPlayer.PlayerB))
                {
                    var match = new LtgMatch();
                    StartMatch(match);
                    while (true)
                    {
                        StartTurn(match);
                        PerformCardAction(match, playerAProcess.StandardOutput, true);
                        PerformCardAction(match, playerBProcess.StandardOutput, true);
                        if (!NextTurn(match, true))
                            break;
                    }
                }
            }
            catch (PlayerProgramTerminatedException)
            {
                HandlePlayerProcessEnded();
            }
        }

        private static void StartMatch(LtgMatch match)
        {
            oldSlotsPlayerA = match.SlotsPlayerA;
            oldSlotsPlayerB = match.SlotsPlayerB;
        }

        private static void StartTurn(LtgMatch match)
        {
            if (lightInterface)
            {
                //
            }
            else
            {
                Console.Out.WriteLine("###### turn {0}", match.TurnNumber);
            }
        }

        private static bool NextTurn(LtgMatch match, bool switchTurns)
        {
            var success = match.NextTurn(switchTurns);

            if (lightInterface)
            {
                Console.Out.WriteLine();
            }
            else
            {
                //
            }

            return success;
        }

        private static void PerformCardAction(LtgMatch match, TextReader reader, bool echoInput)
        {
            var propSlots = match.GetProponentSlots();
            var oppSlots = match.GetOpponentSlots();

            if (lightInterface)
            {
                Console.Out.Write("{0}{1}: ", match.TurnNumber, GetPlayerChar(match.CurrentPlayer));
            }
            else
            {
                Console.Out.WriteLine("*** player {0}'s turn, with slots:",
                    (int)match.CurrentPlayer);
                for (int i = 0; i < propSlots.Length; i++)
                {
                    var slot = propSlots[i];
                    var funcText = GetValueText(match, slot);
                    if (slot.Vitality == LtgMatch.InitialVitality && funcText == initialFuncText)
                        continue;
                    Console.Out.WriteLine("{0}={{{1},{2}}}", i, slot.Vitality, funcText);
                }
                Console.Out.WriteLine("(slots {{{0},{1}}} are omitted)",
                    LtgMatch.InitialVitality, initialFuncText);
            }

            oldSlotsPlayerA = match.SlotsPlayerA.CloneAll();
            oldSlotsPlayerB = match.SlotsPlayerB.CloneAll();

            // Read card action from input stream and perform it.
            var action = ReadCardAction(reader, echoInput);
            var actionSlot = propSlots[action.SlotIndex];
            var applySuccess = false;
            if (action.ApplicationOrder == LtgCardApplicationOrder.Left)
            {
                applySuccess = actionSlot.ApplyLeft(propSlots, oppSlots, action.Card);
                if (!lightInterface)
                {
                    Console.Out.WriteLine("player {0} applied card {1} to slot {2}",
                        (int)match.CurrentPlayer, action.Card.ToName(), action.SlotIndex);
                }
            }
            else if (action.ApplicationOrder == LtgCardApplicationOrder.Right)
            {
                applySuccess = actionSlot.ApplyRight(propSlots, oppSlots, action.Card);
                if (!lightInterface)
                {
                    Console.Out.WriteLine("player {0} applied slot {2} to card {1}",
                        (int)match.CurrentPlayer, action.Card.ToName(), action.SlotIndex);
                }
            }
            else
            {
                throw new InvalidOperationException("Invalid card application order.");
            }

            if (lightInterface)
            {
                if (applySuccess)
                {
                    Console.Out.Write("(ok)");
                }
                else
                {
                    Console.Out.Write("(error)");
                }

                OutputSlotChanges(match, LtgPlayer.PlayerA);
                OutputSlotChanges(match, LtgPlayer.PlayerB);
            }
            else
            {
                if (applySuccess)
                {
                    //
                }
                else
                {
                    Console.Out.WriteLine("Exception");
                    Console.Out.WriteLine("slot {0} reset to {1}", action.SlotIndex, initialFuncText);
                }
            }
        }

        private static void OutputSlotChanges(LtgMatch match, LtgPlayer player)
        {
            LtgSlot[] newSlots;
            LtgSlot[] oldSlots;

            if (player == LtgPlayer.PlayerA)
            {
                newSlots = match.SlotsPlayerA;
                oldSlots = oldSlotsPlayerA;
            }
            else if (player == LtgPlayer.PlayerB)
            {
                newSlots = match.SlotsPlayerB;
                oldSlots = oldSlotsPlayerB;
            }
            else
            {
                throw new ArgumentException("Invalid player.", "player");
            }

            var firstChange = true;
            for (int i = 0; i < newSlots.Length; i++)
            {
                if (newSlots[i].Value == oldSlots[i].Value)
                    continue;

                if (firstChange)
                {
                    Console.Out.WriteLine();
                    firstChange = false;
                }

                Console.Out.Write(GetPlayerChar(player));
                Console.Out.Write(i);
                Console.Out.Write("={0}", GetValueText(match, newSlots[i]));
                Console.Out.Write(" ");
            }
        }

        // Gets infix textual representation of value (function or number).
        private static string GetValueText(LtgMatch match, LtgSlot slot)
        {
            return GetValueTextInternal(match.Clone(), slot.Clone().Value);
        }

        private static string GetValueTextInternal(LtgMatch match, LtgValue val)
        {
            var sb = new StringBuilder();

            var testMatch = match;
            var evalDepth = 0;
            var evaluator = new LtgFunction((depth, propSlots, oppSlots, arg) =>
                {
                    var func = arg as LtgFunction;
                    var name = arg.ToName();
                    if (name == null && func != null)
                        name = func.ParentFunction.ToName();
                    sb.Append(name);
                    if (func != null && func.Arguments != null)
                    {
                        foreach (var a in func.Arguments)
                        {
                            sb.Append("(");
                            sb.Append(GetValueTextInternal(match, a));
                            sb.Append(")");
                        }
                    }
                    return LtgCards.ICombinator;
                });

            var success = evaluator.Evaluate(ref evalDepth,
                testMatch.GetProponentSlots(), testMatch.GetOpponentSlots(), val);
            return sb.ToString();
        }

        private static char GetPlayerChar(LtgPlayer player)
        {
            if (player == LtgPlayer.PlayerA)
            {
                return 'A';
            }
            else if (player == LtgPlayer.PlayerB)
            {
                return 'B';
            }
            else
            {
                throw new ArgumentException("Invalid player.", "player");
            }
        }

        private static LtgAction ReadCardAction(TextReader reader, bool echoInput)
        {
            var action = new LtgAction();

            Action readSlotNumber = () =>
                {
                    if (!lightInterface)
                        Console.Out.WriteLine("slot number?");
                    action.SlotIndex = int.Parse(ReadValue(reader, echoInput));
                };
            Action readCardNumber = () =>
                {
                    if (!lightInterface)
                        Console.Out.WriteLine("card name?");
                    var cardName = ReadValue(reader, echoInput);
                    if (cardName.Length == 1)
                        cardName = cardName.ToUpperInvariant();
                    else
                        cardName = cardName.ToLowerInvariant();
                    action.Card = LtgCards.FromName(cardName);
                };

            if (!lightInterface)
                Console.Out.WriteLine("(1) apply card to slot, or (2) apply slot to card?");
            action.ApplicationOrder = (LtgCardApplicationOrder)int.Parse(ReadValue(reader, echoInput));
            if (action.ApplicationOrder == LtgCardApplicationOrder.Left || lightInterface)
            {
                readCardNumber();
                readSlotNumber();
            }
            else if (action.ApplicationOrder == LtgCardApplicationOrder.Right)
            {
                readSlotNumber();
                readCardNumber();
            }
            else
            {
                throw new InvalidOperationException();
            }

            return action;
        }

        private static string ReadValue(TextReader reader, bool echoInput)
        {
            string value;
            if (lightInterface)
            {
                // Read value followed by space.
                var sb = new StringBuilder();
                while (true)
                {
                    var key = Console.ReadKey(true);
                    var chr = key.KeyChar;
                    if (chr == ' ')
                    {
                        Console.Write(chr);
                        break;
                    }
                    if (chr == '\r' || chr == '\n')
                        continue;
                    if (chr == '\b')
                    {
                        if (sb.Length == 0)
                            continue;
                        sb.Remove(sb.Length - 1, 1);
                    }
                    else
                    {
                        sb.Append(chr);
                    }
                    Console.Write(chr);
                }
                value = sb.ToString();
            }
            else
            {
                // Read value followed by line feed.
                value = reader.ReadLine();
            }

            if (string.IsNullOrEmpty(value))
                throw new PlayerProgramTerminatedException();
            if (echoInput)
            {
                if (lightInterface)
                {
                    Console.Out.Write(value);
                    Console.Out.Write(' ');
                }
                else
                {
                    Console.Out.WriteLine(value);
                }
            }
            return value;
        }

        private static Process CreatePlayerProcess(string path, LtgPlayer player)
        {
            var procStartInfo = new ProcessStartInfo(path);
            procStartInfo.Arguments = ((int)player).ToString();
            procStartInfo.UseShellExecute = false;
            procStartInfo.RedirectStandardInput = true;
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.RedirectStandardError = true;
            return Process.Start(procStartInfo);
        }

        private static void HandlePlayerProcessEnded()
        {
            Console.Error.WriteLine();
            Console.Error.WriteLine("Player program terminated.");
        }

        public class PlayerProgramTerminatedException : Exception
        {
            public PlayerProgramTerminatedException()
                : base()
            {
            }
        }
    }
}