C#프로그래밍

장비 착용, 몬스터 공격, 인벤토리, 아이템 지급

다모아 2023. 7. 28. 13:18

[저장불가]

App

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

namespace json
{
    public class App
    {
        private Game game;

        //생성자
        public App()
        {
            //게임 시작 전 아이템 불러오기
            DataManager.instance.LoadItemDatas();
            DataManager.instance.LoadMonsterDatas();

            this.game = new Game();
            this.game.Start();

            
        }
    }
}

 

Game

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

namespace json
{
    public class Game
    {
        private Hero hero;
        private Monster monster;
        private Item item;
        //생성자
        public Game()
        {

        }

        //게임 시작
        public void Start()
        {
            Console.WriteLine("게임시작");
            //영웅생성
            this.hero = this.CreateHero("홍길동", 3);
            //몬스터 생성
            this.monster = this.CreateMonster(1000);
            //아이템 생성
            this.item = this.CreateItem(100);
            this.monster.onDie = () =>
            {
                //아이템 생성
                int itemId = this.monster.GetItemID();
                Item dropItem = this.CreateItem(itemId);
                Console.WriteLine("아이템({0}){1}이 드롭 되었습니다.", dropItem.GetID(), dropItem.Name);
                //아이템 획득
                this.hero.SetItem(dropItem);

                int itemCount = this.hero.GetItemCount();
                Console.WriteLine(itemCount);
            };

            //영웅에게 인벤토리 생성
            Inventory bag = new Inventory(5);
            this.hero.SetBag(bag);

            //무기 (장검) 지급
            this.hero.SetItem(item); //가방 지급

            //무기 (장검) 장착
            this.hero.Equip(100); //아이템이 있는지 확인하고 인벤토리에서 꺼내서 착용

            //영웅이 몬스터를 공격
            this.hero.Attack(this.monster);

        }

        //영웅 생성
        public Hero CreateHero(string name, int damage)
        {
            Console.WriteLine("영웅 이름: {0}", name);
            Console.WriteLine("영웅 공격력: {0}\n", damage);
            return new Hero(name, damage);
        }

        //몬스터 생성
        public Monster CreateMonster(int id)
        {
            //몬스터 정보
            MonsterData monsterData = DataManager.instance.GetMonsterData(id);
            MonsterInfo monsterInfo = new MonsterInfo(monsterData.id, monsterData.item_id, monsterData.maxHp);
            Monster monster = new Monster(monsterInfo);
            int monsterId = monster.GetID();
            string monsterName = monster.Name;
            int monsterItemID = monster.GetItemID();
            int monsterHp = monster.GetHp();

            Console.WriteLine("몬스터 ID: {0}", monsterId);
            Console.WriteLine("몬스터 이름: {0}", monsterName);
            Console.WriteLine("몬스터 체력: {0}\n", monsterHp);

            //직렬화 객체 -> 문자열
            string monsterJson = JsonConvert.SerializeObject(monster.GetInfo());
            //파일 저장
            File.WriteAllText("./monster_info.json", monsterJson);

            return new Monster(monsterInfo);
        }

        //아이템 생성
        public Item CreateItem(int id)
        {
            //아이템 정보
            ItemData itemData = DataManager.instance.GetItemData(id);
            ItemInfo itemInfo = new ItemInfo(itemData.id, itemData.damage);
            Item item = new Item(itemInfo);
            int itemId = item.GetID();
            string itemName = item.Name;
            int itemDamage = item.GetDamage();

            //직렬화 객체 -> 문자열
            string itemJson = JsonConvert.SerializeObject(item.GetInfo());
            //파일 저장
            File.WriteAllText("./item_info.json", itemJson);

            return new Item(itemInfo);
        }
    }
}

 

Monster

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

namespace json
{
    public class Monster
    {
        public MonsterInfo info;
        public int sumDamage;
        public Action onDie;

        public string Name
        {
            get
            {
                MonsterData data = DataManager.instance.GetMonsterData(this.info.id);
                return data.name;
            }
        }
        //생성자
        public Monster(MonsterInfo info)
        {
            this.info = info;
        }

        //몬스터 가져오기
        public int GetID()
        {
            return this.info.id;
        }

