아카이브

json 연습(몬스터, 영웅, 아이템, 인벤토리 ) 본문

C#프로그래밍

json 연습(몬스터, 영웅, 아이템, 인벤토리 )

timbercat 2023. 7. 28. 14:43

program.cs

using System;

namespace LearnDotnet
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //new키워드: App클래스의 인스턴스 생성하고 생성자 호출
            new App();                                     
        }        
    }
}

App.cs

using System;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

namespace LearnDotnet
{
    public class App
    {
        private Game game;
        //생성자
        public App()
        {
            DataManager.instance.LoadItemDatas();
            DataManager.instance.LoadMonsterDatas();

            //서비스 시작
            this.game = new Game();
            this.game.Start();
        }
    }
}

ItemData.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class ItemData
    {
        public int id;
        public string name;
        public int damage;
    }
}

MonsterData.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class MonsterData
    {
        public int id;
        public string name;
        public int item_id;
        public int maxHp;
    }
}

Item.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class Item
    {
        private ItemData data;
        public string Name
        {
            get
            {
                return this.data.name;
            }
        }
        public Item(ItemData data)
        {
            this.data = data;
        }

        public int GetID()
        {
            return this.data.id;
        }
    }
}

Monster.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class Monster
    {
        private MonsterData data;
        private int maxHp;
        private int hp;
        public Action onDie;

        public Monster(MonsterData data) 
        { 
            this.data = data;
            this.maxHp = this.data.maxHp;
            this.hp = this.maxHp;

            Console.WriteLine("id: {0}, 체력: {0}/{1}", this.hp, this.maxHp);
        }

        public void HitDamage(int damage)
        {
            this.hp -= damage * int.MaxValue;
            if(this.hp <= 0)
            {
                this.hp = 0;
            }
            Console.WriteLine("공격을 받았습니다. 체력 : {0}/{1}", this.hp, this.maxHp);
            if(this.hp <= 0)
            {
                this.Die();
            }
        }

        public void Die()
        {
            Console.WriteLine("몬스터 {0}가 처리되었습니다.", this.data.id);
            //대리자 호출
            this.onDie();
        }
    }
}

Inventory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class Inventory
    {
        private int capacity;
        private List<Item> items = new List<Item>();

        //생성자 
        public Inventory(int capacity)
        {
            this.capacity = capacity;   //수용량 
        }

        public void Add(Item item)
        {
            this.items.Add(item);
        }

        public bool Exist(int id)
        {
            Item item = this.items.Find(x => x.GetID() == id);
            if (item == null)
                return false;
            else
                return true;

            //for (int i = 0; i < this.items.Count; i++) {
            //    if (this.items[i].GetID() == id) {
            //        Console.WriteLine("찾았다!");
            //        return true;
            //    } 
            //}
            //return false;
        }

        public Item GetItem(int id)
        {
            //return this.items.Find(x => x.GetID() == id);

            Item foundItem = null;
            for (int i = 0; i < this.items.Count; i++)
            {
                if (this.items[i].GetID() == id) 
                {
                    foundItem = this.items[i];
                    break;
                }                
            }
            return foundItem;
        }
    }
}

Hero.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class Hero
    {
        private int damage;
        private string name;
        private Inventory bag;
        private Item item;
        private Item leftHandItem;

        //생성자 
        public Hero(string name, int damage)
        {
            this.name = name;
            this.damage = damage;
            Console.WriteLine("영웅({0})이 생성되었습니다, damage: {1}", this.name, this.damage);
        }

        public void SetBag(Inventory bag)
        {
            this.bag = bag;
            Console.WriteLine("가방({0})을 지급 받았습니다.", this.bag);
        }

        public void SetItem(Item item)
        {
            this.item = item; 
        }

        public void Equip(int id)
        {
            //가방에 아이템이 있는지 검색
            if (this.bag.Exist(id))
            {
                //착용
                this.leftHandItem = this.bag.GetItem(id);
                Console.WriteLine("왼손에 아이템({0})을 착용 했습니다.", leftHandItem.Name);
            }
            else
            {
                Console.WriteLine("아이템({0})를 찾을수 없습니다.", id);
            }
        }      
        
        public void Attack(Monster target)
        {
            target.HitDamage(this.damage);
        }
    }
}

Game.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class Game
    {
        private Hero hero;
        private Monster monster;

        //생성자
        public Game()
        {

        }

        public void Start()
        {
            Console.WriteLine("게임이 시작 되었습니다.");
            //영웅이 생성됨 
            this.hero = this.CreateHero("홍길동", 3);
            //몬스터가 생성됨 
            this.monster = this.CreateMonster(1000);

            Inventory bag = new Inventory(5);   //가방을 만들기 
            this.hero.SetBag(bag);  //가방을 지급 

            //무기 지급
            Item item = this.CreateItem(100);
            this.hero.SetItem(item);

            //장비착용
            this.hero.Equip(100);

            //몬스터 공격
            this.hero.Attack(monster);
        }

        public Hero CreateHero(string name, int damage)
        {
            return new Hero(name, damage);
        }

        public Monster CreateMonster(int id)
        {
            MonsterData data = DataManager.instance.GetMonsterData(id);
            return new Monster(data);
        }

        public Item CreateItem(int id)
        {
            ItemData data = DataManager.instance.GetItemData(id);
            return new Item(data);
        }
    }
}

DataManager.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    public class DataManager
    {
        public static readonly DataManager instance = new DataManager();
        private Dictionary<int, ItemData> dicItemDatas = new Dictionary<int, ItemData>();
        private Dictionary<int, MonsterData> dicMonsterDatas;
        //생성자 
        private DataManager()
        {

        }

        public void LoadItemDatas()
        {
            //파일 읽기 
            var json = File.ReadAllText("./item_data.json");
            //Console.WriteLine(json);
            //역직렬화 하면 ItemData객체들을 요소로 하는 배열 객체가 나온다 
            ItemData[] itemDatas = JsonConvert.DeserializeObject<ItemData[]>(json);
            foreach (var data in itemDatas)
                dicItemDatas.Add(data.id, data);
            Console.WriteLine("아이템 데이터 로드 완료: {0}", dicItemDatas.Count);
        }

        public void LoadMonsterDatas()
        {
            //파일 읽기 
            var json = File.ReadAllText("./monster_data.json");
            //Console.WriteLine(json);
            //역직렬화 하면 ItemData객체들을 요소로 하는 배열 객체가 나온다 
            MonsterData[] monsterDatas = JsonConvert.DeserializeObject<MonsterData[]>(json);
            dicMonsterDatas = monsterDatas.ToDictionary(x => x.id); //새로운 사전객체가 만들어진다 
            Console.WriteLine("몬스터 데이터 로드 완료: {0}", dicMonsterDatas.Count);
        }

        public MonsterData GetMonsterData(int id)
        {
            return this.dicMonsterDatas[id];
        }

        public ItemData GetItemData(int id)
        {
            return this.dicItemDatas[id];
        }
    }
}

 

'C#프로그래밍' 카테고리의 다른 글

직렬화 역직렬화 연습  (0) 2023.07.28
Action 대리자 연습(HitDamage)  (0) 2023.07.27
Action 대리자 연습  (0) 2023.07.27
Dictionary 인벤토리*  (0) 2023.07.26
Dictionary 연습2  (0) 2023.07.26