Пример #1
0
 public void Act()
 {
     if (TheWorld.Nearby())
     {
         DealDamage(inventory);
     }
 }
Пример #2
0
        /// <summary>
        /// Implementation of Fox-specific behavior. Note that this class is in
        /// control w.r.t. how the behavior is implemented. The implementation
        /// uses methods from the base class in a library-like manner.
        /// </summary>
        public override void Act()
        {
            // 1.priority: Eating
            if (Hungry && (TheWorld.NearBy(AnimalKind.rabbit) || TheWorld.NearBy(AnimalKind.mouse)))
            {
                Hunt();
                Eat();
            }

            // 2.priority: Mating (with Fox of opposite gender)
            else if (TheWorld.NearBy(AnimalKind.fox) && TheWorld.GenderOfNearBy(AnimalKind.fox) != Gender)
            {
                Mate();
            }

            // 3.priority: Fleeing
            else if (TheWorld.NearBy(AnimalKind.tiger))
            {
                Flee();
            }

            // 4.priority: Sleeping
            else if (Sleepy)
            {
                Sleep();
            }

            else
            {
                Idle();
            }
        }
Пример #3
0
        public override void Act()
        {
            // 1.priority: Eating
            if (IsEating())
            {
                Hunt();
                Eat();
            }

            // 2.priority: Mating (with Fox of opposite gender)
            else if (TheWorld.NearBy(Kind) && TheWorld.GenderOfNearBy(Kind) != Gender)
            {
                Mate();
            }

            // 3.priority: Fleeing
            else if (IsFleeing())
            {
                Flee();
            }

            // 4.priority: Sleeping
            else if (Sleepy)
            {
                Sleep();
            }

            else
            {
                Idle();
            }
        }
Пример #4
0
        public override void Act()
        {
            // 1.priority: Eating
            if (Hungry && (TheWorld.NearBy(AnimalKind.fox) || TheWorld.NearBy(AnimalKind.mouse) || TheWorld.NearBy(AnimalKind.rabbit)))
            {
                Hunt();
                Eat();
            }

            // 2.priority: Sleeping
            else if (Sleepy)
            {
                Sleep();
            }

            // 3.priority: Fleeing (from same-gender Tigers)
            else if (TheWorld.NearBy(AnimalKind.tiger) && TheWorld.GenderOfNearBy(AnimalKind.fox) == Gender)
            {
                Flee();
            }

            // 4.priority: Mating (with opposite-gender Tigers)
            // Thi is why Tigers are almost extinct...
            else if (TheWorld.NearBy(AnimalKind.tiger) && TheWorld.GenderOfNearBy(AnimalKind.fox) != Gender)
            {
                Mate();
            }

            else
            {
                Idle();
            }
        }
Пример #5
0
        public void Run()
        {
            Fox    aFox    = new Fox(AnimalGender.female);
            Mouse  aMouse  = new Mouse(AnimalGender.male);
            Rabbit aRabbit = new Rabbit(AnimalGender.male);
            Tiger  aTiger  = new Tiger(AnimalGender.female);

            AnimalBaseIoC anotherFox = new AnimalBaseIoC(
                AnimalKind.fox,
                AnimalGender.female,
                () => { return(TheWorld.NearBy(AnimalKind.rabbit) || TheWorld.NearBy(AnimalKind.mouse)); },
                () => { return(TheWorld.NearBy(AnimalKind.tiger)); }
                );


            List <AnimalBase> animals = new List <AnimalBase> {
                aFox, aMouse, aRabbit, aTiger
            };

            foreach (AnimalBase anAnimal in animals)
            {
                anAnimal.Live(PreAct, PostAct);
                Console.WriteLine();
            }
        }