        //몬스터 아이템 아이디 가져오기
        public int GetItemID()
        {
            return this.info.item_id;
        }

        //몬스터 체력 가져오기
        public int GetHp()
        {
            return this.info.hp;
        }

        //몬스터 정보 가져오기
        public MonsterInfo GetInfo()
        {
            return this.info;
        }

        //공격 당함
        public void HitDamage(int damage)
        {
            this.info.hp -= damage * int.MaxValue;

            if (this.info.hp <= 0)
            {
                this.info.hp = 0;
            }
            Console.WriteLine("공격(-{0})했습니다. 남은 체력 : {1}/{2}", damage, this.info.hp, this.info.maxHp);
            if (this.info.hp <= 0)
            {
                this.Die();
            }
        }

        //죽음
        public void Die()
        {
            Console.WriteLine("몬스터{0}가 사망했습니다.", this.info.id);
            //대리자 호출
            this.onDie();
        }
    }
}

 

Hero

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

namespace json
{
    public class Hero
    {
        private string name;
        private int damage;
        private Inventory bag;
        private Item leftHandItem;
        private int sumDamage;

        //생성자
        public Hero(string name, int damage)
        {
            this.name = name;
            this.damage = damage;
            this.sumDamage = damage;
        }

        //가방 지급
        public void SetBag(Inventory bag)
        {
            this.bag = bag;
        }

        //아이템 지급
        public void SetItem(Item item)
        {
            this.bag.AddItem(item);
        }

        //무기 장착
        //아이템이 있는지 확인하고 인벤토리에서 꺼내서 착용
        public void Equip(int id)
        {
            //100번 아이템이 인벤토리에 있다면
            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 monster)
        {
            sumDamage += leftHandItem.GetDamage();
            Console.Write("{0}이 {1}을/를 ", name, monster.Name);
            monster.HitDamage(sumDamage);
        }

        //아이템 수 세기
        public int GetItemCount()
        {
            return this.bag.Count;
        }
    }
}

 

Inventory

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

namespace json
{
    public class Inventory
    {
        private int capacity;
        private List<Item> items = new List<Item>();
        public int Count
        {
            get
            {
                return this.items.Count;
            }
        }
        //생성자
        public Inventory(int capacity)
        {
            this.capacity = capacity;
        }

        //아이템 추가
        public void AddItem(Item item)
        {
            this.items.Add(item);
            Console.WriteLine("{0}, {1}이 가방에 들어갔습니다.", item.GetID() ,item.Name);
        }

        //아이템 탐색
        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 < 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 < items.Count; i++)
            {
                if (this.items[i].GetID() == id)
                {
                    foundItem = this.items[i];
                    //리스트에서 제거
                    this.items.Remove(foundItem);
                    break;
                }
            }
            return foundItem;
        }
    }
}

 

MonsterData

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

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

 

MonsterInfo

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

namespace json
{
    public class MonsterInfo
    {
        public int id;
        public int item_id;
        public int maxHp;
        public int hp;

        //생성자
        public MonsterInfo(int id, int item_id, int maxHp)
        {
            this.id = id;
            this.item_id = item_id;
            this.maxHp = maxHp;
            this.hp = maxHp;
        }
    }
}

 

Item

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

namespace json
{
    public class Item
    {
        public ItemInfo info;
        public string Name
        {
            get
            {
                ItemData data = DataManager.instance.GetItemData(this.info.id);
                return data.name;
            }
        }
        //생성자
        public Item(ItemInfo info)
        {
            this.info = info;
        }

        //아이템 가져오기
        public int GetID()
        {
            return this.info.id;
        }

        //공격력 가져오기
        public int GetDamage()
        {
            return this.info.damage;
        }

        //아이템 정보 가져오기
        public ItemInfo GetInfo()
        {
            return this.info;
        }
    }
}

 

ItemData

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

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

 

ItemInfo

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

namespace json
{
    public class ItemInfo
    {
        public int id;
        public int damage;
        //생성자
        public ItemInfo(int id, int damage)
        {
            this.id = id;
            this.damage = damage;
        }
    }
}

 

