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

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;
}
}


Leave a comment

XNA – Add bullets to our overhead game

This tutorial is a continuation from https://joshcodev.wordpress.com/2012/10/25/xna-lets-break-down-our-simple-overhead-game-and-start-making-classes/ . If you have not yet completed this tutorial, you will need to follow it before following this one as we further use our custom classes. If you are just here to learn about shooting bullets, then you do not need the previous tutorial.

Before we can start this tutorial, we need a bullet. Here is a cheesy one you can download or you can create your own. For the sake of this tutorial, just make sure it is a 16×16 image unless you are comfortable enough modifying this code.
Continue reading


Leave a comment

XNA – Let’s break down our simple overhead game and start making classes

This is a continuation from https://joshcodev.wordpress.com/2012/10/25/xna-make-a-sprite-face-your-mouse/ . If you have not yet followed this tutorial, it might be a good time to check it out.

Our old code was simple and worked, so why split it out into classes? Well, mostly because it makes the code easier to work with as we add more code and expand the game. For example, what if we make the game two players? You’d have to create another texture, a second block of draw statements, a second block of update statements, etc. Or when we start to fire bullets. We don’t want to have to create X number of bullets in our constructor, show and hide them, track each one, etc. Classes allow us to easily move the code over to manageable classes that can be re-used.

Let’s start by creating a new class in our projet named sprite.cs. This class will hold our information that will be common across all sprites.
Let’s add our normal using statement.

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

Continue reading


2 Comments

Basic Tile Engine Tutorial – Creating our player class base

Update As with the other tutorials. I have whipped up a new solution for everything that we have covered so far and placed it here. Please feel free to download and have a working demo. I have also cleaned up the code a bit from the tutorial. Going forward, I will try to invest the time needed to clean up the code as I write the tutorials.

This is the third tutorial in our tile engine series. This tutorial will cover starting our player class to make our game playable! Please be sure that you have followed the previous tutorial located here first. This is probably the one component that if I had to do everything over again, I would have done it different. Revisiting this, I likely would have implemented a physics engine such as farseer.

-Start by adding a new class to your project and name it animatedSprite.
-As usual, add all the xna namespaces
Continue reading


1 Comment

Basic Tile Engine Tutorial – Creating our map class

(Update) Just like our first tutorial, I have been recreating this tutorial from scratch to give you a code example. You can download this example here. Also, I have added another method that was missing from the original post named addNewSprite. I’ve also taken the time to really clean up the code and make it more readable.

This is the second part of our basic tile engine tutorial. This tutorial will cover the major programming concepts needed to create a platformer type game. In the previous tutorial, we covered creating our tile class which will be used for our individual tiles. You can find this tutorial if you missed it.

Now that we have our basic tile sprite class, we can start building out our class that will hold our map. Start by creating a new class and naming it Level.cs.

-Include the usual stuff. These are all the namespaces that are needed by default in an XNA game.

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Xml;
using System.IO;

Continue reading