Home > Enterprise >  Items for console game c#
Items for console game c#

Time:10-17

I am new to coding and making a text based console rpg game. I want to implement an item based combat system, the problem being that I am unsure how to create new items with names and stats from a class. Could I be given an example of a simple item class to which I can easily call and create a new item?

CodePudding user response:

You could use a Dictionary to manage your items so that you could spawn them or create them dynamically in your game. Here is a little example below.

Program.cs:

using System;
using System.Collections.Generic;

namespace RPGGame
{
    class Program
    {
        static Dictionary<string, Item> items;

        static void Main(string[] args)
        {
            //
            items = new Dictionary<string, Item>();

            items.Add("sword", new Item("Gold Sword"));

            items["sword"].AddStat("Sharp");
            items["sword"].AddStat("Magic");
            items["sword"].AddStat("Attack");

            Console.WriteLine("Item: "   items["sword"].GetName());

            Console.WriteLine("Stats: ");

            foreach (string stats in items["sword"].GetStats())
            {
                //
                Console.WriteLine(" - "   stats);
            }
        }
    }
}

Item.cs:

using System;
using System.Collections.Generic;

namespace RPGGame
{
    public class Item
    {
        private string name;
        private List<string> stats;

        public Item(string name)
        {
            //
            this.name = name;
            this.stats = new List<string>();
        }

        public void SetName(string name)
        {
            //
            this.name = name;
        }

        public string GetName()
        {
            //
            return name;
        }

        public void AddStat(string stat)
        {
            //
            stats.Add(stat);
        }

        public List<string> GetStats()
        {
            //
            return stats;
        }
    }
}

  • Related