Пример #6
0
        /// <summary>
        /// Runs a blocks physics update... when available!
        /// </summary>
        /// <param name="block">The block location.</param>
        private void PhysBlockAnnounce(Location block)
        {
            // The below code: Basically, if the block already has the needs_recalc flag,
            // it probably has a tick like this one waiting already, so let that one complete rather than starting another!
            if (((BlockFlags)SetNeedsRecalc(block, true).BlockLocalData).HasFlag(BlockFlags.NEEDS_RECALC))
            {
                return;
            }
            // The below code: So long as the server is unable to update faster than a specified update pace, don't bother updating this.
            // Once the server is updating at an acceptable pace, immediately perform the final update.
            // Also, this logic produces a minimum update delay of 0.25 seconds, and no maximum!
            // Meaning it could update a quarter second from now, or five years from nowhere, or whenever.
            Action calc = () =>
            {
                SurroundRunPhysics(block);
            };
            DataHolder <Action> a = new DataHolder <Action>()
            {
                Data = calc
            };

            a.Data = () =>
            {
                double cD = TheWorld.EstimateSpareDelta();
                if (cD > 0.25) // TODO: 0.25 -> CVar? "MinimumTickTime"?
                {
                    TheWorld.Schedule.ScheduleSyncTask(a.Data, 1.0);
                }
                else
                {
                    calc();
                }
            };
            TheWorld.Schedule.ScheduleSyncTask(a.Data, 0.25);
        }
Пример #7
0
        public override void Act()
        {
            // 1.priority: Fleeing
            if (TheWorld.NearBy(AnimalKind.fox) || TheWorld.NearBy(AnimalKind.rabbit))
            {
                Flee();
            }

            // 2.priority: Mating
            else if (TheWorld.NearBy(AnimalKind.mouse) && TheWorld.GenderOfNearBy(AnimalKind.mouse) != Gender)
            {
                Mate();
            }

            // 3.priority: Eating
            else if (Hungry)
            {
                Scavenge();
                Eat();
            }

            // 4.priority: Sleeping
            else if (Sleepy)
            {
                Sleep();
            }

            else
            {
                Idle();
            }
        }
Пример #8
0
        public Rabbit(AnimalGender gender) : base(AnimalKind.rabbit, gender)
        {
            IAnimalBehavior idleBehavior = new AnimalBehavior(this,
                                                              Idle,
                                                              () => true,
                                                              null);

            IAnimalBehavior prio4Behavior = new AnimalBehavior(this,
                                                               Sleep,
                                                               () => Sleepy,
                                                               idleBehavior);

            IAnimalBehavior prio3Behavior = new AnimalBehavior(this,
                                                               () =>
            {
                Scavenge();
                Eat();
            },
                                                               () => Hungry,
                                                               prio4Behavior);

            IAnimalBehavior prio2Behavior = new AnimalBehavior(this,
                                                               Flee,
                                                               () => TheWorld.NearBy(AnimalKind.tiger) ||
                                                               TheWorld.NearBy(AnimalKind.fox),
                                                               prio3Behavior);

            IAnimalBehavior prio1Behavior = new AnimalBehavior(this,
                                                               Mate,
                                                               () => TheWorld.NearBy(AnimalKind.rabbit),
                                                               prio2Behavior);

            Behavior = prio1Behavior;
        }
Пример #9
0
        public ServerCtrl(string filePath)
        {
            players       = new Dictionary <long, Tank>();
            playerSockets = new Dictionary <long, SocketState>();
            wallsSent     = false;
            SetDefaults();
            rand            = new Random();
            randPowerupTime = rand.Next(0, maxPowerupSpawnTime);
            projectileCount = 0;
            beamCount       = 0;
            powerUpTracker  = 0;
            powerUpID       = 0;
            projectileDelay = 0;
            turretAimx      = 0;
            turretAimy      = 0;
            working         = false;
            world           = new TheWorld(worldSize, 0);


            Load(filePath);
            Networking.StartServer(NewPlayer, 11000);
            Console.WriteLine("Server started");

            dataBaseView = new DataBaseView();


            Thread thread = new Thread(() => SendData());

            thread.Start();
        }
