Exemplo n.º 1
0
    /// <summary>
    /// Parse termination set
    /// </summary>
    /// <param name="game"></param>
    /// <param name="childChildren"></param>
    private static void parseTerminations(BasicGame game, IEnumerable <VGDLNode> childChildren)
    {
        foreach (var node in childChildren)
        {
            if (verbose)
            {
                Debug.Log("Parsing termination from: " + node.content + "\nLine: " + node.lineNumber);
            }

            var typeAndArgs = parseArgs(node.content);

            if (verbose)
            {
                var parameters = string.Join(",", typeAndArgs.args.Select(item => item.ToString()).ToArray());
                Debug.Log("Parsing and Adding [" + typeAndArgs.sclass + "] " +
                          "with parameters (" + parameters + ")");
            }


            try
            {
                var termination = CreateInstance <VGDLTermination>(typeAndArgs);
                termination.Validate(game);
                game.addTerminationCondition(termination);
            }
            catch (Exception e)
            {
                Debug.LogError("Termination type [" + typeAndArgs.sclass + "] not initialized, verify it is spelled correctly, the system is case-sensitive \n" + e.Message);
                throw e;
            }
        }
    }
Exemplo n.º 2
0
        public static void Setup()
        {
            ConsoleInputController             = new ConsoleInputController(Player);
            ConsoleInputController.IOInterface = TextIOMock.Object;

            var board = new Game.Simulation.Board
            {
                Squares = new Square[, ]
                {
                    { new Square(' ', 'a', 1), new Square(' ', 'a', 2), new Square(' ', 'a', 3), new Square(' ', 'a', 4), new Square(' ', 'a', 5), new Square(' ', 'a', 6), new Square(' ', 'a', 7), new Square(' ', 'a', 8) },

                    { new Square(' ', 'b', 1), new Square(' ', 'b', 2), new Square(' ', 'b', 3), new Square(' ', 'b', 4), new Square(' ', 'b', 5), new Square(' ', 'b', 6), new Square(' ', 'b', 7), new Square(' ', 'b', 8) },

                    { new Square(' ', 'c', 1), new Square(' ', 'c', 2), new Square(' ', 'c', 3), new Square(' ', 'c', 4), new Square(' ', 'c', 5), new Square(' ', 'c', 6), new Square(' ', 'c', 7), new Square(' ', 'c', 8) },

                    { new Square(' ', 'd', 1), new Square(' ', 'd', 2), new Square(' ', 'd', 3), new Square(' ', 'd', 4), new Square(' ', 'd', 5), new Square(' ', 'd', 6), new Square(' ', 'd', 7), new Square(' ', 'd', 8) },

                    { new Square(' ', 'e', 1), new Square(' ', 'e', 2), new Square(' ', 'e', 3), new Square(' ', 'e', 4), new Square(' ', 'e', 5), new Square(' ', 'e', 6), new Square(' ', 'e', 7), new Square(' ', 'e', 8) },

                    { new Square(' ', 'f', 1), new Square(' ', 'f', 2), new Square(' ', 'f', 3), new Square(' ', 'f', 4), new Square(' ', 'f', 5), new Square('♘', 'f', 6), new Square(' ', 'f', 7), new Square(' ', 'f', 8) },

                    { new Square(' ', 'g', 1), new Square(' ', 'g', 2), new Square(' ', 'g', 3), new Square(' ', 'g', 4), new Square(' ', 'g', 5), new Square(' ', 'g', 6), new Square(' ', 'g', 7), new Square(' ', 'g', 8) },

                    { new Square(' ', 'h', 1), new Square(' ', 'h', 2), new Square(' ', 'h', 3), new Square(' ', 'h', 4), new Square(' ', 'h', 5), new Square(' ', 'h', 6), new Square(' ', 'h', 7), new Square(' ', 'h', 8) }
                }
            };

            Game = new Game.Simulation.Game(board, new SimpleAI(Color.black), Player);
        }
Exemplo n.º 3
0
    private static void LoadLevelFromExampleString(BasicGame game, string example, int level)
    {
        var exampleLevelStr = Path.Combine("vgdl", Path.Combine("examples", example)) + "_lvl" + level;

        //NOTE: we expect the levels to be located in the same folder and called [gamename]_lvl[levelnum].txt
        LoadLevelFromFile(game, exampleLevelStr);
    }
Exemplo n.º 4
0
        public void GetHistoric(int max)
        {
            var testGame = (BasicGame)_games.GameTypes[(int)GameType.Lotto];

            if (max == 0)
            {
                max = testGame.CurrentRound;
            }
            var allNumbers  = new ArrayList();
            var lottoString = new List <string>();

            for (var i = testGame.CurrentRound; i > (testGame.CurrentRound - max); i--)
            {
                var res = BasicGame.GetNumbers(SavePath + testGame.Init.Name, i);
                lottoString.Add(string.Join(",", res.MainTable));
                allNumbers.AddRange(res.MainTable);
                //var arr = res.Split(',').ToList();
            }
            var sorted = lottoString.OrderBy(q => q).ToList();

            //var duplicateKeys = lottoString.GroupBy(x => x)
            //    .Where(group => group.Count() > 1)
            //    .Select(group => group.Key);

            CreateChart(allNumbers, "chart_last_" + max);
        }
