Josh-CO Dev

Solving the worlds problems one line of code at a time.


Leave a comment

XNA – Basic Inventory Tutorial, Harvesting

Yet another from the archives. I apologize that I’ve still been unable to get part 2 of the inventory system. It’s kind of needed for this to work, but I’m sure some of you can put something together with it.

To further build on our tutorials for our basic inventory system, let’s add a basic system to harvest our resources. In my code, I have added a new folder named crafting which I intend to use for anything even remotely crafting related. I then created a new class called Harvesting.cs. Here is the code:

using System;
using FarmGame.Inventory;
using FarmGame.TileEngine;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace FarmGame.Crafting
{
    static class Harvesting
    {
        public static void Harvest(GameObject go, ref PlayerInventory CurrentInventory, ref List objects, ContentManager cm)
        {
            if (go.thisType == GameObject.ObjectType.rock)
               HarvestRock(go, ref CurrentInventory, ref objects, cm);
            if (go.thisType == GameObject.ObjectType.bush)
                HarvestBerryBush(go, ref CurrentInventory, ref objects, cm);
            if (go.thisType == GameObject.ObjectType.tree)
                HarvestTree(go, ref CurrentInventory, ref objects, cm);
        }

        private static void HarvestTree(GameObject g, ref PlayerInventory inventory, ref List objects, ContentManager cm)
        {
            objects.Remove(g);

            inventory.AddItemToInventory(new InventoryItem("wood", 5, cm.Load(@"Objects\wood"), InventoryItem.InventoryType.craft));
        }

        private static void HarvestBerryBush(GameObject g, ref PlayerInventory inventory, ref List objects, ContentManager cm)
        {
            objects.Remove(g);

            inventory.AddItemToInventory(new InventoryItem("berry", 5, cm.Load(@"Objects\berries"), InventoryItem.InventoryType.craft));
        }

        private static void HarvestRock(GameObject g, ref PlayerInventory inventory, ref List objects, ContentManager cm)
        {
            objects.Remove(g);

            inventory.AddItemToInventory(new InventoryItem("stone", 2, cm.Load(@"Objects\stones"), InventoryItem.InventoryType.craft));
        }
    }
}

As per usual, the code should be simple and easy to understand. The one difference here compared to most of my other code is that this is a static class. To put it simply, this means that you do not need to declare a new instance of the class before you call a method, it is loaded in memory when the game launches. Simply just call Harvesting.Harvest, pass in the object you are trying to harvest and the player ineventory. I’m also passing in the list of game objects so that we can handle all object manipulation (such as removing the object from the game) directly from this class.

For my implementation, I am checking for a space key press when it is checking all of my game objects. Here is the relevant code:

if (tileRect.Intersects(Player.fowardBox()))
                {
                    bool harvestable;

                    box.Position = new Vector2(tileRect.X + 5, tileRect.Y + 5);

                    //box.textHandler.Output = "Press space to mine this rock.";
                    box.textHandler.Output = GameObjectDialogue.GetOutput(Inventory.EquippedItem, go, out harvestable);
                    dialogBoxNeeded = true;

                    //check for action key
                    if (keyState.IsKeyDown(Keys.Space) && !prevKeyState.IsKeyDown(Keys.Space))
                    {
                        //add additional code here to return items 
                        if (harvestable)
                        {
                            Harvesting.Harvest(go, ref Inventory, ref GameObjects,CM);                    //this.GameObjects.Remove(go);
                            return;
                        }
                    }
                }


Leave a comment

Javascript

With all of the HTML5 talk that is going around lately, one item that is commonly associated with HTML5 is javascript. Most of the programmers I work with are all applications programmers and thus know very little about javascript. While researching for some presentations I was putting together, I came across a great article that is essentially a refresher on Javascript. If you are familiar with other client side scripting or have learned Javascript in the past, then this article should be an easy read.

https://developer.mozilla.org/en/A_re-introduction_to_JavaScript


Leave a comment

XNA – Object or Character Dialog

Another one from the archives. This one is a goodie! Enjoy!

One thing that was important to me in my latest game was to have actual dialog show on the screen. When the player interacts with objects, I want a box to display on the screen to give them immediate feedback. Granted, my implementation makes some basic assumptions and is quite simple, it is working and scaling quite well for me. Here is a basic implementation:

using System;
using FarmGame.Inventory;
using FarmGame.TileEngine;

namespace FarmGame.Dialogue
{
    static class GameObjectDialogue
    {

        static public string GetOutput(InventoryItem item, GameObject go, out bool harvestable)
        {
            harvestable = false;

            if (go.thisType == GameObject.ObjectType.rock)
                return GetRockOutput(item, out harvestable);
            if (go.thisType == GameObject.ObjectType.bush)
                return GetBushOutput(item, out harvestable);
            if (go.thisType == GameObject.ObjectType.tree)
                return GetTreeOutput(item, out harvestable);
            if (go.thisType == GameObject.ObjectType.house)
                return GetHouseOutput(out harvestable);
            
            return string.Empty;
        }