Пример #10
0
        public override void Because()
        {
            TheWarrior.WasAskedForRequest.ShouldBeFalse();
            TheWarrior.WasGivenResponse.ShouldBeFalse();

            TheWorld.StepForwardOneTimeUnit();
        }
    void ProcessMouseEvents()
    {
        GameObject selectedObj;
        Vector3    hitPoint;

        if (Input.GetMouseButtonDown(0)) // Click event
        {
            if (MouseSelectObjectAt(out selectedObj, out hitPoint, LayerMask.GetMask("Default")))
            {
                TheWorld.CreateBallAt(hitPoint);
                PosControl.SetSelectedObj(TheWorld.GetSelectedObject());
            }
        }
        else if (Input.GetMouseButton(0))                                   // Mouse Drag
        {
            if (MouseSelectObjectAt(out selectedObj, out hitPoint, 1 << 0)) // Notice the two ways of getting the mask
            {
                TheWorld.ResizeCreatedTo(hitPoint);
            }
        }
        else if (Input.GetMouseButtonUp(0))   // Mouse Release
        {
            TheWorld.EnableCreatedMotion();
        }

        if (Input.GetMouseButtonDown(1))                                    // RMB
        {
            if (MouseSelectObjectAt(out selectedObj, out hitPoint, 1 << 8)) // or LayerMask.GetMask("Spheres")
            {
                TheWorld.SetSelected(ref selectedObj);
                PosControl.SetSelectedObj(TheWorld.GetSelectedObject());
            }
        }
    }
Пример #12
0
        /// <summary>
        /// Serialize each object in the world and send to each client connection
        /// </summary>
        public static void SendWorld()
        {
            // string that is built for each frame
            StringBuilder jsonString = new StringBuilder();

            // loop through all of the object in the world to build the string.
            lock (TheWorld)
            {
                foreach (Ship ship in TheWorld.GetShipsAll())
                {
                    jsonString.Append(JsonConvert.SerializeObject(ship) + "\n");
                }
                foreach (Star star in TheWorld.GetStars())
                {
                    jsonString.Append(JsonConvert.SerializeObject(star) + "\n");
                }
                foreach (Projectile proj in TheWorld.GetProjectiles())
                {
                    jsonString.Append(JsonConvert.SerializeObject(proj) + "\n");
                }
            }
            // loop through all of the clients to send the string to.
            lock (TheWorld)
            {
                foreach (KeyValuePair <int, Client> c in ClientConnections)
                {
                    Client client = c.Value;
                    if (client.ss.theSocket.Connected)
                    {
                        Networking.NetworkController.Send(jsonString.ToString(), client.ss);
                    }
                }
            }
        }
Пример #13
0
        public override void Act()
        {
            // 1.priority: Mating
            // Rabbits, right...?
            if (TheWorld.NearBy(AnimalKind.rabbit))
            {
                Mate();
            }

            // 2.priority: Fleeing
            else if (TheWorld.NearBy(AnimalKind.tiger) || TheWorld.NearBy(AnimalKind.fox))
            {
                Flee();
            }

            // 3.priority: Eating
            else if (Hungry)
            {
                Scavenge();
                Eat();
            }

            // 4.priority: Sleeping
            else if (Sleepy)
            {
                Sleep();
            }

            else
            {
                Idle();
            }
        }
Пример #14
0
        public Mouse(AnimalGender gender) : base(AnimalKind.mouse, gender)
        {
            AddBehavior(
                1,
                () => TheWorld.NearBy(AnimalKind.fox) || TheWorld.NearBy(AnimalKind.rabbit),
                Flee);

            AddBehavior(
                2,
                () => TheWorld.NearBy(AnimalKind.mouse) && TheWorld.GenderOfNearBy(AnimalKind.mouse) != Gender,
                Mate);

            AddBehavior(
                3,
                () => Hungry,
                () =>
            {
                Scavenge();
                Eat();
            });

            AddBehavior(
                4,
                () => Sleepy,
                Sleep);
        }