Exemplo n.º 5
0
    /// <summary>
    /// Parse level mappings
    /// </summary>
    /// <param name="game"></param>
    /// <param name="childChildren"></param>
    /// <exception cref="ArgumentException"></exception>
    private static void parseLevelMappings(BasicGame game, List <VGDLNode> childChildren)
    {
        foreach (var node in childChildren)
        {
            if (!node.content.Contains(">"))
            {
                throw new ArgumentException("Mapping error on line: " + node.lineNumber +
                                            "\nMapping should be in the form [c > sprite1 sprite2 etc.]");
            }

            if (verbose)
            {
                Debug.Log("Parsing levelMapping from: " + node.content + "\nLine: " + node.lineNumber);
            }

            var map = node.content.Split(new [] { '>' }, StringSplitOptions.RemoveEmptyEntries);

            var c = map[0].Trim();
            if (c.Length != 1)
            {
                throw new ArgumentException("Only single character mappings allowed on left side of '>'" +
                                            "\nLine: " + node.lineNumber + " Found: [" + c + "]");
            }

            var keys = map[1].Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (verbose)
            {
                Debug.Log("Mapping [" + c + "] to (" + string.Join(",", keys) + ")");
            }

            game.addCharMapping(c[0], keys);
        }
    }
Exemplo n.º 6
0
    private static void parseLevels(BasicGame game, IEnumerable <VGDLNode> childChildren)
    {
        foreach (var node in childChildren)
        {
            if (verbose)
            {
                Debug.Log("Parsing level: " + node.content + "\nLine: " + node.lineNumber);
            }


            var level = new string[node.children.Count];
            var width = 0;
            for (var index = 0; index < node.children.Count; index++)
            {
                level[index] = node.children[index].content;
                if (width < level[index].Length)
                {
                    width = level[index].Length;
                }
            }

            if (verbose)
            {
                Debug.Log("Adding level [" + node.content + "] with dimensions: (" + width + "," + level.Length + ")");
            }

            game.addLevel(level);
        }
    }
Exemplo n.º 7
0
    public BasicGame CreateGame(int numberOfPlayers)
    {
        BasicGame newGame = new BasicGame(LastGameId++);

        newGame.SetNumberOfPlayers(numberOfPlayers);
        Games.Add(newGame);
        return(newGame);
    }
Exemplo n.º 8
0
 public Game(BasicGame other) :
     base(new Graphical.Board(other.Board),
          (other.Player0 == null) ? null : other.Player0.Clone(),
          (other.Player1 == null) ? null : other.Player1.Clone())
 {
     Board2D.InitializeGraphicalElements();
     Board2D.Initialize2DCoordinates(new Vec2 <uint>((MainWindowSize.Width / 4), (MainWindowSize.Height / 32)));
 }
Exemplo n.º 9
0
    public BasicGame.BasicPlayer JoinNewGame(string nickname, int numberOfPlayers)
    {
        BasicGame newGame = CreateGame(numberOfPlayers);

        newGame.Player [0].Connected = true;
        newGame.Player [0].Nickname  = nickname;
        return(newGame.Player [0]);
    }
