본문 바로가기
KDT/C# 프로그래밍

23/07/28 게임 세팅

by 잰쟁 2023. 7. 28.
728x90

App

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

namespace starcraft
{
    public class App
    {
        private Game game;

        //생성자
        public App()
        {
            //------------준비--------------------
            DataManager.instance.LoadItemData();
            DataManager.instance.LoadMonsterData();
            //------------------------------------

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

        }     
    }

DataManager

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

namespace starcraft
{
 
    public class DataManager
    {
         public static readonly DataManager instance = new DataManager();
        //딕셔너리(사전)에 저장
        //키(id)로 빠르게 검색 가능!
        private Dictionary<int, ItemData> dicItemDatas = new Dictionary<int, ItemData>();
        private Dictionary<int, MonsterData> dicMonsterDatas;

        //생성자
        private DataManager() 
        { 
        
        }
        public void LoadItemData()
        {
            //파일 읽기
            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 LoadMonsterData()
        {
            //파일 읽기
            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];
        }
    }
}

ItemData

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

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

Item

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

namespace starcraft
{
    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;
        }
    }
}

MonsterData

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

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

Monster

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

namespace starcraft
{
    public class Monster
    {
        //맴버
        private MonsterData data;
        private int maxHp;
        private int hp;
        public Action onDie;

        //생성자
        public Monster(MonsterData data)
        {
            this.data = data;
            this.maxHp = data.maxHp;
            this.hp = maxHp;
            Console.WriteLine("id : {0}, 체력 : {1}/{2}", data.id, 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();
            }
        }

        //사망 메서드
        private void Die()
        {
            Console.WriteLine("몬스터({0})가 죽었습니다ㅜㅜ", this.data.name);
            //대리자 호출
            this.onDie();
        }

        //아이템아이디 메서드
        public int GetItemId()
        {
            return this.data.item_id;
        }
    }
}

Hero

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

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

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

        //가방 착용 메서드
        public void SetBag(Inventory bag)
        {
            this.bag = bag;
        }

        //아이템 가방에 넣기 메서드
        public void SetItem(Item item)
        {
            this.bag.AddItem(item);
        }

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

        //몬스터 공격 메서드
        public void Attack(Monster target)
        {
            Console.WriteLine("영웅({0})이 몬스터를 공격했습니다. (-{1})",this.name,this.damage);
            target.HitDamage(this.damage);
        }

        //아이템 수 세기 메서드
        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 starcraft
{
    public class Inventory
    {
        //맴버
        private List<Item> items = new List<Item>();   //사용전 초기화!!
        private int capacity;
        public int Count
        {
            get
            {
                return items.Count;
            }
        }

        //생성자
        public Inventory(int capacity)
        {
            this.capacity = capacity;  //용량
            this.items = new List<Item>();
            Console.WriteLine("가방을 생성했습니다. [{0}/{1}]", items.Count, this.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;
        }

        //id로 아이템 검색 메서드
        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];
                    //리스트에서 제거
                    this.items.Remove(foundItem);
                    break;
                }
            }
            return foundItem;
        }
    }
}

Game

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

namespace starcraft
{
    internal 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);
            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);

            //무기(장검) 영웅에게 지급
            Item item = this.CreateItem(100);
            this.hero.SetItem(item);  //가방에 넣기

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

            //영웅 몬스터 공격 & 몬스터 피해입음(죽음) & 아이템 드롭
            this.hero.Attack(monster);        
            
        }

        //아이템 생성 메서드
        public Item CreateItem(int id)
        {
            ItemData data = DataManager.instance.GetItemData(id);
            return new Item(data);
        }

        //영웅 생성 메서드
        public Hero CreateHero(string name, int damage)
        {
            return new Hero(name,damage);
        }

        //몬스터 생성 메서드
        public Monster CreateMonster(int id) 
        {
            MonsterData data = DataManager.instance.GetMonsterData(id);  //id로 찾은 데이터매니저에 있는 몬스터데이터를 불러옴
            Console.WriteLine("몬스터({0})가 생성되었습니다.", data.name);
            return new Monster(data);
        }
    }
}

출력 결과^^!!!!!!!!!!!!!!!!!!!!

 

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

23/07/30 과제(미션)  (1) 2023.07.30
23/07/27 과제(복습)  (0) 2023.07.27
23/07/27 아이템 정보 저장하기  (0) 2023.07.27
23/07/27 대리자 연습  (0) 2023.07.27
23/07/27 Action 대리자  (0) 2023.07.27