Showing posts with label Code_Snippets. Show all posts
Showing posts with label Code_Snippets. Show all posts

Game jam Manchester - 29/8/2013

For the last couple of months I have been attending a gathering of young people who are interested in all things tech and mentoring anyone who was interested in game dev as its usually a good way to get young people interested in computing. This gathering is called "@CoderDojo" and is held in the Northern Quarter in Manchester at @MadLabu18 which is only 20 mins from where I live and there are many more @CoderDojo 's being held all over the world.
It was through @MadLabu18 where I heard about about the @McrGameJam which was held @MadLabu18 on 28/9/2013.
As I have never been or done anything like this, I decided why not and purchased a ticket for myself and good friend Mark @maycontaingeeks who was also interested in the game dev process (he mainly wanted to know why it took me so long to develop Spectrangle360 :) ).

So on the Saturday morning I set off there with just my laptop and VS2010 installed, I had already decided that what ever I would be developing I would be using C# and the #XNA framework. Before the event we had already been given 5 themes to the game jam and the themes they had chosen where "Climbing, Inversion, Robots, Stealing and Hats" with the challenge of creating a game which would include as many of these themes as possible.

When I arrived, there where a few people already waiting outside for the place to open and after a few introductions I got talking to a guy called Phil who told me he was an illustrator and was hoping to group up with a developer, this worked out great as I really cant draw for toffee. Soon after my friend mark arrived where he had already been thinking about a game design which would include some of the themes.





From this Mark explained that the game would consist of a single platforming screen, where some hats would drop down from a tube. It would be your job as a relentless robot to collect these hats and throw them in the correct delivery shoot. Throwing the hats in the matching shoot would gain more points, the game would have a time limit where the final score would be displayed for each robot, oh yes Mark wanted it too be multi player too :S

So after a pretty full on day and some excellent image delivery from Phil and some great jokes and cajoling from Mark we manage to get some form of a game working. We didnt manage to get half of the game mechanics in we wanted eg multiplayer, matching hat tube scoring etc.. but we did have a pretty complete game with a proper beginning and end and a goal to collect 3 hats, not bad to say I had never attempted a platform game in #XNA with proper collision.

At the end of the day we didnt win the game jam but we definitely had fun doing it and I think hats all that mattered :), I would definitely attend one again in the future. Hats off  :) to the organisers and everyone else who went. 

Anyway here is a link to the code, again please excuse the dodgy coding and such, when your in a rush you definietly have to cut corners in terms of nicely tested code etc.. However if you do use any of it in some way I would hope that you email me at jaywroe (at) gmail.com and just throw me an email with what you thought of the code and how you will use it.


Post tinkering

After spending another 1:30 hours I managed to improve the performance of the game when it initializes and when the robot is moving around in terms of collisions with the hats. If I ever get bored or have some spare time I might add the other features we wanted to add and see where it goes...who knows I may recycle some in another game jam.

How Friend Invites work in Spectrangle360



A few #XBLIG #XNA devs have gotten in touch with me over twitter about how I managed to do the "Invite Friend" functionality in Spectrangle360. Although there is an MSDN article on the subject and the XNA gamestatemanagement example shows how this is done I still think a real world example might come in useful for some people.



So I have decided I would explain how I managed to get it to work in Spectrangle360.


Current Structure


Before I dive into the actual code I want to explain a bit about the structure of Spectrangle360 so that the code actually makes sense. Spectrangle360 was developed with the FSM (finite state machine) pattern as a basis, this meant that each of the areas/classes of the game could be split up to handle their own state.



        public interface IState
    {
        void Enter( IStateContext context);
        void Update( IStateContext context, GameTime time);
        void Draw( IStateContext context, SpriteBatch spriteBatch);
        void Exit( IStateContext context);
    }






         public interface IStateContext
    {
        IState State { get; }

        void Update(GameTime time);

        void Draw( SpriteBatch spriteBatch);

        void ChangeState(IState state);
    }