Exemplo n.º 10
0
        public static void Setup()
        {
            board = new Game.Simulation.Board
            {
                Squares = new Square[, ]
                {
                    { new Square('♜', 'a', 1), new Square('♟', 'a', 2), new Square(' ', 'a', 3), new Square(' ', 'a', 4), new Square(' ', 'a', 5), new Square(' ', 'a', 6), new Square(' ', 'a', 7), new Square(' ', 'a', 8) },

                    { new Square(' ', 'b', 1), new Square(' ', 'b', 2), new Square('♘', 'b', 3), new Square(' ', 'b', 4), new Square(' ', 'b', 5), new Square(' ', 'b', 6), new Square(' ', 'b', 7), new Square(' ', 'b', 8) },

                    { new Square(' ', 'c', 1), new Square(' ', 'c', 2), new Square(' ', 'c', 3), new Square(' ', 'c', 4), new Square(' ', 'c', 5), new Square(' ', 'c', 6), new Square(' ', 'c', 7), new Square(' ', 'c', 8) },

                    { new Square(' ', 'd', 1), new Square(' ', 'd', 2), new Square(' ', 'd', 3), new Square(' ', 'd', 4), new Square(' ', 'd', 5), new Square(' ', 'd', 6), new Square(' ', 'd', 7), new Square(' ', 'd', 8) },

                    { new Square('♚', 'e', 1), new Square(' ', 'e', 2), new Square(' ', 'e', 3), new Square(' ', 'e', 4), new Square(' ', 'e', 5), new Square(' ', 'e', 6), new Square(' ', 'e', 7), new Square('♔', 'e', 8) },

                    { new Square('♝', 'f', 1), new Square(' ', 'f', 2), new Square(' ', 'f', 3), new Square(' ', 'f', 4), new Square(' ', 'f', 5), new Square(' ', 'f', 6), new Square('♙', 'f', 7), new Square(' ', 'f', 8) },

                    { new Square(' ', 'g', 1), new Square('♟', 'g', 2), new Square(' ', 'g', 3), new Square(' ', 'g', 4), new Square(' ', 'g', 5), new Square(' ', 'g', 6), new Square(' ', 'g', 7), new Square('♘', 'g', 8) },

                    { new Square(' ', 'h', 1), new Square(' ', 'h', 2), new Square(' ', 'h', 3), new Square(' ', 'h', 4), new Square(' ', 'h', 5), new Square(' ', 'h', 6), new Square(' ', 'h', 7), new Square(' ', 'h', 8) }
                }
            };

            var whitePlayerMock = new Mock <Player>(Color.white)
            {
                CallBase = true
            };

            var blackPlayerMock = new Mock <Player>(Color.black)
            {
                CallBase = true
            };

            var whitePlayerCloneMock = new Mock <Player>(Color.white)
            {
                CallBase = true
            };

            var gameMock = new Mock <BasicGame>(MockBehavior.Loose, board, whitePlayerMock.Object, blackPlayerMock.Object)
            {
                CallBase = true
            };

            gameMock.Setup((BasicGame self) => self.Board)
            .Returns(board);

            /* Need to provide an implementation of Clone(), since it's an abstract method */
            whitePlayerMock.Setup((Player self) => self.Clone())
            .Returns(() => { return(whitePlayerCloneMock.Object); });

            whitePlayerMock.Setup((Player self) => self.Color)
            .CallBase();

            game        = gameMock.Object;
            whitePlayer = whitePlayerMock.Object;
            blackPlayer = blackPlayerMock.Object;
        }
Exemplo n.º 11
0
        public void CheckRound_1145()
        {
            var testGame = (BasicGame)_games.GameTypes[(int)GameType.Lotto];
            var res      = BasicGame.GetNumbers(SavePath + testGame.Init.Name, 1145);

            Assert.AreEqual(7, res.MainTable.Count);
            Assert.AreEqual(1, res.AddTable.Count);
            Assert.AreEqual(2, res.AddTable[0]);
        }
Exemplo n.º 12
0
        public Move CreateMoveFromPlayerInput(RankFile pieceCurrentPosition, RankFile pieceDesiredDestination)
        {
            validate(pieceCurrentPosition, pieceDesiredDestination);

            BasicGame game = Player.Game;

            Chess.Game.Board board = game.Board;

            IPiece piece       = board[pieceCurrentPosition].Piece.Object;
            Square destination = board[pieceDesiredDestination];

            return(new Move(Player, piece, destination));
        }
Exemplo n.º 13
0
 public Game(BasicGame other) :
     base(new Simulation.Board(other.Board),
          (other.Player0 == null) ? null : other.Player0.Clone(),
          (other.Player1 == null) ? null : other.Player1.Clone())
 {
     if (Player0.IsOfType <Human>())
     {
         Player0 = new SimpleAI(other.Player0);
     }
     if (Player1.IsOfType <Human>())
     {
         Player1 = new SimpleAI(other.Player1);
     }
 }
Exemplo n.º 14
0
    public BasicGame.BasicPlayer JoinGame(string nickname, int numberOfPlayers, int id)
    {
        BasicGame game = GetGame(id);

        foreach (BasicGame.BasicPlayer player in game.Player)
        {
            if (!player.Connected)
            {
                player.Connected = true;
                player.Nickname  = nickname;
                return(player);
            }
        }
        return(game.Player [0]);
    }
Exemplo n.º 15
0
    public BasicGame.BasicPlayer JoinEmptyGame(string nickname, int numberOfPlayers)
    {
        BasicGame game = GetEmptyGame(numberOfPlayers);

        foreach (BasicGame.BasicPlayer player in game.Player)
        {
            if (!player.Connected || player.Nickname == nickname)
            {
                player.Connected = true;
                player.Nickname  = nickname;
                return(player);
            }
        }
        return(game.Player [0]);
    }