Пример #15
0
        /// <summary>
        /// Randomize spawn location for ship
        /// </summary>
        /// <param name="ship"></param>
        public static void SpawnShip(Ship ship)
        {
            Random   rand = new Random();
            int      LocX;
            int      LocY;
            bool     safeSpawn = false;
            Vector2D position  = new Vector2D(0.0, 0.0);

            //loop through potential random spawn locations to find location that is
            //not near a star or a ship.
            while (!safeSpawn)
            {
                int worldSize = (int)gameSettings["UniverseSize"] - 1;
                // finding possible random variables for the spawn location
                LocX     = rand.Next(-(worldSize / 2), worldSize / 2);
                LocY     = rand.Next(-(worldSize / 2), worldSize / 2);
                position = new Vector2D(LocX, LocY);

                // flags to determine if ship should spawn or not.
                bool starSpawn = true; // set for spawning on top of stars
                bool shipSpawn = true; // set for spawning on top of other ships

                //checks to see if potential spawn location is too close to a star
                foreach (Star star in TheWorld.GetStars())
                {
                    if ((star.loc - position).Length() <= 50)
                    {
                        starSpawn = false;
                    }
                }

                //checks to see if potential spawn location is too close to a ship
                foreach (Ship shipLoop in TheWorld.GetShipsAll())
                {
                    if ((shipLoop.loc - position).Length() <= 50)
                    {
                        shipSpawn = false;
                    }
                }

                //If neither star or ship is hindering spawn, break out of loop
                if (starSpawn == true && shipSpawn == true)
                {
                    safeSpawn = true;
                }
            }

            ship.SetLoc(position);
            ship.SetHp((int)gameSettings["StartingHP"]);
            ship.SetThrust(false);
            Vector2D vel = new Vector2D(0, 0);

            ship.SetVelocity(vel);
            ship.SetDeathCounter(0);
            Vector2D Dir = new Vector2D(0, 1);

            ship.SetDir(Dir);
            ship.SetFireRateCounter((int)(gameSettings["FramesPerShot"]));
        }
Пример #16
0
        private async void FireBeam(TheWorld world, Beam beam)
        {
            //Invoke drawing on main thread
            await Task.Delay(500);

            //remove beam
            world.RemoveBeam(beam);
        }
Пример #17
0
 void Awake()
 {
     instance = this;
     timer = GetComponent<WorldTimer>();
     noteRef = GetComponent<WorldNoteRef>();
     memory = GetComponent<Memory>();
     cardPool = GetComponent<CardPool>();
     triggerMgr = GetComponent<TriggerMgr>();
     cardCanvas = _cardCanvas;
     eventCanvas = _eventCanvas;
 }