So when Spectrangle360 first starts up the game enters into a "GameS

creenManager" state which inherits from "IState", this "GameScreenManager" state is the main state of the game which is always running unless the game throws any exceptions. From this state other states are entered eg when the Demo is playing, the game is playing or the game is being played via Xbox live and this state "TwoPlayerLobby" is the class that handles all the work when a players is in the lobby trying to create or join a two player game.


The Code


The first piece of code is the code which I used to basically set up some variables and to hook the "InviteAccepted" event :-



    public void Hook(SpectrangleManager manager, GameScreenManager gm, bool hook)
        {
            _mgr = null;

            _mgr = manager;

            _gsm = null;
            _gsm = gm;

            _context = gm;

            if (!hook)
            {
                NetworkSession.InviteAccepted += NetworkSession_InviteAccepted;
            }
        }




This hook code is called from the "MainScreen" state via its enter method like this, "_TPL" is an instance of the "TwoPlayerLobby" class :-



    public void Enter(IStateContext context)
        {
            ...
                ((GameScreenManager)context)._TPL.Hook(((GameScreenManager)context).Manager, (GameScreenManager)context, ((GameScreenManager)context).AcceptHook);

            ...
        }




Having an instance of the "TwoPlayerLobby" class means that the game is always ready to accept invites when the player is in the "TwoPlayerLobby" state.



The code used once a game invite has been accepted is this :-



    public void NetworkSession_InviteAccepted(object sender, InviteAcceptedEventArgs e)
        {

            Game1.HSC.SearchNetworkOff = true;
            Game1.HSC.Enabled = false;

            _gsm.GameSearch.Disable = true;

            {

                // stops a different gamer controller joining a game in progress
                if (e.Gamer.PlayerIndex != Game1.Global.Controller())
                {
                    _gsm.ChangeState(new NetworkErrorMessage("You cannot join game in progress with a different gamer. Please return to the title screen if you wish to swap profiles."));
                    return;
                }


                // Quit the current session
                if (_mgr.Session != null)
                {
                    try
                    {
                        _mgr.Session.Dispose();
                        _mgr.Session = null;
                    }
                    catch
                    {
                        return;
                    }
                }




                // We can now create a new instance of the SpectrangleManager game and then create the player instances to be used later.





                _gsm.Manager = new SpectrangleManager( Game1.Global.Content, (GameScreenManager)_gsm);

                _mgr = _gsm.Manager;

                _mgr.Players[0] = new Player(_mgr, PlayerIndex.One, "1", PlayerSide.WHITE, false);
                _mgr.Players[1] = new Player(_mgr, PlayerIndex.Two, "2", PlayerSide.BLACK, false);

                try
                {
                    // Join the new session
                    _mgr.Session = NetworkSession.JoinInvited(1);
                }
                catch
                {
                    _gsm.ChangeState(new NetworkErrorMessage("Unable to join game in progress."));
                    return;
                }








                // hook the normal network session events
                HookSessionEvents();



                // We can change the state to wait for the host to start as we have now accepted the friend invite
                _gsm.ChangeState(new WaitForHostToStart(2, false, _mgr,_mgr.Session));
            }
           
        }






And there you have it, this code allows friend invites to be accepted and once the invite is accepted the "GameScreenManager" main state is changed to "WaitForHostToStart" state. Yes I know this could have been done much cleaner but I just wanted to get this to work the easiest way I could at the time. If I ever develop another multiplayer game with Xbox Live friend invites I would probably look at this whole code again to see if I could improve it.



Anyway hope it helps some one.



Jase


I blog with BE Write

Using SpriteVortex to create animations

The other day whilst experimenting with some projects I started looking round the web to see if there was a tool I could use to extract a Spritesheet I could use in XNA from an image which had number of different animation frames.

Well I couldnt find anything that exactly did what I wanted but I did find a little app called SpriteVortex. 