        private static string GetHouseOutput(out bool harvestable)
        {
            harvestable = false;
            return "This is your house.";    
        }

        private static string GetTreeOutput(InventoryItem ii, out bool harvestable)
        {
            if (ii.ItemName == "axe")
            {
                harvestable = true;
                return "Press space to chop this tree.";
            }
            else
            {
                harvestable = false;
                return "You must have the axe equipped.";
            }
        }

        static public string GetRockOutput(InventoryItem ii, out bool harvestable)
        {
            if (ii.ItemName == "pickaxe")
            {
                harvestable = true;
                return "Press space to mine this rock.";
            }
            else
            {
                harvestable = false;
                return "You must have the pickaxe equipped.";
            }
        }

        static public string GetBushOutput(InventoryItem ii, out bool harvestable)
        {
            if (ii.ItemName == "scythe")
            {
                harvestable = true;
                return "Press space to harvest berries.";
            }
            else
            {
                harvestable = false;
                return "You must have the scythe equipped.";
            }
        }
    }
}

I won’t get too into the details as it should be self explanatory. In this case, you are passing in the equipped item and the object you are interacting with. It will then return if the object is harvestable. In my case, I have rocks, bushes, trees, and a house.

Calling it from your code is equally as simple. I have this in the update method of my level class:

            bool dialogBoxNeeded = false;

if (tileRect.Intersects(Player.fowardBox()))
                {
                    bool harvestable;

                    box.Position = new Vector2(tileRect.X + 5, tileRect.Y + 5);

                    //box.textHandler.Output = "Press space to mine this rock.";
                    box.textHandler.Output = GameObjectDialogue.GetOutput(Inventory.EquippedItem, go, out harvestable);
                    dialogBoxNeeded = true;

                    //check for action key
                    if (keyState.IsKeyDown(Keys.Space) && !prevKeyState.IsKeyDown(Keys.Space))
                    {
                        //add additional code here to return items 
                        if (harvestable)
                        {
                            Harvesting.Harvest(go, ref Inventory, ref GameObjects, CM);
                            //this.GameObjects.Remove(go);
                            return;
                        }
                    }
                }

                box.DrawBox = dialogBoxNeeded;

Basically, the player has a seperate bounding box that projects in front of them. We are checking this bounding box to see if it interacts with a game object. If so, we note the position for our box, determine the text, and flag the code as needing a dialog box.

Now we need to call the draw method:

            if (this.box.DrawBox)
                this.box.Draw(sb);

I’m not going to step through it, but here is the box class:

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Text;
using Microsoft.Xna.Framework.Content;

namespace FarmGame.UI_Elements
{
    class Box
    {
        public Text textHandler { get; set; }
        public Texture2D Texture { get; set; }
        public Vector2 Position { get; set; }
        public bool DrawBox { get; set; }

        //private int TextureWidth { get; set; }
        //private int TextureHeight { get; set; }

        private string Output;
        //StringBuilder sb;

        public Box(ContentManager cm)
        {
            this.Texture = cm.Load(@"UI\popuptext");

            textHandler = new Text(cm, @"Fonts\boxSpriteFont");
            textHandler.TextColor = Color.White;
        }

        public Box(ContentManager cm, string output, Vector2 coords)
        {
            this.Texture = cm.Load(@"UI\popuptext");
            this.Output = output;
            this.Position = coords;

            textHandler = new Text(cm, @"Fonts\boxSpriteFont");
            textHandler.TextColor = Color.White;
        }

        public void Draw(SpriteBatch sb)
        {
            sb.Draw(this.Texture, this.Position, null, Color.White );

            textHandler.FontPos = new Vector2(Position.X + 15, Position.Y + 15);
            textHandler.DrawText(sb);
        }
    }
}


Leave a comment

XNA – Basic Enemy AI

Here’s another from the archives!

One thing I was surprised to find in XNA, was just how simple it really ended up being to add some incredibly basic enemy AI and pathfinding. In my game, the enemies are dumped onto a platform and then are bound by all the same rules of gravity as the player. Initially, they all suffered from Super Mario Bros syndrome where they would just walk off the platform and die. The solution was surprisingly simple: read which way the enemy is facing, project out a separate bounding rectangle, and then go through all of the tiles in our map and see if there is an intersection. If there is not, then the enemy is at the end of the platform and needs to turn around. All of this is called from the update method of our enemy. Here is the relevant code:

public void PathFinding(GameTime gt)
{
int maxX = this.SpriteWidth; // *2;
bool endOfPathFound = true;



Rectangle pathFindingRect = new Rectangle();

if(direction == Direction.Right)
pathFindingRect = new Rectangle(((int)Position.X - this.SpriteWidth/2) + maxX, (int)(Position.Y -this.SpriteHeight) +1,
this.SpriteWidth, this.SpriteHeight);
else if(direction == Direction.Left)
pathFindingRect = new Rectangle(((int)Position.X - this.SpriteWidth / 2) - maxX, (int)(Position.Y - this.SpriteHeight) + 1,
this.SpriteWidth, this.SpriteHeight);

foreach (TileSprite ts in level.Map)
{
if (ts.Landable)
{
if (pathFindingRect.Intersects(ts.BoundingBox))
{
endOfPathFound = false;
}
}
}

if (endOfPathFound)
{
if (direction == Direction.Left)
direction = Direction.Right;
else if (direction == Direction.Right)
direction = Direction.Left;
}
}