Пример #18
0
        /// <summary>
        /// Commands from client are stored in each instance of the client class, unique to each player.
        /// On every frame, if a client command is set to true, process the command and reset flag.
        /// </summary>
        public static void ProcessCommands()
        {
            double shipTurnRate = (double)gameSettings["ShipTurnRate"];

            // Process the current flag in the correct way for every client.
            foreach (KeyValuePair <int, Client> c in ClientConnections)
            {
                Client client = c.Value;
                Ship   ship   = TheWorld.GetShipAtId(client.ID);
                if (client.left == true)
                {
                    Vector2D tempDir = new Vector2D(ship.dir);
                    tempDir.Rotate(-shipTurnRate); // ship turn rate is specified as a game setting.
                    ship.SetDir(tempDir);
                    client.left = false;
                }
                if (client.right == true)
                {
                    Vector2D tempDir = new Vector2D(ship.dir);
                    tempDir.Rotate(shipTurnRate);
                    ship.SetDir(tempDir);
                    client.right = false;
                }
                if (client.thrust == false)
                {
                    ship.SetThrust(false);
                }
                if (client.thrust == true)
                {
                    ship.SetThrust(true);
                    client.thrust = false;
                }

                // if we have waited long enough after previous fire, fire projectile
                if (client.fire == true && ship.fireRateCounter == (int)gameSettings["FramesPerShot"])
                {
                    // fire projectile
                    Vector2D projVel  = new Vector2D(ship.dir * (double)gameSettings["ProjectileSpeed"]);
                    Vector2D startPos = new Vector2D(ship.loc + (ship.dir * 20));
                    InsertProjectile(startPos, ship.dir, projVel, ship);
                    client.fire = false;

                    //Reset fireRateCounter after a ship fires
                    ship.SetFireRateCounter(-1);
                }
                // if we haven't waited long enough after previous fire
                else if (client.fire == true && ship.fireRateCounter < (int)gameSettings["FramesPerShot"])
                {
                    // increment the counter.
                    ship.SetFireRateCounter(ship.fireRateCounter + 1);
                }
            }
        }
Пример #19
0
 /// <summary>
 /// Method to handle the first messages received by the server before it starts sending JSON and setup the drawing panel w/ world size and player according to this information.
 /// </summary>
 /// <param name="message">Message being sent from the server.</param>
 /// <returns>String array of additional messages not handled by this method</returns>
 private string[] SetUpWorld(string[] message)
 {
     if (int.TryParse(message[0], out int playerID) && int.TryParse(message[1], out int worldSize))
     {
         world = new TheWorld(worldSize, playerID);
     }
     else
     {
         throw new Exception("Something went wrong setting up the world");
     }
     return(message.Skip(2).ToArray());
 }
Пример #20
0
 /// <summary>
 /// Moves stars in orbit for fancy game mode
 /// </summary>
 public static void ProcessStars()
 {
     foreach (Star star in TheWorld.GetStars())
     {
         Vector2D tempDir  = new Vector2D(star.dir);
         Vector2D tempDir2 = new Vector2D(star.dir);
         tempDir.Rotate(-1);
         star.SetDir(tempDir);
         // rotates the star around the center of the world.
         Vector2D tempLoc = new Vector2D(star.loc + (tempDir2 * Math.Tan(Math.PI / 180) * ((int)gameSettings["UniverseSize"] / 3.5)));
         star.SetLoc(tempLoc);
     }
 }
Пример #21
0
        /// <summary>
        /// Kills ship of client that disconnects and removes client from world
        /// </summary>
        /// <param name="ss"></param>
        public static void DisconnectClientHandler(Networking.SocketState ss, string message)
        {
            Console.WriteLine(message);
            Ship ship = TheWorld.GetShipAtId(ss.ID);

            ship.SetHp(0);
            SendWorld(); // make sure to send the world so that the client knows to terminate the ship.
            lock (TheWorld)
            {
                // remove ship and client connection associated with that ship.
                TheWorld.RemoveShipAll(ss.ID);
                ClientConnections.Remove(ss.ID);
            }
        }
Пример #22
0
        public void DescribeLocation(int locationIdToDisplay)
        {
#if DEBUG
            if (!TheWorld.ContainsKey(locationIdToDisplay))
            {
                Console.WriteLine("DEVELOPER FAULT location does not exist");
            }
#endif


            Location wherePlayerIs = TheWorld[locationIdToDisplay];
            Display.WriteMessage($"You are at {wherePlayerIs.Name}");
            Display.LeaveALine();
            Display.WriteMessage($"{wherePlayerIs.Description}");
        }
Пример #23
0
        /// <summary>
        /// Inserts ship into the world's dictionary of ships
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="score"></param>
        public static void InsertShip(int id, string name, int score)
        {
            Ship ship = new Ship();

            ship.SetID(id);
            ship.SetName(name);
            ship.SetScore(score);

            lock (TheWorld)
            {
                //Spawn ship randomizes location and sets direction
                SpawnShip(ship);
                //Adds ship to dictionary
                TheWorld.AddShipAll(ship);
            }
        }
