public static Game CreateGame() { int id = 0; while (Games.Exists(game => game.GameId == id)) { id = Random.Next(0, 10); } Game createdGame = new Game(id); Obstacle cube = ObstacleFactory.getPrototype("Cube").Clone(); cube.SetPosition(new Point(Random.Next(0, 600), Random.Next(200, 300))); Obstacle circle = ObstacleFactory.getPrototype("Circle").Clone(); circle.SetPosition(new Point(Random.Next(0, 600), Random.Next(200, 300))); Obstacle rectangle = ObstacleFactory.getPrototype("Rectangle").Clone(); rectangle.SetMovement(new DiagonalMovement(50, 500)); rectangle.SetPosition(new Point(Random.Next(99, 100), Random.Next(10, 30))); createdGame.Obstacles.Add(cube); cube.SetId(createdGame.Obstacles.Count); createdGame.Obstacles.Add(rectangle); rectangle.SetId(createdGame.Obstacles.Count); createdGame.Obstacles.Add(circle); circle.SetId(createdGame.Obstacles.Count); Games.Add(createdGame); return(createdGame); }
void Start() { blockFactory = new BlockFactory(this, gameWeights, levelContainer); obstacleFactory = new ObstacleFactory(this, gameWeights); cookieFactory = new CookieFactory(this, gameWeights); CreateInitWalls(); }
public Obstacle SpawnObstacle(int value) { if (value == NumberOfFactories) { throw new Exception("Bad index"); } Obstacle obstacle = null; switch (value) { case 0: { _obstacleFactory = new SpikeFactory(); obstacle = _obstacleFactory.GetObstacle(); break; } case 1: { _obstacleFactory = new PitFactory(); obstacle = _obstacleFactory.GetObstacle(); break; } } return(obstacle); }
public void Initialize(float lvlSpeed) { tilePool = FindObjectOfType <RoadTilePool>(); obstacleFactory = FindObjectOfType <ObstacleFactory>(); moveForward = FindObjectOfType <MoveForward>(); speed = lvlSpeed; }
private void Awake() { GameObject engine = GameObject.FindGameObjectWithTag("Engine"); obstacleFactory = engine.GetComponent <ObstacleFactory>(); this.engine = engine.GetComponent <Engine>(); healthBar.maxHealth = maxHp; }
/// <summary> /// Adds a specified number of obstacles to the lane of a specified obstacle type, then /// readjusts their X coordinate spacing accordingly. /// Precondition: none /// Post-condition: this.obstacles.Count == numberOfObstacles /// @each obstacle.X is spaced accordingly on lane /// </summary> /// <param name="obstacleType">Type of the obstacle.</param> /// <param name="maxNumberObstacles">The max number of obstacles.</param> public virtual void AddObstacles(ObstacleType obstacleType, int maxNumberObstacles) { for (var i = 0; i < maxNumberObstacles; i++) { this.add(ObstacleFactory.CreateObstacle(obstacleType)); } this.Obstacles.ToList().ForEach(obstacle => obstacle.Direction = this.direction); }
public LevelGenerator(TreadmillBehaviour treadmill) { this.factory = new ObstacleFactory (); this.treadmill = treadmill; this.pendingObstacles = new Queue (); this.rnd = new System.Random (); }
void Start() { //! Because the Unity Engine does not allow Interfaces to be assigned from Inspector we are using a factory to get the Strategies for our obstacle behaviour //! Therefore, it's not the best solution but it still gives more flexibility and reduce coupling ObstacleBehaviour = ObstacleFactory.GetObstacle(ObstacleType); ObstacleBehaviour.SetDoor(GetChildrenWithTag(DoorTag)); _player = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerController>(); _enemy = GameObject.FindGameObjectWithTag("Enemy").GetComponent <EnemyController>(); }
public CombatFactory(LunchHourGames lhg, LoadingProgress progress, PlayerFactory playerFactory, ObstacleFactory obstacleFactory, StageFactory stageFactory, InventoryFactory inventoryFactory) { this.lhg = lhg; this.progress = progress; this.playerFactory = playerFactory; this.obstacleFactory = obstacleFactory; this.stageFactory = stageFactory; this.inventoryFactory = inventoryFactory; }
/// <summary> /// Generates a curve /// </summary> /// <param name="renderPipes">Generate a pipe too</param> public void Create(bool renderPipes) { InitializeData(renderPipes); SetVertices(); SetTriangles(); mesh.RecalculateNormals(); AlignCurveBasePoints(); obstacleFactory = this.gameObject.AddComponent <ObstacleFactory>(); obstacleFactory.SetCurve(this); }
private void LoadTiles(int x, int y) { ObstacleFactory destroyableFactory = FactoryPicker.GetFactory("Destroyable"); ObstacleFactory undestroyableFactory = FactoryPicker.GetFactory("Undestroyable"); var index = 0; for (int i = y; i < height; i++) { for (int j = x; j < width; j++) { int texture = 2; // Default ground tile // If we launch the game and map is not big enough it will throw an npe XD switch (map[i, j]) { // Destructible Obstacles case "B": obstacles.Add(destroyableFactory.GetDestroyable("BrickWall")); break; case "C": obstacles.Add(destroyableFactory.GetDestroyable("Crate")); break; // Undestructible Obstacles case "O": obstacles.Add(undestroyableFactory.GetUndestroyable("Obsidian")); break; case "S": obstacles.Add(undestroyableFactory.GetUndestroyable("Stone")); break; default: if (int.TryParse(map[i, j], out texture)) { obstacles.Add(null); } else { throw new ArgumentException($"Map tile {map[i, j]} does not map to any object."); } break; } // We add a ground tile every time tiles.Add(new Ground(texture)); //_compoundTile.Add(obstacles[index] == null ? tiles[index] : obstacles[index]); } } }
public void GenerateMap(Level newLevel) { deleteCurrentMap(); Map map = new Map(newLevel); navigation = GetComponent <Navigation>(); navigation.setup(map.config, tileSize, mapHolder, maxMapSize); obstacleFactory = GetComponent <ObstacleFactory>(); tileMap = obstacleFactory.placeGroundTiles(map, mapHolder, outlinePercent, tileSize); List <Coord> CoordsWithObstacle = obstacleFactory.placeObstacles(map, mapHolder, outlinePercent, tileSize); map.markCoordAsOccupiedByObstacle(CoordsWithObstacle); map.shuffleFreeCoords(); generatedMap = map; }
/// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { loadingScreen = new LoadingScreen(lhg); inventoryFactory = new InventoryFactory(lhg, loadingScreen); playerFactory = new PlayerFactory(lhg, loadingScreen, inventoryFactory); obstacleFactory = new ObstacleFactory(lhg, loadingScreen); stageFactory = new StageFactory(lhg, loadingScreen); combatFactory = new CombatFactory(lhg, loadingScreen, playerFactory, obstacleFactory, stageFactory, inventoryFactory); showCombatLoading("combat1"); //showControlsTestScreen(); base.Initialize(); }
public override bool UpdateNodes(TrinityGrid grid, Structures.Avoidance avoidance) { var actor = Core.Actors.RactorByRactorId <TrinityActor>(avoidance.RActorId); if (actor == null || !actor.IsValid) { return(false); } CleanUpRotators(); var part = avoidance.Definition.GetPart(actor.ActorSnoId); if (part?.MovementType == MovementType.Rotation) { Rotator rotator; if (!_rotators.TryGetValue(actor.RActorId, out rotator)) { rotator = CreateNewRotator(actor); _rotators.Add(actor.RActorId, rotator); Task.FromResult(rotator.Rotate()); } var centerNodes = grid.GetNodesInRadius(actor.Position, 8f); var radAngle = MathUtil.ToRadians(rotator.Angle); var nodes = grid.GetRayLineAsNodes(actor.Position, MathEx.GetPointAt(actor.Position, 28f, radAngle)).SelectMany(n => n.AdjacentNodes).ToList(); var futureRadAngle = MathUtil.ToRadians((float)rotator.GetFutureAngle(TimeSpan.FromMilliseconds(500))); nodes.AddRange(grid.GetRayLineAsNodes(actor.Position, MathEx.GetPointAt(actor.Position, 28f, futureRadAngle)).SelectMany(n => n.AdjacentNodes)); nodes.AddRange(centerNodes); nodes = nodes.Distinct().ToList(); const int defaultWeightModification = 32; HandleNavigationGrid(grid, nodes, avoidance, actor, 0f, defaultWeightModification); } else { var telegraphNodes = grid.GetNodesInRadius(actor.Position, 12f); const int defaultWeightModification = 12; HandleNavigationGrid(grid, telegraphNodes, avoidance, actor, 0f, defaultWeightModification); } Core.DBGridProvider.AddCellWeightingObstacle(actor.RActorId, ObstacleFactory.FromActor(actor)); return(true); }
public bool UpdateNodes(TrinityGrid grid, Structures.Avoidance avoidance) { var actor = Core.Actors.RactorByRactorId <TrinityActor>(avoidance.RActorId); if (actor == null || !actor.IsValid) { return(false); } var fireChainFriendList = Core.Avoidance.CurrentAvoidances.Where(c => c != avoidance && c.ActorSno == avoidance.ActorSno) .ToList(); var appliedAvoidanceNode = false; foreach (var fireChainFriend in fireChainFriendList) { var friend = Core.Actors.RactorByRactorId <TrinityActor>(fireChainFriend.RActorId); if (friend == null || !friend.IsValid) { continue; } var nodes = grid.GetRayLineAsNodes(actor.Position, friend.Position).SelectMany(n => n.AdjacentNodes); AvoidanceFlags flags = AvoidanceFlags.Avoidance; int weightModification = BaseAvoidanceHandler.DefaultWeightModification; if (avoidance.Settings.Prioritize) { flags |= AvoidanceFlags.CriticalAvoidance; weightModification = BaseAvoidanceHandler.CriticalWeightModification; } grid.FlagAvoidanceNodes(nodes, flags, avoidance, weightModification); appliedAvoidanceNode = true; } if (appliedAvoidanceNode) { Core.DBGridProvider.AddCellWeightingObstacle(actor.RActorId, ObstacleFactory.FromActor(actor)); return(true); } return(false); }
protected void HandleNavigationGrid(AvoidanceFlags defaultFlags, TrinityGrid grid, IEnumerable <AvoidanceNode> nodes, Structures.Avoidance avoidance, TrinityActor actor, float radius, int normalWeightModificationOverride = 0) { AvoidanceFlags flags = defaultFlags; int weightModification = DefaultWeightModification; if (normalWeightModificationOverride != 0) { weightModification = normalWeightModificationOverride; } if (avoidance.Settings.Prioritize) { weightModification = CriticalWeightModification; flags |= AvoidanceFlags.CriticalAvoidance; } grid.FlagAvoidanceNodes(nodes, flags, avoidance, weightModification); Core.DBGridProvider.AddCellWeightingObstacle(actor.RActorId, ObstacleFactory.FromActor(actor, radius)); }
public Obstacle PerformSpawn() { #if DEBUG var screen = FlatRedBall.Screens.ScreenManager.CurrentScreen; LastTwoSpawnTimes[0] = LastTwoSpawnTimes[1]; LastTwoSpawnTimes[1] = screen.PauseAdjustedCurrentTime; SpawnRollingAverage.AddValue((float)(LastTwoSpawnTimes[1] - LastTwoSpawnTimes[0])); #endif var newObstacle = ObstacleFactory.CreateNew(); if (FlatRedBallServices.Random.Between(0, 1) < RatioOfGold) { newObstacle.CurrentBonusCategoryState = Obstacle.BonusCategory.Bonus; } int repositionsSoFar = 0; while (repositionsSoFar <= NumberOfTimesToRepositionCrates) { PositionNewObstacle(newObstacle); var distanceFromCenterOfPath = Math.Abs(newObstacle.X - pathX) - newObstacle.Width; bool isOnPath = distanceFromCenterOfPath < PathWidth / 2.0f; if (!isOnPath) { break; } repositionsSoFar++; } lastSpawnY = this.Y; return(newObstacle); }
private void Spawn() { if (SpawnIntervall == 0) { return; } StaticObstacle obstacle = new StaticObstacle(); switch (Level) { case 1: obstacle = ObstacleFactory.GetStaticObstacle(); break; case 2: obstacle = ObstacleFactory.GetStickyObstacle(); break; case 3: obstacle = ObstacleFactory.GetStaticOrStickyObstacle(); break; case 4: obstacle = ObstacleFactory.GetRandomObstacle(); break; case 5: obstacle = ObstacleFactory.GetRandomObstacle(); break; case 6: obstacle = ObstacleFactory.GetMovingOrStickyObstacle(); break; } obstacle.Position = new Vector2(JamGame.ScreenWidth, ConveyorHitBox.Position.Y - ConveyorHitBox.Size.Height - obstacle.Hitbox.Height); Components.Add(obstacle); }
public override void _Ready() { rf = (RocketFactory)GetChild(0); of = (ObstacleFactory)GetChild(1); tf = (TargetFactory)GetChild(2); rockets = rf.createPopulation(References.populationSize); obstacles = of.createPopulation(References.obstaclePopulationSize); target = tf.createTarget(); populationDead = false; time = 0; maxFitnessAchieved = 0; for (int i = 0; i < rockets.Length; i++) { rockets[i].SetTarget(target); } genePool = new List <Instruction[]>(); fitnessHistory = new List <string>(); infoText = (RichTextLabel)GetNode("/root/MainScene/UI/InfoText"); }
private void Awake() { if (Instance != null) return; Instance = this; }
// Start is called before the first frame update void Start() { factory = new ObstacleFactory(); InvokeRepeating("SpawnObject", spawnTime, spawnDelay); }
// Singleton done // Factory done // Strategy done // Observer done // Adapter done // Decorator done // Facade done // Command done // Template Method - zaidimo temos // State - zaidimo busena // Proxy - // Iterator, Composite, Flyweight // Chain of Responsibility // Null Object - score null // Memento - restart/resume game // Visitor - when enemies die, they visit visitor // Interpreter - custom game mod public Form1() { InitializeComponent(); instance = this; //Singleton and Adapter logger.LogMessage("Adapter Works!"); guiLogger.LogMessage("Gui Logger Works!"); pacman = new Classes.Pacman(false); MoveDown moveDown = new MoveDown(pacman); MoveUp moveUp = new MoveUp(pacman); MoveLeft moveLeft = new MoveLeft(pacman); MoveRight moveRight = new MoveRight(pacman); //Command pacman.Move(moveDown); pacman.Move(moveUp); pacman.Move(moveLeft); pacman.Move(moveRight); //Strategy Enemy enemy = new Enemy(new AiAmbusher()); enemy.SelectStrategy(); enemy.strategy = new AiRandom(); enemy.SelectStrategy(); //Observer pacman.Attach(enemy); pacman.State = true; //Abstract factory AbstractFactory candyFactory = new CandyFactory(); ICandy candy1 = candyFactory.GetCandy("small"); candy1.CreateCandy(); ICandy candy2 = candyFactory.GetCandy("big"); candy2.CreateCandy(); ICandy candy3 = candyFactory.GetCandy("cherry"); candy3.CreateCandy(); ICandy candy4 = candyFactory.GetCandy("BANANA"); candy4.CreateCandy(); AbstractFactory colorFactory = new ColorFactory(); IColor color1 = colorFactory.GetColor("yellow"); color1.CreateColor(); IColor color2 = colorFactory.GetColor("red"); color2.CreateColor(); //Facade FoodFacade food = new FoodFacade(); food.CreateRedCherry(); food.CreateRedSmall(); food.CreateYellowBanana(); food.CreateYellowBig(); //Decorator with Template Method pacman.weapon = new Gun(); Debug.WriteLine(pacman.weapon.Shoot()); pacman.weapon = new Cannon(pacman.weapon); Debug.WriteLine(pacman.weapon.Shoot()); pacman.weapon = new SpeedTrap(pacman.weapon); Debug.WriteLine(pacman.weapon.Shoot()); // State // Changes game state from resumed to paused and vice versa StateContext stateContext = new StateContext(); StateResumed stateResumed = new StateResumed(); StatePaused statePaused = new StatePaused(); stateResumed.Handle(stateContext); Console.WriteLine(stateContext.GetState().GetString()); statePaused.Handle(stateContext); Console.WriteLine(stateContext.GetState().GetString()); // Proxy // Loads background image for gameboard IBackgroundImage image = new ProxyBackgroundImage("Background1.jpg"); image.Display(); Console.WriteLine(""); // Image will not be loaded from disk again image.Display(); // Flyweight // Pattern used to generate obstacles based on their length for (int i = 0; i < 8; i++) { //Creating duplicate objects Obstacle obs = ObstacleFactory.GetObstacle(i < 4 ? i : i / 2); obs.SetX(4); obs.SetY(4); obs.SetRotation(0); obs.Draw(); } // Chain of responsibility // For handling scores AllScoresHandler handler1 = new NullObject(); AllScoresHandler handler2 = new BonusHandler(); AllScoresHandler handler3 = new PointsHandler(); handler1.SetNextHandler(handler2); handler2.SetNextHandler(handler3); int[] points = { 0, 15, 5, 10, -5, 16, 18, 0, 0, 13, 1, 2, 3 }; foreach (int point in points) { handler1.HandleScore(point); } Console.WriteLine("Final points: " + Highscore.Instance.score); // Mediator // Implemented chatroom Chatroom chatroom = new Chatroom(); Participant player = new Participant("Player"); Participant spectator1 = new Participant("Spectator1"); Participant spectator2 = new Participant("Spectator2"); chatroom.Register(player); chatroom.Register(spectator1); chatroom.Register(spectator2); player.Send("Spectator1", "Hello, spectator!"); spectator1.Send("Player", "Hello, player!"); spectator2.Send("Player", "Hey, don't forget me!"); // Memento // Saving player score for later use CareTaker careTaker = new CareTaker(); careTaker.Add(Highscore.Instance.SetMemento()); Console.WriteLine("Memento saved state: " + careTaker.Get(0).GetScore()); Highscore.Instance.score = 2222; careTaker.Add(Highscore.Instance.SetMemento()); Console.WriteLine("Memento saved state: " + careTaker.Get(1).GetScore()); Console.WriteLine("Restoring to first memento."); Highscore.Instance.SetMemento(careTaker.Get(0)); Console.WriteLine("Restored score is: " + Highscore.Instance.score); // Interpreter // Eating yellow banana will binary shift your score to the left and add 10 points to the result Console.WriteLine("Score before interpreter: " + Highscore.Instance.score); Counter originalCounter = new ConcreteCounter(Highscore.Instance.score); Counter bananaCounter = new ConcreteCounter(10); Counter counter = new ShiftCounter(bananaCounter, originalCounter); Highscore.Instance.score = counter.Count(); Console.WriteLine("Score before interpreter: " + Highscore.Instance.score); }