4 Comments

XNA – Basic Inventory System, Part 1.

Here is another one dug up from the archives. Unfortunately, I haven’t been able to dig up part 2 yet.

So, you’ve started working on a game and have decided that you need an inventory system. What I have found is that this task really doesn’t have to be as difficult as it sounds. The first thing we need to do is create a class that will hold our inventory items.

using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace game.Inventory
{
    class InventoryItem
    {

I’ve created an enum to hold what type of item it is. In my case, I’ve got tools, crafting items, furnitue, etc.

       
//what type of item is it
        public enum InventoryType
        {
            craft,
            consumable,
            furniture,
            tool
        };
        public InventoryType thisType { get; set; }

        //the texture for any tool tips
        public Texture2D Texture { get; set; }

        //the number of the item that you have
        public int NumAvailable { get; set; }
        public string ItemName { get; set; }

        private int MaxQuantity = 99;

Everything else is basic properties and variables and should be pretty self explanatory. Texture is the texture that we will use to draw the icon for the onscreen inventory, numavailable is how many you have, itemname is the name of the item, and maxquantity is the maximum number allowed.

We have an empty constructor, and another one that populates the pertinent fields

        public InventoryItem()
        {
           //empty constructor
        }

        public InventoryItem(string name, int numAvailable, Texture2D texture, InventoryType type)
        {
            this.NumAvailable = numAvailable;
            this.Texture = texture;
            this.thisType = type;
            this.ItemName = name;
        }

Two add methods. One of this simply increments the quantity available and the other increments it by a set amount

        public void AddItems()
        {
            this.NumAvailable++;
            CheckMaxQuantity();
        }

        public void AddItems(int numToAdd)
        {
            this.NumAvailable += numToAdd;
            CheckMaxQuantity();
        }

Then we have our basic draw method and a simple method to make sure we never exceed our maximum quantity.

        public void Draw(SpriteBatch sb, Vector2 position)
        {
            sb.Draw(this.Texture, position, Color.White);
        }

        private void CheckMaxQuantity()
        {
            if (this.NumAvailable > MaxQuantity)
                NumAvailable = MaxQuantity;
        }

That’s it. In the next post, I’ll show how I pulled together the actual inventory class and how I am handling the inventory control, drawing of the ui, etc.


Leave a comment

XNA – Sprite Sheet Animation

Dug this article out from the old archives and thought I would post it here. Context might not make sense, but the basic code should work all the same. You can tie this into the tile engine tutorial.

Haven’t had too much time to do any programming this week, but I did just convert my player animation engine to animate a sprite based on a sprite sheet rather than a horizontal imageset. Here is the relevant code.

I realize that this needs to be more object oriented, but I’ll get there.
This is added to the animated sprite class:

public int YFrame
        {
            get { return yFrame; }
            set { yFrame = value; }
        }
        int yFrame = 0;

All the rest of the code is in the player class

private void AnimateLeft(GameTime gt)
        {
            if (currentKBState != previousKBState)
            {
                //CurrentFrame = 5;
                CurrentFrame = 0;
                YFrame = 1;
            }

            Timer += (float)gt.ElapsedGameTime.TotalMilliseconds;

            if (Timer > Interval)
            {
                CurrentFrame++;

                //if (CurrentFrame > 7)
                    //CurrentFrame = 4;
                if (CurrentFrame > 2)
                    CurrentFrame = 0;

                Timer = 0f;
            }
        }

        private void AnimateRight(GameTime gt)
        {
            if (currentKBState != previousKBState)
            {
                //CurrentFrame = 9;
                CurrentFrame = 0;
                YFrame = 2;
            }

            Timer += (float)gt.ElapsedGameTime.TotalMilliseconds;

            if (Timer > Interval)
            {
                CurrentFrame++;

                //if (CurrentFrame > 11)
                   //CurrentFrame = 8;
                if (CurrentFrame > 2)
                    CurrentFrame = 0;

                Timer = 0f;
            }
        }

SourceRect = new Rectangle(CurrentFrame * SpriteWidth, YFrame * SpriteHeight, SpriteWidth, SpriteHeight);

And that’s it. Just use the code that we had from the previous articles, and the animation will now pull from the sprite sheet.


Leave a comment

Creating your own game art

One thing that I have always struggled with is art, anything artsy actually. Quite frankly, I am a terrible artist. For this reason, game development has always been quite difficult for me as I either have to make my own horrible looking art, or find free art on the internet. While doing some research I ran across a great website here. This guy is able to take some art knowledge that I would consider fairly complex, and really dumb it down so that us non-artistic programmers can really “get it.” In particular, he has some great articles on drawing characters and tiles. I’ve used this as a great resource to help in my current game and have learned enough concepts that I can better my own art. So, go check him out!