Ejemplo n.º 1
0
        public override void FireShot()
        {
            if (ShotsFired < MaxShots || !Game.Match.UsePlayerTurns)
            {
                ++ShotsFired;
                Game.Services.GetService <SoundControl>().PlaySound(SoundControl.PistolSound);

                var muzzle = SpriteGraphicsEffect.CreateMuzzle(
                    Game.Match.GameTime,
                    Ball.Position + 2f * Ball.AimDirection,
                    Ball.AimDirection.RotationFromDirection()
                    );
                Game.Match.World.GraphicsEvents.Add(muzzle);

                var rayHit = Game.Match.Physics.Raycast(Ball.Position, Ball.Position + Ball.AimDirection * 1000f);
                if (rayHit.HasHit)
                {
                    Game.Match.World.StaticGeometry.SubtractCircle(rayHit.Position.X, rayHit.Position.Y, ExplosionRadius);
                    Ballz.The().Match.World.GraphicsEvents.Add(SpriteGraphicsEffect.CreateExplosion(Ballz.The().Match.GameTime, rayHit.Position, 0, 0.2f));
                    if (rayHit.Entity != null)
                    {
                        if (rayHit.Entity is Ball)
                        {
                            Ball theBall = rayHit.Entity as Ball;
                            if (theBall.Health > 0)
                            {
                                theBall.ChangeHealth(-Damage);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public void Start()
        {
            BrowserThread = new Thread(() =>
            {
                Browser                   = new WebBrowser();
                Browser.Width             = Ballz.The().GraphicsDevice.Viewport.Width;
                Browser.Height            = Ballz.The().GraphicsDevice.Viewport.Height;
                Browser.ScrollBarsEnabled = false;
                //Browser.IsWebBrowserContextMenuEnabled = false;
                LatestBitmap       = new Bitmap(Browser.Width, Browser.Height);
                Browser.Validated += (s, e) =>
                {
                    lock (this)
                    {
                        Browser.DrawToBitmap(LatestBitmap, new Rectangle(0, 0, Browser.Width, Browser.Height));
                    }
                };

                Browser.DocumentCompleted += (s, e) =>
                {
                    lock (this)
                    {
                        Browser.DrawToBitmap(LatestBitmap, new Rectangle(0, 0, Browser.Width, Browser.Height));
                    }
                };

                Browser.Navigate("file://C:/Users/Lukas/Documents/gui.html");

                var context = new ApplicationContext();
                Application.Run();
            });

            BrowserThread.SetApartmentState(ApartmentState.STA);
            BrowserThread.Start();
        }
Ejemplo n.º 3
0
        private void HandleMatchStart(GameStartInfo startInfo)
        {
            var settings = MatchSettings.Deserialize(startInfo.Settings);

            Ballz.The().Network.StartNetworkGame(settings, startInfo.YourPlayerId);
            Ballz.The().Match.IsRemoteControlled = true;
        }
Ejemplo n.º 4
0
 public void Start()
 {
     Peer.Start();
     HandleNewPlayer(null, new LobbyPlayerGreeting {
         PlayerName = Ballz.The().Settings.PlayerName
     });
 }
Ejemplo n.º 5
0
 public void SetMainMenu(MenuPanel menu)
 {
     activeMenu.Clear();
     activeMenu.Push(menu); //TODO: uncast
     state = GameState.MenuState;
     menu.OnOpen();
     Ballz.The().LockMouse = false;
 }
Ejemplo n.º 6
0
 private void ProcessMouseInput()
 {
     if (CurrentMouseState.LeftButton != PreviousMouseState.LeftButton)
     {
         var isPressed = CurrentMouseState.LeftButton == ButtonState.Pressed;
         var player    = Ballz.The().Match?.PlayerByNumber(1);
         OnInput(InputMessage.MessageType.ControlsAction, pressed: isPressed, player: player);
     }
 }
Ejemplo n.º 7
0
        public override void OnEntityCollision(Entity other)
        {
            if (Ballz.The().Match.IsRemoteControlled)
            {
                return;
            }
            //TODO: Player damage

            onAnyCollision();
        }
Ejemplo n.º 8
0
        public static Texture2D LoadTextureData(string pngdata)
        {
            var png = Convert.FromBase64String(pngdata);

            using (var ms = new MemoryStream(png))
            {
                var texture = Texture2D.FromStream(Ballz.The().GraphicsDevice, ms);
                return(texture);
            }
        }
Ejemplo n.º 9
0
        private void HandleRemoteInput(NetConnection sender, InputMessage msg)
        {
            var player = PlayersByConnection[sender.RemoteUniqueIdentifier].MatchPlayer;

            msg.Player = player;
            if (player != null)
            {
                Ballz.The().Input.InjectInputMessage(msg, player);
            }
        }
Ejemplo n.º 10
0
        public void OpenMenu(MenuPanel newMenu)
        {
            var oldMenu = activeMenu.Peek();

            oldMenu.OnClose();
            newMenu.OnOpen();

            activeMenu.Push(newMenu);
            RaiseMessageEvent(new MenuMessage(activeMenu.Peek()));
            state = GameState.MenuState;
            Ballz.The().LockMouse = false;
        }
Ejemplo n.º 11
0
 protected virtual void RaiseMessageEvent(Message msg)
 {
     Message?.Invoke(this, msg);
     if (state == GameState.MenuState)
     {
         Ballz.The().Services.GetService <SoundControl>().StartMusic(SoundControl.MenuMusic);
     }
     else
     {
         Ballz.The().Services.GetService <SoundControl>().StopMusic(SoundControl.MenuMusic);
     }
 }
Ejemplo n.º 12
0
        private void SendWorldState()
        {
            var entities = Ballz.The().Match.World.Entities;

            foreach (var e in entities)
            {
                Broadcast(e);
            }

            var sessionState = Ballz.The().Match.GetState();

            Broadcast(sessionState);
        }
Ejemplo n.º 13
0
 public Texture2D GetTerrainTypeTexture()
 {
     Update();
     lock (PublicShape)
     {
         if (PublicShape.TypeTexture == null)
         {
             PublicShape.TypeTexture = new Texture2D(Ballz.The().GraphicsDevice, width, height);
             PublicShape.TypeTexture.SetData(PublicShape.TypeData);
         }
     }
     return(PublicShape.TypeTexture);
 }
Ejemplo n.º 14
0
        private void OnInput(InputMessage.MessageType inputType, bool pressed = false, char key = char.MinValue, Player player = null)
        {
            var inputMessage = new InputMessage(inputType, pressed, key, player);

            if (Ballz.The().MessageOverlay != null)
            {
                Ballz.The().MessageOverlay.HandleInput(inputMessage);
            }
            else
            {
                Input?.Invoke(this, inputMessage);                 //todo: use object pooling and specify message better
            }
        }
Ejemplo n.º 15
0
        public void Update(GameTime time)
        {
            NetIncomingMessage im;

            while ((im = Peer.ReadMessage()) != null)
            {
                // handle incoming message
                switch (im.MessageType)
                {
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    Console.WriteLine($"NetMessage {im.MessageType}: {im.ReadString()}");
                    break;

                case NetIncomingMessageType.StatusChanged:
                    NetConnectionStatus status = (NetConnectionStatus)im.ReadByte();

                    if (status == NetConnectionStatus.Connected)
                    {
                        IsConnected = true;
                        Sync.AddConnection(im.SenderConnection);
                        Connected?.Invoke(this, null);
                        SendToServer(new LobbyPlayerGreeting {
                            PlayerName = Ballz.The().Settings.PlayerName
                        });                                                                                         // TODO: Use actual player name
                    }
                    else
                    {
                        IsConnected = false;
                    }

                    if (status == NetConnectionStatus.Disconnected)
                    {
                        Disconnected?.Invoke(this, null);
                    }

                    break;

                case NetIncomingMessageType.Data:
                    Sync.ReadMessage(im);
                    break;

                default:
                    Console.WriteLine($"Unhandled message type: {im.MessageType} {im.LengthBytes} bytes");
                    break;
                }
                Peer.Recycle(im);
            }
        }
Ejemplo n.º 16
0
        public void LoadSettings()
        {
            var GameSettings = Ballz.The().Settings;

            EnableFullscreen.Checked = GameSettings.Fullscreen;
            PlayerName.Value         = GameSettings.PlayerName ?? "";
            if (Ballz.The().GetResolutions().Contains(Ballz.The().Settings.ScreenResolution))
            {
                Resolution.SelectedIndex = Ballz.The().GetResolutions().IndexOf(Ballz.The().Settings.ScreenResolution);
            }

            MasterVolume.Value = GameSettings.MasterVolume;
            MusicVolume.Value  = GameSettings.MusicVolume;
        }
Ejemplo n.º 17
0
        public void StartNetworkGame(MatchSettings gameSettings, int localPlayerId)
        {
            if (Role == NetworkRole.Server)
            {
                server.StartNetworkGame(gameSettings);
            }
            else if (Role == NetworkRole.Client)
            {
                gameSettings.GameMode.InitializeSession(Ballz.The(), gameSettings);
                Ballz.The().Logic.StartGame(gameSettings, true, localPlayerId);
            }

            GameState = NetworkGameState.InGame;
        }
Ejemplo n.º 18
0
        public virtual void FireProjectile()
        {
            if (Ballz.The().Match.IsRemoteControlled)
            {
                return;
            }

            Game.Services.GetService <SoundControl>().PlaySound(SoundControl.BazookaSound);
            Shot newShot = CreateShot();

            ProjectileInAir = newShot;
            Game.Match.World.AddEntity(newShot);
            Ball.PhysicsBody.ApplyForce(-10000 * Ball.ShootCharge * newShot.Recoil * Ball.AimDirection);
        }
Ejemplo n.º 19
0
        public OptionsMenu() : base("Options")
        {
            Skin = PanelSkin.Default;

            PlayerName.PlaceholderText = "Enter your Name";

            Resolution = new DropDown(new Vector2(0, 280));
            var resolutions = Ballz.The().GetResolutions();

            foreach (var resolution in resolutions)
            {
                Resolution.AddItem($"{resolution.Width}x{resolution.Height}");
            }

            LoadSettings();

            AddItem(new Label("Player Name:"));
            AddItem(PlayerName);

            AddItem(EnableFullscreen);

            AddItem(new Label("Screen Resolution:"));
            AddItem(Resolution);

            AddItem(new Label("Sound Volume:"));
            AddItem(MasterVolume);

            AddItem(new Label("Music Volume:"));
            AddItem(MusicVolume);

            var backButton = new MenuButton(
                "Back",
                size: new Vector2(0.5f, -1.0f),
                skin: ButtonSkin.Alternative,
                anchor: Anchor.BottomLeft,
                click: () => Ballz.The().Logic.MenuGoBack()
                );

            AddItem(backButton);
            var saveButton = new MenuButton(
                "OK",
                size: new Vector2(0.5f, -1.0f),
                skin: ButtonSkin.Alternative,
                anchor: Anchor.BottomRight,
                click: SaveSettings
                );

            AddItem(saveButton);
        }
Ejemplo n.º 20
0
        public override void OnTerrainCollision(Terrain terrain, Vector2 position)
        {
            if (Ballz.The().Match.IsRemoteControlled)
            {
                return;
            }

            float impact = 0.04f * Velocity.Length() * BulletHoleRadius;

            if (impact > 0.2)
            {
                // Destroy terrain and die
                terrain.SubtractCircle(position.X, position.Y, impact);
            }

            onAnyCollision();
        }
Ejemplo n.º 21
0
        public SinglePlayerMenu() : base("Singleplayer")
        {
            var currGameSettings = new MatchSettings();

            // hard-coded game settings
            {
                // Player 1
                {
                    var team1 = new Team
                    {
                        ControlledByAI = false,
                        Name           = "Germoney",
                        Country        = "Germoney",
                        NumberOfBallz  = 2
                    };
                    currGameSettings.Teams.Add(team1);
                }
                // Player 2
                {
                    var team2 = new Team
                    {
                        ControlledByAI = false,
                        Name           = "Murica",
                        Country        = "Murica",
                        NumberOfBallz  = 2
                    };
                    currGameSettings.Teams.Add(team2);
                }
            }

            // Select GameMode
            foreach (var factory in SessionFactory.SessionFactory.AvailableFactories)
            {
                var factoryLabel = new MenuButton(factory.Name);
                factoryLabel.OnClick += (e) =>
                {
                    currGameSettings.GameMode = factory;
                    Ballz.The().Logic.StartGame(currGameSettings);
                };
                AddItem(factoryLabel);
            }


            AddItem(new BackButton());
        }
Ejemplo n.º 22
0
        public void Explode()
        {
            if (ExplosionRadius <= 0.0f)
            {
                return;
            }

            Ballz.The().Match.World.StaticGeometry.SubtractCircle(Position.X, Position.Y, ExplosionRadius);

            Ballz.The().Match.World.GraphicsEvents.Add(new CameraShakeEffect {
                Intensity = 2f, Duration = 0.2f, Start = Ballz.The().Match.GameTime
            });
            Ballz.The().Match.World.GraphicsEvents.Add(SpriteGraphicsEffect.CreateExplosion(Ballz.The().Match.GameTime, Position, 0));

            // TODO: damage to all players within explosion radius
            foreach (var p in Ballz.The().Match.Players)
            {
                foreach (var b in p.OwnedBalls)
                {
                    if (Vector2.Distance(b.Position, this.Position) < ExplosionRadius)
                    {
                        if (!Ballz.The().Settings.FriendlyFire&& b.Player.TeamName == Team)
                        {
                            break;
                        }

                        b.ChangeHealth(-this.HealthDecreaseFromExplosionImpact * Vector2.Distance(b.Position, this.Position) / ExplosionRadius);

                        b.PhysicsBody.ApplyLinearImpulse(HealthDecreaseFromExplosionImpact *
                                                         Vector2.Distance(b.Position, this.Position) / ExplosionRadius *
                                                         Vector2.Normalize(b.Position - this.Position)
                                                         );
                    }
                }
            }

            if (ShotType == ShotType_T.Generating)
            {
                Ballz.The().Match.World.Water.AddParticles(this.Position, 20);
            }


            // Remove projectile
            Dispose();
        }
Ejemplo n.º 23
0
        private void OnData(object data)
        {
            if (data is LobbyPlayerList)
            {
                PlayerListChanged?.Invoke(this, data as LobbyPlayerList);
            }

            if (data is GameStartInfo)
            {
                HandleMatchStart(data as GameStartInfo);
            }

            if (data is Session.NetSessionState)
            {
                Ballz.The().Match.ApplyState(data as Session.NetSessionState);
            }

            // Entities
            var entity = data as Entity;

            if (entity != null)
            {
                // Same entity already exists?
                var localEntity = Ballz.The().Match.World.EntityById(entity.ID);
                if (localEntity != null)
                {
                    ObjectSync.Sync.SyncState(entity, localEntity);
                }
                else
                {
                    Ballz.The().Match.World.AddEntity(entity);
                }
                return;
            }

            var terrainModification = data as Terrain.TerrainModification;

            if (terrainModification != null)
            {
                Ballz.The().Match.World.StaticGeometry.ApplyModification(terrainModification);
                return;
            }
        }
Ejemplo n.º 24
0
        private void onAnyCollision()
        {
            if (Ballz.The().Match.IsRemoteControlled)
            {
                return;
            }

            // Should the explosion countdown start on collision and has not yet started?
            if (ExplosionDelay > 0.0f && ExplosionCountdown < 0.0f)
            {
                ExplosionCountdown = ExplosionDelay;
            }


            // Die?
            if (DisposeOnCollision)
            {
                Explode();
            }
        }
Ejemplo n.º 25
0
        public void StartGame(MatchSettings settings, bool isMultiplayer = false, int localPlayerId = -1)
        {
            ButtonRepeat.Stop();
            ButtonDelay.Stop();
            // Go back to main menu so it will show when the user enters the menu later
            MenuGoBack();
            // Select the "Continue" entry
            activeMenu.Peek().SelectIndex(0);

            state = GameState.SimulationState;
            Ballz.The().LockMouse = true;
            if (Game.Match != null)
            {
                Game.Match.Dispose();
            }

            Game.Match = settings.GameMode.StartSession(Game, settings, isMultiplayer, localPlayerId);
            Game.Match.Start();
            RaiseMessageEvent(new LogicMessage(LogicMessage.MessageType.GameMessage));
        }
Ejemplo n.º 26
0
        public static Texture2D GenerateTerrain(int width, int height)
        {
            var types = GenerateArray(width, height);

            var typeData = types.Cast <Terrain.TerrainType>();

            var colorData = typeData.Select(t => {
                switch (t)
                {
                case Terrain.TerrainType.Air:
                    return(Color.Black);

                case Terrain.TerrainType.Earth:
                    return(new Color(127, 64, 0));

                case Terrain.TerrainType.Stone:
                    return(new Color(127, 127, 127));

                case Terrain.TerrainType.Sand:
                    return(Color.Yellow);

                case Terrain.TerrainType.Water:
                    return(Color.Blue);

                case Terrain.TerrainType.VegetationSeed:
                    return(Color.Lime);

                case Terrain.TerrainType.SpawnPoint:
                    return(Color.Red);

                default:
                    throw new ArgumentOutOfRangeException(nameof(t), t, null);
                }
            });

            var t2D = new Texture2D(Ballz.The().GraphicsDevice, width, height);

            t2D.SetData(colorData.ToArray());

            return(t2D);
        }
Ejemplo n.º 27
0
        public void TryJump()
        {
            if (JumpCoolDown <= 0f)
            {
                // Send raycasts to the bottom. If it hits anything, perform the actual jump.

                float   closestDist = float.MaxValue;
                Vector2 bestPos     = Vector2.Zero;

                for (float angle = -180f; angle <= 180f; angle += 5f)
                {
                    var rayDirection = new Vector2(0, -(Ball.Radius + 0.05f));
                    rayDirection = rayDirection.Rotate(angle * (float)Math.PI / 180f);
                    var rayHit = Match.Physics.Raycast(Ball.Position, Ball.Position + rayDirection);
                    if (rayHit.HasHit)
                    {
                        Vector2 pos  = rayHit.Position;
                        float   dist = Vector2.Distance(pos, Ball.Position);

                        if (dist < closestDist)
                        {
                            closestDist = dist;
                            bestPos     = pos;
                        }
                    }
                }

                if (closestDist < float.MaxValue)
                {
                    //Ball.Velocity = new Vector2(Ball.Velocity.X, 0) - 5f * Vector2.Normalize(bestPos - Ball.Position);
                    Vector2 VecUp = new Vector2(0, 1);
                    if (Ballz.The().Match.World.StaticGeometry.HasGravityPoint)
                    {
                        Vector2.Normalize(Ball.Position - Ballz.The().Match.World.StaticGeometry.GravityPoint);
                    }

                    Ball.Velocity = 5f * VecUp;
                    JumpCoolDown  = PauseBetweenJumps;
                }
            }
        }
Ejemplo n.º 28
0
        public void RegisterTypes()
        {
            SynchronizingInfo.RegisterClass <LobbyPlayerList>();
            SynchronizingInfo.RegisterClass <LobbyPlayerGreeting>();
            SynchronizingInfo.RegisterClass <SerializedMatchSettings>();
            SynchronizingInfo.RegisterClass <GameStartInfo>();
            SynchronizingInfo.RegisterClass <Team>();
            SynchronizingInfo.RegisterClass <Message>();
            SynchronizingInfo.RegisterClass <NetworkMessage>();
            SynchronizingInfo.RegisterClass <InputMessage>();
            SynchronizingInfo.RegisterClass <Terrain.TerrainModification>();

            SynchronizingInfo.RegisterClass <Session.NetSessionState>(
                (msg, obj) => ((Session.NetSessionState)obj).Serialize(msg),
                (msg, obj) => ((Session.NetSessionState)obj).Deserialize(msg)
                );


            SynchronizingInfo.RegisterIdentifiable <Entity>(
                (id) => Ballz.The().Match.World.EntityById((int)id),
                (obj) => ((Entity)obj).ID,
                (msg, obj) => ((Entity)obj).Serialize(msg),
                (msg, obj) => ((Entity)obj).Deserialize(msg)
                );

            SynchronizingInfo.RegisterIdentifiable <Ball>(
                (id) => Ballz.The().Match.World.EntityById((int)id),
                (obj) => ((Entity)obj).ID,
                (msg, obj) => ((Ball)obj).Serialize(msg),
                (msg, obj) => ((Ball)obj).Deserialize(msg)
                );

            SynchronizingInfo.RegisterIdentifiable <Shot>(
                (id) => Ballz.The().Match.World.EntityById((int)id),
                (obj) => ((Entity)obj).ID,
                (msg, obj) => ((Shot)obj).Serialize(msg),
                (msg, obj) => ((Shot)obj).Deserialize(msg)
                );
        }
Ejemplo n.º 29
0
        public void HandleMessage(object sender, Message message)
        {
            if (message.Kind == Message.MessageType.InputMessage)
            {
                // Pass input messages to the respective ball controllers
                InputMessage msg = (InputMessage)message;

                // When using turn mode in hot-seat, direct all input messages to the active player
                if (Session.UsePlayerTurns && msg.Player != null && msg.Player.IsLocal && Session.ActivePlayer != null && ActiveControllers.ContainsKey(Session.ActivePlayer))
                {
                    ActiveControllers[Session.ActivePlayer]?.HandleMessage(sender, msg);
                }
                // Otherwise, redirect input messages to the player given by msg.Player
                else if (msg.Player != null && msg.Player.IsLocal && ActiveControllers.ContainsKey(msg.Player) && ActiveControllers.ContainsKey(msg.Player))
                {
                    ActiveControllers[msg.Player]?.HandleMessage(sender, msg);
                }
            }

            if (message.Kind == Message.MessageType.LogicMessage)
            {
                LogicMessage msg = (LogicMessage)message;

                if (msg.Kind == LogicMessage.MessageType.GameMessage)
                {
                    Enabled = !Enabled;
                    if (Enabled && Game.Match.State != SessionState.Finished)
                    {
                        Game.Match.State = SessionState.Running;
                    }
                    else
                    {
                        Ballz.The().Services.GetService <SoundControl>().PlaySound(SoundControl.DeclineSound);
                        Game.Match.State = SessionState.Paused;
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public Texture2D ToTexture()
        {
            if (Texture == null)
            {
                Texture = new Texture2D(Ballz.The().GraphicsDevice, Browser.Width, Browser.Height, false, SurfaceFormat.Bgra32);
            }

            var bitmap = ToBitmap();

            if (bitmap != null)
            {
                var bitmapdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

                byte[] data = new byte[bitmap.Width * bitmap.Height * 4];
                Marshal.Copy(bitmapdata.Scan0, data, 0, data.Length);
                bitmap.UnlockBits(bitmapdata);

                byte[] fixeddata = new byte[bitmap.Width * bitmap.Height * 4];

                for (int i = 0; i < data.Length; i += 4)
                {
                    bool transparent = data[i + 0] == 255 && data[i + 1] == 0 && data[i + 2] == 255;
                    fixeddata[i + 0] = data[i + 0];
                    fixeddata[i + 1] = data[i + 1];
                    fixeddata[i + 2] = data[i + 2];
                    fixeddata[i + 3] = transparent ? (byte)0 : (byte)255;
                }

                Texture.SetData(fixeddata);

                return(Texture);
            }
            else
            {
                return(null);
            }
        }