Exemplo n.º 16
0
        public static void Setup()
        {
            board = new Game.Simulation.Board
            {
                Squares = new Square[, ]
                {
                    { new Square(' ', 'a', 1), new Square(' ', 'a', 2), new Square(' ', 'a', 3), new Square(' ', 'a', 4), new Square(' ', 'a', 5), new Square(' ', 'a', 6), new Square(' ', 'a', 7), new Square(' ', 'a', 8) },

                    { new Square(' ', 'b', 1), new Square(' ', 'b', 2), new Square(' ', 'b', 3), new Square('♟', 'b', 4), new Square(' ', 'b', 5), new Square(' ', 'b', 6), new Square(' ', 'b', 7), new Square(' ', 'b', 8) },

                    { new Square(' ', 'c', 1), new Square(' ', 'c', 2), new Square(' ', 'c', 3), new Square(' ', 'c', 4), new Square(' ', 'c', 5), new Square(' ', 'c', 6), new Square(' ', 'c', 7), new Square('♜', 'c', 8) },

                    { new Square(' ', 'd', 1), new Square(' ', 'd', 2), new Square(' ', 'd', 3), new Square('♔', 'd', 4), new Square(' ', 'd', 5), new Square('♚', 'd', 6), new Square(' ', 'd', 7), new Square(' ', 'd', 8) },

                    { new Square('♜', 'e', 1), new Square(' ', 'e', 2), new Square(' ', 'e', 3), new Square(' ', 'e', 4), new Square(' ', 'e', 5), new Square(' ', 'e', 6), new Square(' ', 'e', 7), new Square(' ', 'e', 8) },

                    { new Square(' ', 'f', 1), new Square(' ', 'f', 2), new Square(' ', 'f', 3), new Square('♞', 'f', 4), new Square(' ', 'f', 5), new Square(' ', 'f', 6), new Square(' ', 'f', 7), new Square(' ', 'f', 8) },

                    { new Square(' ', 'g', 1), new Square(' ', 'g', 2), new Square(' ', 'g', 3), new Square(' ', 'g', 4), new Square(' ', 'g', 5), new Square(' ', 'g', 6), new Square('♞', 'g', 7), new Square(' ', 'g', 8) },

                    { new Square(' ', 'h', 1), new Square(' ', 'h', 2), new Square(' ', 'h', 3), new Square(' ', 'h', 4), new Square(' ', 'h', 5), new Square(' ', 'h', 6), new Square(' ', 'h', 7), new Square(' ', 'h', 8) }
                }
            };

            var whitePlayerMock = new Mock <Player>(Color.white)
            {
                CallBase = true
            };

            var blackPlayerMock = new Mock <Player>(Color.black)
            {
                CallBase = true
            };

            var gameMock =
                new Mock <BasicGame>(MockBehavior.Loose, board, whitePlayerMock.Object, blackPlayerMock.Object)
            {
                CallBase = true
            };

            game        = gameMock.Object;
            blackPlayer = blackPlayerMock.Object;
        }
Exemplo n.º 17
0
        private void validate(RankFile pieceCurrentPosition, RankFile pieceDesiredDestination)
        {
            BasicGame game = Player.Game;

            Chess.Game.Board board = game.Board;
            IPiece           piece = board[pieceCurrentPosition].Piece.Object;

            if (piece == null)
            {
                throw new InvalidMoveException($"There is no piece at the position {pieceCurrentPosition.ToString()}");
            }

            if (piece.CanMoveTo(board[pieceDesiredDestination]) == false)
            {
                throw new InvalidMoveException($"{piece.GetType().Name} at {pieceCurrentPosition.ToString()} cannot move to {pieceDesiredDestination.ToString()}");
            }

            if (Player.Pieces.Contains(piece) == false)
            {
                throw new InvalidMoveException($"{piece.GetType().Name} at {pieceCurrentPosition.ToString()} does not belong to {Player.Name}");
            }
        }
Exemplo n.º 18
0
    private IEnumerator ExampleParser(bool run, TextAsset example, string examplesPath)
    {
        if (example.name.Contains("lvl"))
        {
            //Debug.Log(">>> SKIPPING: "+example.name);
            yield return(null);

            yield break;
        }

        Debug.Log(">>> PARSING: " + example.name);
        yield return(null);

        try
        {
            currentGame = parseGameFromString(example.text);
        }
        catch (Exception e)
        {
            parserTestErrors++;
            Debug.LogException(e);
            Debug.LogWarning("PARSER TESTS FAILED: " + parserTestErrors);

            //StopCoroutine("parserTest");
            //Debug.Break();

            yield break;
        }

        for (int i = 0; i < 5; i++)
        {
            var levelString = Path.Combine(examplesPath, example.name);
            levelString += "_lvl" + i;

            Debug.Log(">>> PARSING LEVEL: " + levelString);
            yield return(null);

            try
            {
                currentGame.buildLevelFromFile(levelString);
            }
            catch (Exception e)
            {
                parserTestErrors++;
                Debug.LogException(e);
                Debug.LogWarning("PARSER TESTS FAILED: " + parserTestErrors);

                //StopCoroutine("parserTest");
                //Debug.Break();

                continue;
            }

            if (run)
            {
                Debug.Log(">>> RUNNING LEVEL: " + levelString);
                yield return(RunGameRandomly(currentGame));

                currentGame.reset();
                currentGame = parseGameFromString(example.text);
            }
            else
            {
                yield return(new WaitForEndOfFrame());
            }
        }

        yield return(new WaitForEndOfFrame());
    }