This app seems to be able to scan an image and pick out the frames of your image using a colour key and construct a list of sprites. The app then lets you construct a list of animation sets which you can add each sprite too and it even has a little animation preview window where you can offset each frame to get them to animate correctly and set the animation time for each frame.
When you have done with your animation you can then export the whole thing to an XML file.

This all sounded good however I couldnt seem to find a way use this XML to generate animation in my own XNA project. So I got to thinking how I would do it. Well as the XML is simply XML I thought I might be able to write my own XML deserializer to read in the XML and construct the sprite and animation objects from the data.

After doing a bit of reading round on serializing and deserializing I came up with this cs file :-

namespace SpriteVortexDeserialize
{
 
    [XmlRoot("Sprite")]
    public class Sprite
    {
        [XmlAttribute("Name")]
        public string Name;
 
        [XmlAttribute("Id")]
        public int Id;
 
        [XmlElement("Coordinates")]
        public Coordinates Coordinates;
    }
 
    [XmlRoot("Coordinates")]
    public class Coordinates
    {
        [XmlElement("X")]
        public int X;
        [XmlElement("Y")]
        public int Y;
        [XmlElement("Width")]
        public int Width;
        [XmlElement("Height")]
        public int Height;
    }
 
    [XmlRoot("Animation")]
    public class Animation
    {
        [XmlAttribute("Name")]
        public string Name;
 
        [XmlAttribute("FrameRate")]
        public int FrameRate;
 
        [XmlAttribute("Loop")]
        public string Loop;
 
        [XmlAttribute("PingPong")]
        public string PingPong;
 
        [XmlArray("Frames")]
        [XmlArrayItem("Frame", typeof(Frame))]
        public List<Frame> _frames;
    }
 
    [XmlRoot("Frame")]
    public class Frame
    {
        [XmlAttribute("SpriteId")]
        public int SpriteId;
        [XmlAttribute("OriginX")]
        public float OriginX;
        [XmlAttribute("OriginY")]
        public float OriginY;
        [XmlAttribute("OffSetX")]
        public int OffSetX;
        [XmlAttribute("OffSetY")]
        public int OffSetY;
        [XmlAttribute("Duration")]
        public float Duration;
    }
 
    [XmlRoot("Texture")]
    public class Texture
    {
        [XmlAttribute("Path")]
        public string Path;
        [XmlAttribute("Name")]
        public string Name;
    }
 
    [XmlRoot("SpriteMapping")]
    public class SpriteMapping
    {
        [XmlElement("Texture")]
        public Texture texture;
 
        [XmlArray("Sprites")]
        [XmlArrayItem("Sprite", typeof(Sprite))]
        public List<Sprite> _sprites;
 
        [XmlArray("Animations")]
        [XmlArrayItem("Animation", typeof(Animation))]
        public List<Animation> _animations;
    }
} 
 
Once you have this class you can then deserialize the XML into this object structure using this code :-


SpriteMapping spriteMapping = new SpriteMapping();
XmlSerializer serializer = new XmlSerializer(spriteMapping.GetType());
TextReader textReader = new StreamReader("./Content/testknight.xml");
spriteMapping = (SpriteMapping)serializer.Deserialize(textReader);
textReader.Close();
 
As usual you would have to put your image assets and your XML into the Content project however you have to set the XML file to ContextProcessor = "No Processing Required" and Copy to Output Directory = "Always Copy".

Hope this helps somebody out who wants to use this little app without writing your own sprite manager functionality, also if I get some feedback on this post I might also upload a sample project but havent decided that yet.
Jase

Highscores Component XNA v4.0

Highscores Component XNA v4.0

A while ago I downloaded Jon Watte's Highscore Component. However after using it for quite some time it became apparent that I had to convert this to work in the new XNA v4.0.

So I did this work, I cant say how well I converted it but it seems to work for me. If you would find this useful heres a link to the CS file. You will have to pull this CS file into your project and change the namespace to match the name of your games namespace. Hope it helps someone in some way.

highscorescomponent.cs

Jase