DataManager

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

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

        }

        //아이템 로드하기
        public void LoadItemDatas()
        {
            //아이템 데이터 불러오기
            string itemJson = File.ReadAllText("./item_data.json");
            //역직렬화 문자열 -> 객체
            ItemData[] itemData = JsonConvert.DeserializeObject<ItemData[]>(itemJson);
            //ItemData[]에 Dictionary로 넣어주기
            dicItemData = itemData.ToDictionary(x => x.id);
        }

        public void LoadMonsterDatas()
        {
            //몬스터 데이터 불러오기
            string monsterJson = File.ReadAllText("./monster_data.json");
            //역직렬화 문자열 -> 객체
            MonsterData[] monsterData = JsonConvert.DeserializeObject<MonsterData[]>(monsterJson);
            //MonsterData[]에 Dictionary로 넣어주기
            dicIMonsterData = monsterData.ToDictionary(x => x.id);
        }

        //아이템 가져오기
        public ItemData GetItemData(int id)
        {
            return this.dicItemData[id];
        }

        //몬스터 가져오기
        public MonsterData GetMonsterData(int id)
        {
            return this.dicIMonsterData[id];
        }
    }
}

[저장불가]

 

datamanager - 변하지않는 데이터 관리
infomanager - 변하는 데이터 관리


App
게임시작 전 아이템 불러오기
Game클래스로 게임시작하기
----------------------------

Game
----------------------------
영웅
몬스터
아이템
----------------------------
Start메서드
영웅,몬스터,아이템 생성
몬스터가 죽으면 .. 대리자
// 아이템 생성 , 아이템 획득
영웅에게 인벤토리 생성
무기 지급
무기 장착
영웅이 몬스터 공격

영웅 생성
몬스터 생성
아이템 생성
----------------------------

DataManager ---> 변하지않는 데이터 관리
----------------------------
instance 생성
ItemData와 MonsterData의 객체생성
----------------------------
아이템 로드하기
몬스터 로드하기
아이템 가져오기
몬스터 가져오기

Hero
----------------------------
이름
공격력
인벤토리
왼손
영웅공격력 + 무기공격력
----------------------------
가방지급
아이템지급
무기장착
--> 아이템이 있는지 확인하고 인벤토리에서 꺼내서 착용...Exist메서드 생성 .. 100번 아이템이 인벤토리에 있다면
몬스터 공격
아이템 수 세기

Item
----------------------------
info
Name ... > info에서 name 추출
----------------------------
아이템 가져오기
공격력 가져오기
아이템 정보 가져오기

ItemData
----------------------------
ID
name
damage

ItemInfo
----------------------------
id
damage

Monster
----------------------------
info
onDie ---> Action 대리자
Name ...> name 가져오기
----------------------------
몬스터 가져오기
몬스터 아이템 아이디 가져오기
몬스터 체력 가져오기
몬스터 정보 가져오기
공격 당함
죽음...>대리자 호출

MonsterData
----------------------------
id
name
item_id
maxHp

MonsterInfo
----------------------------
id
item_id
maxHp
hp
----------------------------


[저장가능]

App
기존유저 , 신규유저인지 확인
기존유저 : 역직렬화
신규유저 : 직렬화

객체에 저장하기

GameInfo
게임정보 저장객체[아이템 정보들]
신규유저 초기화

InfoManager
저장해야하는 정보들을 관리하는 싱글톤 클래스

ItemInfo
아이템 정보

Item
아이템 정보들을 사용?

Hero
아이템 추가와 아이템 가져오기
[아이템에서]


직렬화 역직렬화 , 객체에서 정보를 꺼내서 가져오는거 연습
가장 적은 데이터로 먼저 저장하는 연습하기





과제
게임 미션 구현하기
불러오기 저장하기
변하지 않는 데이터 - 이름 엑셀로 만들고
변하는 데이터는 저장
보상 받았냐 안받았냐 등등,,

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

FindItemName, Find, List  (0) 2023.07.31
주말과제  (0) 2023.07.28
JSON  (0) 2023.07.27
엑셀데이터를 JSON, JSON online viewer  (0) 2023.07.27
람다, Action<T> , Func<T>  (0) 2023.07.27