Exemplo n.º 19
0
    /// <summary>
    /// Parse interaction set
    /// </summary>
    /// <param name="game"></param>
    /// <param name="childChildren"></param>
    /// <exception cref="ArgumentException"></exception>
    private static void parseInteractions(BasicGame game, IEnumerable <VGDLNode> childChildren)
    {
        foreach (var node in childChildren)
        {
            if (!node.content.Contains(">"))
            {
                throw new ArgumentException("Interaction error on line: " + node.lineNumber +
                                            "\nInteraction should be in the form [sprite1 sprite2 etc. > SomeInteraction paramX=5 etc.]");
            }

            if (verbose)
            {
                Debug.Log("Parsing interaction: " + node.content + "\nLine: " + node.lineNumber);
            }

            var interaction = node.content.Split(new [] { '>' }, StringSplitOptions.RemoveEmptyEntries);

            var effectTypeAndArgs = parseArgs(interaction[1]);

            var colliders = interaction[0].Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            //Check for TIME effects
            if (interaction[0].ToUpper().Contains("TIME"))
            {
                if (verbose)
                {
                    var parameters = string.Join(",", effectTypeAndArgs.args.Select(item => item.ToString()).ToArray());
                    Debug.Log("Defining Time Effect > " + effectTypeAndArgs.sclass + " with parameters (" + parameters + ")");
                }

                try
                {
                    var timeEffect  = CreateInstance <VGDLTimeEffect>("VGDLTimeEffect", effectTypeAndArgs.args, true);
                    var innerEffect = CreateInstance <VGDLEffect>(effectTypeAndArgs, true);
                    timeEffect.effectDelegate = innerEffect;

                    if (colliders[0].CompareAndIgnoreCase("TIME"))
                    {
                        var i = 1;
                        while (colliders.Length > i && string.IsNullOrEmpty(colliders[i]))
                        {
                            //Nothing, just skipping empty spaces
                            i++;
                        }

                        if (colliders.Length > i)
                        {
                            timeEffect.targetType = colliders[i].Trim();
                        }
                    }
                    else
                    {
                        timeEffect.targetType = colliders[0].Trim();
                    }

                    timeEffect.Validate(game);
                    game.addTimeEffect(timeEffect);

                    if (timeEffect.is_stochastic)
                    {
                        game.setStochastic(true);
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("TimeEffect type [" + effectTypeAndArgs.sclass +
                                   "] not found, verify it is spelled correctly, the system is case-sensitive");
                    throw;
                }

                //If a TIME effect was defined it should not also be defined as a collision.
                continue;
            }

            if (colliders.Length < 2)
            {
                throw new ArgumentException("Not enough colliders for interaction error on line: " + node.lineNumber +
                                            "\nInteraction should be in the form [sprite1 sprite2 (sprite3...) > SomeEffect paramX=5 etc.]" +
                                            "\nAlternative effects are [TIME > SomeTimeEffect etc. ]" +
                                            "\nor [sprite1 TIME > SomeEffect paramX=5 etc.]" +
                                            "\nor [EOS sprite1 (sprite2...)] > SomeEffect etc." +
                                            "\nor [sprite1 EOS (sprite2...)] > SomeEffect etc.");
            }

            VGDLEffect effect;
            try
            {
                //Hack to accomodate addTimer
                if (effectTypeAndArgs.sclass.CompareAndIgnoreCase("addTimer"))
                {
                    var timeEffect = CreateInstance <VGDLTimeEffect>(effectTypeAndArgs, true);
                    timeEffect.Validate(game);
                    var innerEffect = CreateInstance <VGDLEffect>(effectTypeAndArgs.args["ftype"], effectTypeAndArgs.args, true);
                    timeEffect.effectDelegate = innerEffect;
                    timeEffect.isNative       = false;

                    //Target type can be set explicitly as a parameter to addTimer.
                    //timeEffect.targetType

                    effect = timeEffect;

                    if (verbose)
                    {
                        Debug.Log("Defining addTimer effect with delegated effect [" + effectTypeAndArgs.args["ftype"] + "]");
                    }
                }
                else
                {
                    effect = CreateInstance <VGDLEffect>(effectTypeAndArgs);
                    effect.Validate(game);
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Effect type [" + effectTypeAndArgs.sclass +
                               "] not found, verify it is spelled correctly, the system is case-sensitive");
                throw;
            }

            if (verbose)
            {
                Debug.Log("Adding collision [" + interaction[0] + "] effect (" + interaction[1] + ")");
            }

            var obj1 = colliders[0];

            for (var index = 1; index < colliders.Length; index++)
            {
                var obj2 = colliders[index];

                if (obj1.CompareAndIgnoreCase("EOS"))
                {
                    game.addEosEffect(obj2, effect);
                }
                else if (obj2.CompareAndIgnoreCase("EOS"))
                {
                    game.addEosEffect(obj1, effect);
                }
                else
                {
                    game.addCollisionEffect(obj1, obj2, effect);
                }

                if (verbose)
                {
                    var parameters = string.Join(",", effectTypeAndArgs.args.Select(item => item.ToString()).ToArray());
                    Debug.Log("Defining interaction " + obj1 + " + " + obj2 + " > " + effectTypeAndArgs.sclass + " with parameters (" + parameters + ")");
                }

                if (effect.is_stochastic)
                {
                    game.setStochastic(true);
                }
            }
        }
    }
Exemplo n.º 20
0
    /// <summary>
    /// Parse sprite set
    /// </summary>
    /// <param name="game"></param>
    /// <param name="childChildren"></param>
    /// <param name="parentClass"></param>
    /// <param name="parentArgs"></param>
    /// <param name="parentKeys"></param>
    /// <exception cref="ArgumentException"></exception>
    private static void parseSprites(BasicGame game, IEnumerable <VGDLNode> childChildren, string parentClass = null, Dictionary <string, string> parentArgs = null, List <string> parentKeys = null)
    {
        foreach (var node in childChildren)
        {
            if (!node.content.Contains(">"))
            {
                throw new ArgumentException("Sprite error on line: " + node.lineNumber +
                                            "\nSprite def should be in the form: spriteName > (SomeSpriteType paramX=5 etc.)");
            }

            if (verbose)
            {
                Debug.Log("Parsing sprite from: " + node.content + "\nLine: " + node.lineNumber);
            }

            List <string> stypes;
            if (parentKeys == null)
            {
                stypes = new List <string>();
            }
            else
            {
                stypes = new List <string>(parentKeys);
            }

            var spriteDef = node.content.Split('>');

            var key  = spriteDef[0].Trim();
            var sdef = spriteDef[1].Trim();

            if (verbose && parentClass != null)
            {
                var parameters = string.Join(",", parentArgs.Select(item => item.ToString()).ToArray());
                Debug.Log(key + " parentClass " + parentClass + " and arguments (" + parameters + ")");
            }

            var typeAndArgs = parseArgs(sdef, parentClass, parentArgs);

            stypes.Add(key);

            //Leaf types update subtypes of all parent types.
            game.updateSubTypes(stypes, key);

            //NOTE: ignoring singletons for now, only reason for it to exist
            //is to keep the designer from spawning multiple of them.
            //And the only function that sounds like it would use it in the JAVA framework,
            //doesn't actually check it (TransformToSingleton),
            //even the sprite defs in the only game that uses it don't set the singleton parameter.
            //eg. singleton parameter is overhead that no one uses.

            if (node.children.Any())
            {
                //Add the type unless it's an abstract type (eg. has no class definition)
                if (!string.IsNullOrEmpty(typeAndArgs.sclass))
                {
                    if (verbose)
                    {
                        var parameters = string.Join(",", typeAndArgs.args.Select(item => item.ToString()).ToArray());
                        Debug.LogFormat("Defining: {0} as type {1} with parameters ({2}) and parsing it's subtree!", key, typeAndArgs.sclass, parameters);
                    }

                    var spriteInfo = new VGDLSpriteInfo(key, typeAndArgs.sclass, typeAndArgs.args, stypes);
                    game.registerSpriteConstructor(key, spriteInfo);

                    game.addOrUpdateKeyInSpriteOrder(key);
                }


                parseSprites(game, node.children, typeAndArgs.sclass, typeAndArgs.args, stypes);
            }
            else //leaf node
            {
                if (verbose)
                {
                    var parameters = string.Join(",", typeAndArgs.args.Select(item => item.ToString()).ToArray());
                    Debug.LogFormat("Defining: {0} as type {1} with parameters ({2})", key, typeAndArgs.sclass, parameters);
                }

                var spriteInfo = new VGDLSpriteInfo(key, typeAndArgs.sclass, typeAndArgs.args, stypes);
                game.registerSpriteConstructor(key, spriteInfo);

                game.addOrUpdateKeyInSpriteOrder(key);
            }
        }
    }
Exemplo n.º 21
0
    private IEnumerator RunGameRandomly(BasicGame game)
    {
        var agents = new VGDLPlayerInterface[game.no_players];

        for (int i = 0; i < agents.Length; i++)
        {
            agents[i] = new VGDLRandomAgent();
        }

        game.prepareGame(agents);


        var ended = false;

        var stepsUntilRendering = 1;

        while (!ended && game.getGameTick() < maxSteps)
        {
            try
            {
                game.updateGameState();
            }
            catch (Exception e)
            {
                parserTestErrors++;
                Debug.LogException(e);
                Debug.LogWarning("PARSER TESTS FAILED: " + parserTestErrors);

                //StopCoroutine("parserTest");
                //Debug.Break();
                break;
            }

            if (stepsUntilRendering <= 0)
            {
                shouldRender        = true;
                stepsUntilRendering = StepsBetweenRendering;
                yield return(null);
            }

            stepsUntilRendering--;

            if (!game.isEnded)
            {
                continue;
            }

            ended = true;

            var scores = game.handleResult();

            Debug.Log("GAME OVER!\n" + (game.gameResult.playerOutcomes[0] == VGDLPlayerOutcomes.PLAYER_WINS ? "YOU WON!" : "YOU LOST!") + " Score: " + game.gameResult.playerScores[0]);
        }

        if (game.getGameTick() >= maxSteps)
        {
            Debug.Log("TIMEOUT!\n");
        }

        yield return(null);
    }
Exemplo n.º 22
0
 public JoinCommand(BasicGame game)
 {
     this.game = game;
 }
Exemplo n.º 23
0
    static void Main()
    {
        BasicGame game = new BasicGame();

        game.Run();
    }
Exemplo n.º 24
0
    private void loadLevelFromExampleString(BasicGame game, string example, int level)
    {
        var exampleLevelStr = Path.Combine("Assets", Path.Combine("vgdl", Path.Combine("examples", example))) + "_lvl" + level + ".txt";

        game.buildLevelFromFile(exampleLevelStr);
    }
Exemplo n.º 25
0
 public TemporaryGame(BasicGame other) :
     base(other)
 {
 }
Exemplo n.º 26
0
 public LeaveCommand(BasicGame game)
 {
     this.game = game;
 }
Exemplo n.º 27
0
    public static VGDLGame LoadGame(VGDLGameAndLevel gameToLoad, bool loadLevelsFromGameTree = false)
    {
        var       exampleToLoad = "";
        BasicGame game          = null;

        switch (gameToLoad.type)
        {
        case VGDLExampleTypes.Unspecified:
            exampleToLoad += gameToLoad.filename;
            //File.ReadAllText
            break;

        case VGDLExampleTypes.GridPhysics:
            exampleToLoad += Path.Combine("gridphysics", gameToLoad.filename);
            game           = LoadFromExampleString(exampleToLoad, loadLevelsFromGameTree);
            break;

        case VGDLExampleTypes.ContinuousPhysics:
            exampleToLoad += Path.Combine("contphysics", gameToLoad.filename);
            game           = LoadFromExampleString(exampleToLoad, loadLevelsFromGameTree);
            break;

        case VGDLExampleTypes.TwoPlayer:
            exampleToLoad += Path.Combine("2player", gameToLoad.filename);
            game           = LoadFromExampleString(exampleToLoad, loadLevelsFromGameTree);
            break;

        default:
            throw new ArgumentOutOfRangeException();
        }

        //NOTE: Something went wrong
        if (game == null)
        {
            return(null);
        }

        game.name = exampleToLoad;

        if (loadLevelsFromGameTree)
        {
            if (game.levelList.Count > gameToLoad.level)
            {
                game.buildLevelFromLines(game.levelList[gameToLoad.level]);
            }
            else
            {
                Debug.LogError("Level " + gameToLoad.level + " not defined (levels are indexed from Zero)");
            }
        }
        else
        {
            if (gameToLoad.type == VGDLExampleTypes.Unspecified)
            {
                //NOTE: we expect the levels to be located next to the game specification and named filename_lvl[#level].txt
                LoadLevelFromFile(game, gameToLoad.filename + "_lvl" + gameToLoad.level + ".txt");
            }
            else
            {
                LoadLevelFromExampleString(game, exampleToLoad, gameToLoad.level);
            }
        }

        return(game);
    }
Exemplo n.º 28
0
        public object Run(Platform machine)
        {
            try
            {
                // Lecture du fichier xml de la plateforme (verbatim)
                UpdateStatus?.Invoke(this, "Get infos from platform");


                //var srcPlatform = XML_Platforms.Read(_SelectedPlatformXML);
                //string platformName = XML_Platforms.GetByTag(srcPlatform.Element("Platform"), "Name") as string;

                // L'objet n'est utilisé que pour avoir des données, il ne sert pas pour l'écriture


                if (machine.PlatformFolders.Count < 1)
                {
                    UpdateStatus?.Invoke(this, "Error: this machine has no path");
                    return(false);
                }

                // Travail sur le fichier des plateformes
                string platformsFile = Path.Combine(PS.Default.LastLBpath, PS.Default.fPlatforms);
                WorkOnPlatformFile(platformsFile, machine.Name);

                // Backup datas
                string xmlPlateforme = Path.Combine(PS.Default.LastLBpath, PS.Default.dPlatforms, $"{machine.Name}.xml");
                if (File.Exists(xmlPlateforme))
                {
                    BackupPlatformFile(xmlPlateforme);
                    UpdateStatus?.Invoke(this, $"Backup of '{xmlPlateforme}'");
                }


                // --- Initialisation des dossiers cible
                string root = Path.GetDirectoryName(Path.GetDirectoryName(machine.FolderPath));
                InitTargetPaths(machine, root);


                int done = 0;
                int i    = 0;
                foreach (Cont.FileObj game in Games)
                {
                    UpdateProgressT?.Invoke(this, i);

                    UpdateStatus?.Invoke(this, $"Work on: {game.Nom}");

                    string gameName = Path.GetFileNameWithoutExtension(game.Nom);
                    string tmpPath  = Path.Combine(Config.Folder, Path.GetFileNameWithoutExtension(game.Nom));

                    // Décompression
                    if (Path.GetExtension(game.Path).Equals(".zip", StringComparison.OrdinalIgnoreCase))
                    {
                        ZipDecompression.UnCompressArchive(game.Path, tmpPath, CancelToken);
                    }

                    if (CancelToken.IsCancellationRequested)
                    {
                        UpdateStatus?.Invoke(this, "Stopped by user");
                        return(false);
                    }


                    // Chargement des données du jeu
                    string   xmlFile      = Path.Combine(tmpPath, "TBGame.xml");
                    XElement verbatimGame = XML_Games.GetGameNode(xmlFile);

                    BasicGame baseGame = XML_Games.Scrap_BasicGame <BasicGame>(verbatimGame);
#if DEBUG
                    baseGame.Platform = "Sega Genesis";
#endif

                    /*
                     * string gameTitle = XML_Games.GetByTag(verbatimGame, "Title");
                     * UpdateStatus?.Invoke(this, $"Game Title: {gameTitle}");
                     *
                     * string platformGame = XML_Games.GetByTag(verbatimGame, "Platform");
                     * UpdateStatus?.Invoke(this, $"Game for {platformGame}");
                     *
                     * string gameID = XML_Games.GetByTag(verbatimGame, "ID");
                     * UpdateStatus?.Invoke(this, $"GameId: {gameID}");*/



                    // Test pour vérifier si ce sont les mêmes plateformes
                    if (!machine.Name.Equals(baseGame.Platform))
                    {
                        UpdateStatus?.Invoke(this, $"Aborded, wrong plateforme '{game.Nom}'");
                        i++;
                        UpdateProgressT?.Invoke(this, i);
                        continue;
                    }

                    // Copies
                    //Copy_Images(Path.Combine(tmpPath, PS.Default.Images), TImagesP);


                    // Copie et modifie
                    ManageFiles(verbatimGame, tmpPath, Cst.ManualP);

                    //Copy_TBManager(tmpPath);

                    WorkOnGamesFile(xmlPlateforme, verbatimGame, xmlFile, baseGame);


                    // Effacer le dossier temporaire
                    Delete(tmpPath);

                    //i++;
                    UpdateProgress?.Invoke(this, 100);
                    UpdateStatus?.Invoke(this, "Game Finished");

                    done++;
                }

                UpdateStatus?.Invoke(this, $"Number of games processed: {done}/{Games.Count()}");

                return(true);
            }
            catch (Exception exc)
            {
                return(false);
            }
        }
Exemplo n.º 29
0
 private static void LoadLevelFromFile(BasicGame game, string filename)
 {
     game.buildLevelFromFile(filename);
 }
Exemplo n.º 30
0
 public StartCommand(BasicGame game)
 {
     this.game = game;
 }
Exemplo n.º 31
0
        /// <summary>
        /// Travaille sur le fichier de sortie pour injecter
        /// </summary>
        /// <param name="xmlPlateforme"></param>
        /// <param name="baseGame"></param>
        private void WorkOnGamesFile(string xmlPlateforme, XElement verbatimGame, string xmlSrcFile, BasicGame baseGame)
        {
            // Travail sur le fichier de plateforme
            using (XML_Games xGame = new XML_Games(xmlPlateforme))
            {
                bool?replace = false;
                if (xGame.Exists("ID", baseGame.Id))
                {
                    replace = AskDxMBox("Game is Already present, replace it (or duplicate) ?", "Question", E_DxButtons.Yes | E_DxButtons.No, baseGame.Title);
                }

                if (replace == true)
                {
                    UpdateStatus?.Invoke(this, $"Removing game: {baseGame.Title}");
                    xGame.RemoveByChild(Cst.Game, Cst.Id, baseGame.Id);

                    UpdateStatus?.Invoke(this, $"Removing AdditionnalApps: {baseGame.Title}");
                    xGame.RemoveByChild(Cst.AddApp, Cst.GameId, baseGame.Id);

                    UpdateStatus?.Invoke(this, $"Removing CustomFields: {baseGame.Title}");
                    xGame.RemoveByChild(Cst.CustField, Cst.GameId, baseGame.Id);

                    UpdateStatus?.Invoke(this, $"Removing AlternateNames");
                    xGame.RemoveByChild(Cst.AltName, Cst.GameId, baseGame.Id);
                }

                // Injection
                UpdateStatus?.Invoke(this, $"Inject game");
                xGame.InjectGame(verbatimGame);
                UpdateStatus?.Invoke(this, $"Inject additionnal applications");
                xGame.InjectAddApps(XML_Games.GetNodes(xmlSrcFile, Cst.AddApp));
                UpdateStatus?.Invoke(this, $"Inject custom fields");
                xGame.InjectCustomF(XML_Games.GetNodes(xmlSrcFile, Cst.CustField));

                /*XML_Games.InjectAddApps(clones, machineXMLFile);
                 * if (PS.Default.wCustomFields)
                 * {
                 *  //var r = XML_Games.ListCustomFields(xmlFile, "CustomField");
                 *  XML_Games.Trans_CustomF(xmlFile, machineXMLFile);
                 * }*/

                //XML_Games.Remove_Game(lbGame.Id, machineXMLFile);
            }
        }