Пример #24
0
        /// <summary>
        /// Inserts projectile into the world's dictionary of projectiles
        /// </summary>
        /// <param name="id"></param>
        /// <param name="loc"></param>
        /// <param name="dir"></param>
        /// <param name="vel"></param>
        /// <param name="ship"></param>
        public static void InsertProjectile(Vector2D loc, Vector2D dir, Vector2D vel, Ship ship)
        {
            if (ship.hp > 0)
            {
                Projectile proj = new Projectile();
                proj.SetID(projectileCounter);
                proj.SetLoc(loc);
                proj.SetDir(dir);
                proj.SetVel(vel);
                proj.SetAlive(true);
                proj.SetOwner(ship.ID);
                TheWorld.AddProjectile(ship.ID, proj);

                //increment so that each projectile has a unique ID
                projectileCounter++;
            }
        }
    // Mouse click selection
    // Copied from: http://answers.unity3d.com/questions/411793/selecting-a-game-object-with-a-mouse-click-on-it.html
    void ProcessMouseEvents()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // Debug.Log("Mouse is down");

            RaycastHit hitInfo = new RaycastHit();

            bool hit = Physics.Raycast(MainCamera.ScreenPointToRay(Input.mousePosition), out hitInfo, Mathf.Infinity, 1);
            // 1 is the mask for default layer
            if (hit)
            {
                TheWorld.SelectObjectAt(hitInfo.transform.gameObject, hitInfo.point);
            }
            TheSlider.SetSliderValue(TheWorld.GetSelectedRadius());
        }
    }
Пример #26
0
        // Mouse click selection
        // Mouse click checking
        void CheckMouseClick()
        {
            if (Input.GetMouseButtonDown(0))
            {
                // Debug.Log("Mouse is down");

                RaycastHit hitInfo = new RaycastHit();
                // Note: mTarget is in a layer not rayCast!!

                bool hit = Physics.Raycast(MainCamera.ScreenPointToRay(Input.mousePosition), out hitInfo, Mathf.Infinity, 1);
                // 1 is the mask for default layer
                if (hit)
                {
                    TheWorld.SelectObjectAt(hitInfo.transform.gameObject, hitInfo.point);
                    // Main controller SHOULD NOT know anything about what
                    // user wants to do with mouse click
                }
                else
                {
                    Debug.Log("No hit");
                }
            }
        }
Пример #27
0
        private void OnFrame(TheWorld world)
        {
            // Don't try to redraw if the window doesn't exist yet.
            // This might happen if the controller sends an update
            // before the Form has started.
            if (!IsHandleCreated)
            {
                return;
            }

            // Invalidate this form and all its children
            // This will cause the form to redraw as soon as it can
            try
            {
                drawingPanelGame.SetWorld(world);
                MethodInvoker m = new MethodInvoker(() => this.Invalidate(true));
                this.Invoke(m);
                controller.TalkToserver();
            }
            catch
            {
            }
        }
 public override void Because()
 {
     TheWorld.StepForwardOneTimeUnit();
 }
 public void It_should_not_move_any_further_units_in_that_direction()
 {
     TheWorld.GetCoordinatesOf(TheWarrior, TheRoom).ShouldEqual(new WorldCoordinates(2, 2));
 }
 public void It_should_move_into_that_spot()
 {
     TheWorld.GetCoordinatesOf(TheWarrior, TheRoom).ShouldEqual(new WorldCoordinates(2, 1));
 }
 public void Other_entity_should_be_in_new_spot()
 {
     TheWorld.GetCoordinatesOf(Enemy, TheRoom).ShouldEqual(new WorldCoordinates(1, 1));
 }