'C#/수업내용'에 해당되는 글 13건

  1. 2019.05.07 2D Animation, Mecanim, Background
  2. 2019.04.25 Damage Text 출력하기
  3. 2019.04.04 Generic, Dictionary, Json을 이용한 데이터 처리
  4. 2019.04.04 ItemData구현
  5. 2019.04.03 Dictionary를 이용한 Inventory구현 및 Json사용
  6. 2019.04.02 Inventory구현 (창고이동, 제작, 목록 등등)
  7. 2019.04.01 Inventory를 다시 Array로 되돌리기
  8. 2019.04.01 제너릭 클래스, 상속을 이용하여 Inventory 만들기

2D Animation, Mecanim, Background

C#/수업내용 2019. 5. 7. 18:32

Animation 만들고 Mecanim Parameters 이용하여 재생, Background, Tile 반복이동



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class TestSunnyLand : MonoBehaviour
{
    public Button idleBtn;
    public Button runBtn;
    public Button jumpBtn;
    public GameObject player;
    public GameObject backGround;
    public GameObject tile;
    private Animator anim;
    private bool move;
 
    private void Awake()
    {
        this.anim = this.player.gameObject.GetComponent<Animator>();
    }
 
    public void Start()
    {
        this.StartGame();
    }
 
    public void StartGame()
    {
        this.idleBtn.onClick.AddListener(() =>
        {
            StartCoroutine(this.OnCompleteAnim("isIdle"));
        });
        this.runBtn.onClick.AddListener(() =>
        {
            StartCoroutine(this.OnCompleteAnim("isRun"));
        });
        this.jumpBtn.onClick.AddListener(() =>
        {
            StartCoroutine(this.OnCompleteAnim("isJump"));
            StartCoroutine(this.Jump());
        });
    }
 
    private IEnumerator MoveBackground()
    {
        while (this.move)
        {
            this.backGround.transform.position = new Vector3(Mathf.Repeat(Time.time, 15), this.backGround.transform.position.y, this.backGround.transform.position.z);
            yield return null;
        }
    }
    private IEnumerator MoveTile()
    {
        while (this.move)
        {
            if (this.tile.transform.position.x > -5f)
            {
                this.tile.transform.position = new Vector3(this.tile.transform.position.x - 1.5f * Time.deltaTime, this.tile.transform.position.y, this.tile.transform.position.z);
                yield return null;
            }
            else
            {
                this.tile.transform.position = new Vector3(000);
            }
        }
    }
 
    private IEnumerator OnCompleteAnim(string name)
    {
        var state = this.anim.GetCurrentAnimatorStateInfo(0);
        if(name == "isRun")
        {
            this.anim.SetBool("isIdle"false);
            this.anim.SetBool("isRun"true);
            this.move = true;
            StartCoroutine(this.MoveTile());
            StartCoroutine(this.MoveBackground());
            yield return new WaitForSeconds(this.anim.GetCurrentAnimatorStateInfo(0).length);
        }
        else if(name == "isIdle")
        {
            this.anim.SetBool("isRun"false);
            this.anim.SetBool("isIdle"true);
            this.move = false;
        }
        else if(name == "isJump")
        {
            if(state.IsName("isIdle"))
            {
                this.StopAllAnim();
                this.anim.SetBool(name, true);
                yield return new WaitForSeconds(this.anim.GetCurrentAnimatorStateInfo(0).length);
                this.anim.SetBool(name, false);
                this.anim.SetBool("isIdle"true);
            }
            else if(state.IsName("isRun"))
            {
                this.move = true;
                StartCoroutine(this.MoveTile());
                StartCoroutine(this.MoveBackground());
                this.anim.SetBool("isIdle"false);
                this.anim.SetBool(name, true);
                yield return new WaitForSeconds(this.anim.GetCurrentAnimatorStateInfo(0).length);
                this.anim.SetBool(name, false);
                this.anim.SetBool("isRun"true);
            }
        }
    }
 
    private void StopAllAnim()
    {
        var state = this.anim.runtimeAnimatorController.animationClips;
        foreach(var anim in state)
        {
            this.anim.SetBool(anim.name, false);
        }
    }
 
    private IEnumerator Jump()
    {
        bool isJump = true;
        while (true)
        {
            if (isJump)
            {
                this.player.transform.position = new Vector3(this.player.transform.position.x, this.player.transform.position.y + 5f * Time.deltaTime, 0);
                if (this.player.transform.position.y > 1)
                {
                    isJump = false;
                }
            }
            else if (!isJump)
            {
                this.player.transform.position = new Vector3(this.player.transform.position.x, this.player.transform.position.y - 5f * Time.deltaTime, 0);
                if (this.player.transform.position.y <= 0.1f)
                {
                    this.player.transform.position = new Vector3(this.player.transform.position.x, 00);
                    break;
                }
 
            }
            yield return null;
        }
    }
}
 
cs


:

Damage Text 출력하기

C#/수업내용 2019. 4. 25. 18:17


WorldToScreenPoint를 이용하여 캐릭터의 상단에 데미지 텍스트를 출력함


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class TestHudText : MonoBehaviour
{
    public Button btn;
    public Button btn2;
    public GameObject pivot;
    public Transform hudPoint;
    public Text txt0; //worldspace point
    public Text txt1; //viewport point
    public Text txt2; //spaceport point
    private Canvas canvas;
 
    private void Awake()
    {
        this.canvas = FindObjectOfType<Canvas>();
    }
 
    private void Start()
    {
        this.btn.onClick.AddListener(() =>
        {
            //프리팹 로드
            var hudPre = Resources.Load<HUDDamageText>("Prefabs/Test/HUDDamageText");
            //인스탄트
            var screenPoint = Camera.main.WorldToScreenPoint(this.hudPoint.position);
            var targetLocalPos = new Vector3(screenPoint.x - Screen.width / 2, screenPoint.y - Screen.height / 2, screenPoint.z);
            this.pivot.GetComponent<RectTransform>().anchoredPosition = targetLocalPos;
            var hud = Instantiate(hudPre);
 
            //인잇 메서드 호출(텍스트랑 컬러)
            Color color = new Color(100);
            hud.Init("456", color);
 
            //부모 Canvas로 설정
            hud.transform.SetParent(this.pivot.transform, false);
 
            //초기화
            hud.transform.localPosition = Vector3.zero;
 
            //타겟 포지션            
            Debug.LogFormat("{0},{1},{2}", targetLocalPos.x, targetLocalPos.y, targetLocalPos.z);
            Debug.LogFormat("{0},{1},{2}", screenPoint.x, screenPoint.y, screenPoint.z);
            var target = new Vector3(01000);
            DOTween.ToAlpha(() => hud.txt.color, x => hud.txt.color = x, 00.5f);
 
            hud.transform.DOScale(new Vector3(222), 0.3f).OnComplete(() =>
            {
                hud.transform.DOScale(new Vector3(111), 0.2f);
            });
            hud.transform.DOLocalMove(target, 1.5f).SetEase(Ease.OutBack).OnComplete(() =>
            {
                Destroy(hud.gameObject);
            });
        });
 
        this.btn2.onClick.AddListener(() =>
        {
            Debug.LogFormat("hudPoint world coordinate : {0}"this.hudPoint.position);
            this.txt0.text = this.hudPoint.position.ToString();
            var viewPortPoint = Camera.main.WorldToViewportPoint(this.hudPoint.position);
            this.txt1.text = viewPortPoint.ToString();
            var screenPoint = Camera.main.WorldToScreenPoint(this.hudPoint.position);
            this.txt2.text = screenPoint.ToString();
        });
    }
}
 
cs


:

Generic, Dictionary, Json을 이용한 데이터 처리

C#/수업내용 2019. 4. 4. 16:52
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class RawData
    {
        public int id;
        public RawData()
        {
 
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class WeaponData : RawData
    {
        public string name;
        public int level;
        public int damage_min;
        public int damage_max;
 
        public WeaponData(int id, string name, int level, int min, int max)
        {
                this.id = id;
                this.name = name;
                this.level = level;
                this.damage_min = min;
                this.damage_max = max;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class WeaponInfo
    {
        public int id;
        public int damage;
        public WeaponInfo(int id, int damage_min, int damage_max)
        {
            Random rand = new Random();
            this.id = id;
            this.damage = rand.Next(damage_min, damage_max);
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class WeaponItem
    {
        public WeaponInfo info;
        public WeaponItem(WeaponInfo info)
        {
            this.info = info;
        }
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class ArmorData :RawData
    {
        public string name;
        public int level;
        public int armor_min;
        public int armor_max;
 
        public ArmorData(int id, string name, int level, int min, int max)
        {
            this.id = id;
            this.name = name;
            this.level = level;
            this.armor_min = min;
            this.armor_max = max;
        }
    }
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class ArmorInfo :RawData
    {
        public int armor;
        public ArmorInfo(int id, int armor_min, int armor_max)
        {
            Random rand = new Random();
            this.id = id;
            this.armor = rand.Next(armor_min, armor_max);
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class ArmorItem
    {
        public ArmorInfo info;
        public ArmorItem(ArmorInfo info)
        {
            this.info = info;
        }
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class CharStatData :RawData
    {
        public string name;
        public int main_stat_id;
        public float main_stat_val;
        public int sub_stat_id;
        public float sub_stat_val;
 
        public CharStatData(int id, string name, int main_stat_id, float main_stat_val, int sub_stat_id, float sub_stat_val)
        {
            this.id = id;
            this.name = name;
            this.main_stat_id = main_stat_id;
            this.main_stat_val = main_stat_val;
            this.sub_stat_id = sub_stat_id;
            this.sub_stat_val = sub_stat_val;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class StatData :RawData
    {
        public string name;
        public StatData(int id, string name)
        {
            this.id = id;
            this.name = name;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
 
namespace Study_0404
{
    public class App
    {
        public Dictionary<int, WeaponData> dicWeaponItem;
        public Dictionary<int, ArmorData> dicArmorItem;
        public Dictionary<int, StatData> dicStatData;
        public Dictionary<int, CharStatData> dicCharStatData;
 
        public App()
        {
            dicWeaponItem = new Dictionary<int, WeaponData>();
            dicArmorItem = new Dictionary<int, ArmorData>();
            dicStatData = new Dictionary<int, StatData>();
            dicCharStatData = new Dictionary<int, CharStatData>();
        }
        
        public void Start()
        {
            LoadData("./Data/weapon_data.json", dicWeaponItem);
            LoadData("./Data/armor_data.json", dicArmorItem);
            LoadData("./Data/stat_data.json", dicStatData);
            LoadData("./Data/char_stat_data.json", dicCharStatData);
            for(int i = 0; i < 5; i++)
            { 
                Console.WriteLine("{0}",dicWeaponItem[i].name);
            }
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("{0}",dicArmorItem[i].name);
            }
            for (int i = 100; i < 105; i++)
            {
                Console.WriteLine("{0}",dicStatData[i].name);
            }
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("{0}{1}",dicCharStatData[i].id, dicCharStatData[i].name);
            }
        }
 
        //data load method
        public void LoadData<T>(string path, Dictionary<int, T> dictionary) where T : RawData
        {
            var str = File.ReadAllText(path);
            var arrJson = JsonConvert.DeserializeObject<T[]>(str);
            foreach(var json in arrJson)
            {
                dictionary.Add(json.id, json);
            }
        }
        
        //아이템 인스턴스화
        /*
        public WeaponItem CreateItem(int id, int type)
        {
            Random rand = new Random();
            if(type == 0)
            {
                int damageOrArmor = rand.Next(dicWeaponItem[id].damage_min, dicWeaponItem[id].damage_max);
                ItemInfo info = new ItemInfo(id, type, damageOrArmor);
                return new WeaponItem(info);
            }
            else if(type == 1)
            {
                int damageOrArmor = rand.Next(dicArmorItem[id].armor_min, dicArmorItem[id].armor_max);
                ItemInfo info = new ItemInfo(id, type, damageOrArmor);
                return new WeaponItem(info);
            }
            return default(WeaponItem);
        }
        */
 
    }
}
 
cs


'C# > 수업내용' 카테고리의 다른 글

2D Animation, Mecanim, Background  (0) 2019.05.07
Damage Text 출력하기  (0) 2019.04.25
ItemData구현  (0) 2019.04.04
Dictionary를 이용한 Inventory구현 및 Json사용  (0) 2019.04.03
Inventory구현 (창고이동, 제작, 목록 등등)  (0) 2019.04.02
:

ItemData구현

C#/수업내용 2019. 4. 4. 15:07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
 
namespace Study_0404
{
    public class App
    {
        private string[] arrDataName = { "weapon_data.json""armor_data.json""stat_data.json""char_stat_data.json" };
        public Dictionary<int, ItemData> dicWeaponItem;
        public Dictionary<int, ItemData> dicArmorItem;
        public List<Item> inventory;
 
        public App()
        {
            dicWeaponItem = new Dictionary<int, ItemData>();
            dicArmorItem = new Dictionary<int, ItemData>();
            inventory = new List<Item>();
        }
 
 
        public void Start()
        {
            this.LoadAllData();
            for(int index=0; index<6; index++)
            {
                inventory.Add(this.CreateItem(index, 0));
                inventory.Add(this.CreateItem(index, 1));
 
            }
            for(int index = 0; index < inventory.Count; index++)
            {
                Console.WriteLine("pointer id : {0}", index);
                if(inventory[index].info.type == 0)
                {
                    Console.WriteLine("{0}.{1} Lv.{2} Dmg.{3}", inventory[index].info.id, dicWeaponItem[inventory[index].info.id].name, dicWeaponItem[inventory[index].info.id].level, inventory[index].info.damage);
                }
                if(inventory[index].info.type == 1)
                {
 
                    Console.WriteLine("{0}.{1} Lv.{2} Arm.{3}", inventory[index].info.id, dicArmorItem[inventory[index].info.id].name, dicArmorItem[inventory[index].info.id].level, inventory[index].info.armor);
                }
            }
        }
 
        //data load method
        public void LoadAllData() 
        {
            for(int i = 0; i<this.arrDataName.Length; i++)
            {
                var fileName = this.arrDataName[i];
                string path = string.Format("./Data/{0}", arrDataName[i]);
            }
            string weaponDataPath = "./Data/weapon_data.json";
            bool isExist = true;
            if (isExist)
            {
                var weapon = File.ReadAllText(weaponDataPath);
                var weaponJson = JsonConvert.DeserializeObject<ItemData[]>(weapon);
                foreach (var data in weaponJson)
                {
                    var itemData = new ItemData(data.id, data.type, data.name, data.level, data.damage_min, data.damage_max);
                    dicWeaponItem.Add(itemData.id, itemData);
                }
            }
            string armorDataPath = "./Data/armor_data.json";
            isExist = File.Exists(armorDataPath);
            if (isExist)
            {
                var armor = File.ReadAllText(armorDataPath);
                var armorJson = JsonConvert.DeserializeObject<ItemData[]>(armor);
                foreach(var data in armorJson)
                {
                    var itemData = new ItemData(data.id, data.type, data.name, data.level, data.armor_min, data.armor_max);
                    dicArmorItem.Add(itemData.id, itemData);
                }
            }            
 
        }
 
        public Item CreateItem(int id, int type)
        {
            Random rand = new Random();
            if(type == 0)
            {
                int damageOrArmor = rand.Next(dicWeaponItem[id].damage_min, dicWeaponItem[id].damage_max);
                ItemInfo info = new ItemInfo(id, type, damageOrArmor);
                return new Item(info);
            }
            else if(type == 1)
            {
                int damageOrArmor = rand.Next(dicArmorItem[id].armor_min, dicArmorItem[id].armor_max);
                ItemInfo info = new ItemInfo(id, type, damageOrArmor);
                return new Item(info);
            }
            return default(Item);
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class Item
    {
        public ItemInfo info;
        public Item(ItemInfo info)
        {
            this.info = info;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class ItemData
    {
        public int id;
        public int type;
        public string name;
        public int level;
        public int damage_min;
        public int damage_max;
        public int armor_min;
        public int armor_max;
 
        public ItemData(int id, int type, string name, int level, int min, int max)
        {
            if(type==0)
            {
                this.id = id;
                this.type = type;
                this.name = name;
                this.level = level;
                this.damage_min = min;
                this.damage_max = max;
            }
            else if(type==1)
            {
                this.id = id;
                this.type = type;
                this.name = name;
                this.level = level;
                this.armor_min = min;
                this.armor_max = max;
 
            }
        }
    }
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_0404
{
    public class ItemInfo
    {
        public int id;
        public int type;
        public int damage;
        public int armor;
        public ItemInfo(int id, int type, int damageOrArmor)
        {
            if (type == 0)
            {
                this.id = id;
                this.type = type;
                this.damage = damageOrArmor;
            }
            else if (type == 1)
            {
                this.id = id;
                this.type = type;
                this.armor = damageOrArmor;
            }
 
        }
    }
}
 
cs


:

Dictionary를 이용한 Inventory구현 및 Json사용

C#/수업내용 2019. 4. 3. 23:33


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using Newtonsoft.Json;
 
namespace Dictionary_0403
{
    public class App
    {
        Dictionary<int, ItemData> dicItems = new Dictionary<int, ItemData>();
        public App()
        {
            var readJson = File.ReadAllText(@"weapon_data.json");
            Console.WriteLine(readJson);
            var arrItemData = JsonConvert.DeserializeObject<ItemData[]>(readJson);
            foreach(var item in arrItemData)
            {
                Console.WriteLine(item.name);
            }
        }
 
        public void Start()
        {
            Dictionary<stringstring> dicPeople = new Dictionary<stringstring>();
            dicPeople.Add("940915-1111111""홍길동");
            dicPeople.Add("950915-1111111""임꺽정");
 
            var name = dicPeople["940915-1111111"];
            Console.WriteLine("name = {0}", name);
 
            var hasKey = dicPeople.ContainsKey("940915-1111111");
            if(hasKey)
            {
                name = dicPeople["940915-1111111"];
                dicPeople.Remove("940915-1111111");
                Console.WriteLine("{0}", name);
            }
            else
            {
                Console.WriteLine("해당키의 값은 없습니다.");
            }
 
            foreach(KeyValuePair<stringstring> pair in dicPeople)
            {
                Console.WriteLine("{0} : {1}", pair.Key, pair.Value);
            }
        }
 
        public void Start2()
        {
            var item = new ItemData(0"혈마검"701822.3f, 2231.8f);
            dicItems.Add(item.id, item);
            item = new ItemData(1"카를레이의 주장"701735.5f, 2085.8f);
            dicItems.Add(item.id, item);
            item = new ItemData(2"지존의 손잡이 칼"70321.0f, 321.0f);
            dicItems.Add(item.id, item);
            item = new ItemData(3"은장도"701735.5f, 2085.8f);
            dicItems.Add(item.id, item);
            item = new ItemData(4"손잡이 칼"70321.0f, 325.5f);
            dicItems.Add(item.id, item);
            item = new ItemData(5"그린스톤 경의 부채"701735.5f, 2085.8f);
            dicItems.Add(item.id, item);
            foreach(KeyValuePair<int, ItemData> pair in dicItems)
            {
                Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지: {3}~{4}", pair.Value.id, pair.Value.name, pair.Value.maxLevel, pair.Value.damageMin, pair.Value.damageMax);
            }
 
            var firstItem = this.CreateItem(0);
            var secondItem = this.CreateItem(1);
            var thirdItem = this.CreateItem(2);
            var fourthItem = this.CreateItem(3);
            var fifthtItem = this.CreateItem(4);
            var sixthtItem = this.CreateItem(5);
            Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지:{3}", firstItem.itemInfo.id, dicItems[firstItem.itemInfo.id].name, dicItems[firstItem.itemInfo.id].maxLevel, firstItem.itemInfo.damage);
            Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지:{3}", secondItem.itemInfo.id, dicItems[secondItem.itemInfo.id].name, dicItems[secondItem.itemInfo.id].maxLevel, secondItem.itemInfo.damage);
            Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지:{3}", thirdItem.itemInfo.id, dicItems[thirdItem.itemInfo.id].name, dicItems[thirdItem.itemInfo.id].maxLevel, thirdItem.itemInfo.damage);
            Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지:{3}", fourthItem.itemInfo.id, dicItems[fourthItem.itemInfo.id].name, dicItems[fourthItem.itemInfo.id].maxLevel, fourthItem.itemInfo.damage);
            Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지:{3}", fifthtItem.itemInfo.id, dicItems[fifthtItem.itemInfo.id].name, dicItems[fifthtItem.itemInfo.id].maxLevel, fifthtItem.itemInfo.damage);
            Console.WriteLine("\n\n{0}. {1}\n 레벨:{2}, 데미지:{3}", sixthtItem.itemInfo.id, dicItems[sixthtItem.itemInfo.id].name, dicItems[sixthtItem.itemInfo.id].maxLevel, sixthtItem.itemInfo.damage);
        }
 
        public Item CreateItem(int id)
        {
            double damage = this.GetRandomNumber(dicItems[id].damageMin, dicItems[id].damageMax);
            ItemInfo info = new ItemInfo(id, dicItems[id].maxLevel, (float)damage);
            return new Item(info);
        }
        public double GetRandomNumber(double minimum, double maximum)
        {
            Random rand = new Random();
            return rand.NextDouble() * (maximum - minimum) + minimum;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Dictionary_0403
{
    public class Item
    {
        public ItemInfo itemInfo;
 
        public Item(ItemInfo itemInfo)
        {
            this.itemInfo = itemInfo;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Dictionary_0403
{
    public class ItemData
    {
        public int id;
        public string name;
        public int maxLevel;
        public float damageMin;
        public float damageMax;
 
        public ItemData(int id, string name, int maxLevel, float damageMin, float damageMax)
        {
            this.id = id;
            this.name = name;
            this.maxLevel = maxLevel;
            this.damageMin = damageMin;
            this.damageMax = damageMax;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Dictionary_0403
{
    public class ItemInfo
    {
        public int id;
        public int level;
        public float damage;
 
        public ItemInfo(int id, int level, float damage)
        {
            this.id = id;
            this.level = level;
            this.damage = damage;
        }
    }
}
 
cs



Json형식의 파일을 역직렬화하여 Item객체를 생성하였다.

역직렬화 하는데 Newtonsoft.Json 패키지를 사용하였다.

:

Inventory구현 (창고이동, 제작, 목록 등등)

C#/수업내용 2019. 4. 2. 17:45


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GenericInventory
{
    class App
    {
        public App()
        {
            Console.WriteLine("App 생성자");
        }
        public void StartApp()
        {
            Inventory<HerbItem> herbInventory = new Inventory<HerbItem>();
            Inventory<MagicItem> magicInventory = new Inventory<MagicItem>();
            Inventory<Item> guildWarehouse = new Inventory<Item>();
            ConsoleKey menuKey = ConsoleKey.D1;
            string inputName;
 
            while(menuKey != ConsoleKey.D7)
            {
                Console.WriteLine("1.아이템제작 2.아이템목록 3.아이템검색 4.아이템버리기 5.창고이동 6.아이템변경");
                menuKey = Console.ReadKey().Key;
                switch(menuKey)
                {
                    case ConsoleKey.D1:
                        Console.WriteLine("제작하실 아이템 종류와 품목을 선택하세요");
                        Console.WriteLine("약초 : 평온초 / 은엽수 / 뱀뿌리 / 마법초 / 무덤이끼");
                        Console.WriteLine("마부 : 가속의 서약 / 원소의 격류 / 치명적인 항해");
                        inputName = Console.ReadLine();
                        switch(inputName)
                        {
                            case "평온초":
                                herbInventory.AddItem(new HerbItem(inputName));
                                break;
                            case "은엽수":
                                herbInventory.AddItem(new HerbItem(inputName));
                                break;
                            case "뱀뿌리":
                                herbInventory.AddItem(new HerbItem(inputName));
                                break;
                            case "마법초":
                                herbInventory.AddItem(new HerbItem(inputName));
                                break;
                            case "무덤이끼":
                                herbInventory.AddItem(new HerbItem(inputName));
                                break;
                            case "가속의 서약":
                                magicInventory.AddItem(new MagicItem(inputName));
                                break;
                            case "원소의 격류":
                                magicInventory.AddItem(new MagicItem(inputName));
                                break;
                            case "치명적인 항해":
                                magicInventory.AddItem(new MagicItem(inputName));
                                break;
                            default:
                                Console.WriteLine("제작할 수 없는 아이템입니다.");
                                break;
                        }
                        break;
                    case ConsoleKey.D2:
                        Console.WriteLine("허브가방");
                        herbInventory.PrintItemList();
                        Console.WriteLine("\n마부가방");
                        magicInventory.PrintItemList();
                        break;
                    case ConsoleKey.D3:
                        Console.WriteLine("찾을 아이템 이름을 입력하세요");
                        inputName = Console.ReadLine();
                        var herbTemp = herbInventory.SearchItem(inputName);
                        var magicTemp = magicInventory.SearchItem(inputName);
                        if(herbTemp!=null)
                        {
                            Console.WriteLine("{0}이 가방에 {1}개 있습니다", herbTemp.itemName, herbTemp.itemCount);
                        }
                        else if(magicTemp!=null)
                        {
                            Console.WriteLine("{0}이 가방에 {1}개 있습니다.", magicTemp.itemName, magicTemp.itemCount);
                        }
                        else
                        {
                            Console.WriteLine("가방에 존재하지 않는 아이템입니다.");
                        }
                        break;
                    case ConsoleKey.D4:
                        Console.WriteLine("버릴 아이템 이름을 입력하세요");
                        inputName = Console.ReadLine();
                        var herbSuccess = herbInventory.RemoveItem(inputName);
                        var magicSuccess = magicInventory.RemoveItem(inputName);
                        if(herbSuccess == true || magicSuccess)
                        {
                            Console.WriteLine("{0}를 버렸습니다.", inputName);
                        }
                        else if(herbSuccess == false && magicSuccess == false)
                        {
                            Console.WriteLine("{0}이 가방에 없습니다.", inputName);
                        }
                        break;
                    case ConsoleKey.D5:
                        Console.Write("1.창고에서 가져오기 2.창고에 넣기");
                        var key = Console.ReadKey().Key;
                        bool moveSuccess;
                        switch(key)
                        {
                            case ConsoleKey.D1:
                                moveSuccess = guildWarehouse.MoveWareToInven(ref guildWarehouse.items, ref herbInventory.items, ref magicInventory.items);
                                break;
                            case ConsoleKey.D2:
                                moveSuccess = guildWarehouse.MoveInvenToWare(ref guildWarehouse.items, ref herbInventory.items, ref magicInventory.items);
                                break;
                            default:
                                Console.WriteLine("잘못입력하셨습니다");
                                break;
                        } 
                        break;
                    case ConsoleKey.D6:
                        Console.WriteLine("변경할 아이템의 이름을 입력하세요");
                        string toChangeItem = Console.ReadLine();
                        Console.WriteLine("무슨 아이템으로 변경할까요?");
                        string changeItem = Console.ReadLine();
                        if(herbInventory.UpdateItem(ref herbInventory.items, new HerbItem(changeItem), toChangeItem) == false &&
                        magicInventory.UpdateItem(ref magicInventory.items, new MagicItem(changeItem), toChangeItem) == false)
                        {
                            Console.WriteLine("변경하실 수 있는 아이템이 없습니다.");
                        }
                        else
                        {
                            Console.WriteLine("변경이 완료되었습니다!");
                        }
                        break;
                }
            }
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GenericInventory
{
    public class HerbItem : Item
    {
        public HerbItem(string name)
        {
            this.itemType = 2;
            this.itemCount = 1;
            this.itemName = name;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GenericInventory
{
    public class Item
    {
        public int itemType;
        public string itemName;
        public int itemCount;
 
        public Item()
        {
        }
    }
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GenericInventory
{
    public class MagicItem : Item
    {
        public MagicItem(string name)
        {
            this.itemType = 1;
            this.itemCount = 1;
            this.itemName = name;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GenericInventory
{
    public class Inventory<T> where T : Item
    {
        public List<T> items = new List<T>();
 
        public Inventory()
        {
            Console.WriteLine("인벤토리가 생성되었습니다.");
        }
 
        public void AddItem(T item)
        {
            int addCount = 0;
            foreach (var search in items)
            {
                if (item.itemName == search.itemName)
                {
                    search.itemCount++;
                    addCount = 1;
                    Console.WriteLine("{0}가 가방에 추가되었습니다.", item.itemName);
                    break;
                }
            }
            if (addCount != 1)
            {
                items.Add(item);
                Console.WriteLine("{0}가 가방에 추가되었습니다.", item.itemName);
            }
        }
 
        public bool RemoveItem(string name)
        {
            int removeCount = 0;
            foreach (var search in items)
            {
                if (name == search.itemName)
                {
                    if (search.itemCount != 1)
                    {
                        search.itemCount--;
                        return true;
                    }
                    else if (search.itemCount == 1)
                    {
                        items.RemoveAt(removeCount);
                        return true;
                    }
                }
                removeCount++;
            }
            return false;
        }
 
        public void PrintItemList()
        {
            foreach (var count in items)
            {
                Console.WriteLine("{0}, {1}개", count.itemName, count.itemCount);
            }
        }
 
        public T SearchItem(string name)
        {
            foreach (var search in items)
            {
                if (search.itemName == name)
                {
                    return search;
                }
            }
            return default(T);
        }
 
        public bool UpdateItem(ref List<T> item, T items, string toChangeItem)
        {
            int countUpdate = 0;
            for (int index = 0; index < item.Count; index++)
            {
                if (toChangeItem == item[index].itemName)
                {
                    for (int indexTemp = 0; indexTemp < item.Count; indexTemp++)
                    {
                        if (item[indexTemp].itemName == items.itemName)
                        {
                            item[indexTemp].itemCount++;
                            item.RemoveAt(index);
                            countUpdate = 1;
                            return true;
                        }
                    }
                    if (countUpdate != 1)
                    {
                        item[index] = items;
                        countUpdate = 1;
                        return true;
                    }
                }
            }
            return false;
        }
 
        public bool MoveWareToInven(ref List<Item> warehouse, ref List<HerbItem> herbInventory, ref List<MagicItem> magicInventory)
        {
            int takeItemCount = 0;
            int index = 0;
            Console.WriteLine("무엇을 가져오시겠습니까?");
            Console.WriteLine("창고의 아이템 목록");
            foreach(var item in warehouse)
            {
                Console.Write("{0} {1}개\t", item.itemName, item.itemCount);
            }
            string takeItemName = Console.ReadLine();
            foreach(var item in warehouse)
            {
                if(item.itemName == takeItemName)
                {
                    takeItemCount = 1;
                    break;
                }
                index++;
            }
 
            if(takeItemCount != 1 && takeItemName != "평온초" && takeItemName != "은엽수" && takeItemName != "뱀뿌리" && takeItemName != "마법초" &&
                takeItemName != "무덤이끼" && takeItemName != "가속의 서약" && takeItemName != "원소의 격류" && takeItemName != "치명적인 항해")
            {
                Console.WriteLine("창고에 존재하지 않는 아이템입니다.");
                return false;
            }
            else
            {
                if(takeItemName == "평온초" || takeItemName == "은엽수" || takeItemName == "뱀뿌리" || takeItemName == "마법초" || takeItemName == "무덤이끼")
                {
                    foreach(var search in herbInventory)
                    {
                        if(search.itemName == takeItemName)
                        {
                            search.itemCount++;
                            warehouse.RemoveAt(index);
                            return true;
                        }
                    }
                    herbInventory.Add(new HerbItem(takeItemName));
                    warehouse.RemoveAt(index);
                    return true;
                }
                else if(takeItemName == "가속의 서약" || takeItemName == "원소의 격류" || takeItemName == "치명적인 항해")
                {
                    foreach(var search in magicInventory)
                    {
                        if(search.itemName == takeItemName)
                        {
                            search.itemCount++;
                            warehouse.RemoveAt(index);
                            return true;
                        }
                    }
                    magicInventory.Add(new MagicItem(takeItemName));
                    warehouse.RemoveAt(index);
                    return true;
                }
            }
            return false;
        }
 
        public bool MoveInvenToWare(ref List<Item> warehouse, ref List<HerbItem> herbInventory, ref List<MagicItem> magicInventory)
        {
            int takeItemCount = 0;
            int index = 0;
            Console.WriteLine("무엇을 넣으시겠습니까?");
            Console.WriteLine("자신의 아이템 목록");
            foreach (var item in herbInventory)
            {
                Console.Write("{0} {1}개\t", item.itemName, item.itemCount);
            }
            foreach (var item in magicInventory)
            {
                Console.Write("{0} {1}개\t", item.itemName, item.itemCount);
            }
            string takeItemName = Console.ReadLine();
            foreach (var item in herbInventory)
            {
                if (item.itemName == takeItemName)
                {
                    takeItemCount = 1;
                    break;
                }
                index++;
            }
            if(takeItemCount != 1)
            {
                index = 0;
                foreach(var item in magicInventory)
                {
                    if(item.itemName == takeItemName)
                    {
                        takeItemCount = 1;
                        break;
                    }
                    index++;
                }
            }
 
            if (takeItemCount != 1 && takeItemName != "평온초" && takeItemName != "은엽수" && takeItemName != "뱀뿌리" && takeItemName != "마법초" &&
                takeItemName != "무덤이끼" && takeItemName != "가속의 서약" && takeItemName != "원소의 격류" && takeItemName != "치명적인 항해")
            {
                Console.WriteLine("인벤토리에 존재하지 않는 아이템입니다.");
                return false;
            }
            else
            {
                if (takeItemName == "평온초" || takeItemName == "은엽수" || takeItemName == "뱀뿌리" || takeItemName == "마법초" || takeItemName == "무덤이끼")
                {
                    foreach (var search in warehouse)
                    {
                        if (search.itemName == takeItemName)
                        {
                            search.itemCount++;
                            herbInventory.RemoveAt(index);
                            return true;
                        }
                    }
                    warehouse.Add(new HerbItem(takeItemName));
                    herbInventory.RemoveAt(index);
                    return true;
                }
                else if (takeItemName == "가속의 서약" || takeItemName == "원소의 격류" || takeItemName == "치명적인 항해")
                {
                    foreach (var search in warehouse)
                    {
                        if (search.itemName == takeItemName)
                        {
                            search.itemCount++;
                            magicInventory.RemoveAt(index);
                            return true;
                        }
                    }
                    warehouse.Add(new MagicItem(takeItemName));
                    magicInventory.RemoveAt(index);
                    return true;
                }
            }
            return false;
        }
    }
}
 
cs


:

Inventory를 다시 Array로 되돌리기

C#/수업내용 2019. 4. 1. 16:08


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    class Inventory
    {
        //Item형식의 값을 저장할 공간 
        private Item[] items = new Item[10];
        public int inventoryCount = 10;
 
        //기본 생성자 
        public Inventory()
        {
            Console.WriteLine("Inventory클래스의 생성자");
            Console.WriteLine("items.Length: {0}", items.Length);
        }
 
        //넣고 (매개변수로 Item인스턴스를 받아 배열에 넣는다)
        public void AddItem(Item item)
        {
            //배열의 방에 현재 위치에 있는지 확인후 없으면 다음방에 넣는다.
            //Item, Item, null, null,null, null,null, null,null, null
            //Item, Item, Item, Item,Item, Item,Item, Item,Item, Item
            //더이상 넣을수 없습니다.
            for(int index=0; index<items.Length; index++)
            {
                if (this.GetItemCount() == inventoryCount)
                {
                    Console.WriteLine("인벤토리가 꽉찼습니다.");
                    break;
                }
                else if(items[index] == null)
                {
                    items[index] = item;
                    Console.WriteLine("{0}의 제작이 완료되었습니다.", item.name);
                    break;
                }
            }
 
 
        }
 
        //뺀다 
        public void GetItemByName(string searchName)
        {
            //배열안에 있는 요소들중에 serachName 문자열과 비교해서 같은거 찾음
            //찾은거 반환, 못찾으면? null반환 
            //같은게 있다면? 하나만 가져오자 
            //돌도끼, 돌도끼, null, null,null, null,null, null,null, null
            //null, 돌도끼, null, null,null, null,null, null,null, null
            //반환값 : 돌도끼
            //null, 돌도끼, null, null,null, null,null, null,null, null
            //null, 돌도끼, null, 장검,null, null,null, null,null, null
            //돌도끼, 장검, null, null, null, ,null, null,null, null,null, null
            //손도끼, 돌도끼, null, null,null, null,null, null,null, null
            int index = 0;
            var readKey = ConsoleKey.D0;
            foreach (Item checkInventory in items)
            {
                if (checkInventory.name == searchName)
                {
                    Console.WriteLine("{0}가 인벤토리에 있습니다. 버리시겠습니까?(1.버린다 2.넣어둔다)", searchName);
                    readKey = Console.ReadKey().Key;
                    break;
                }
                index++;
            }
            if (readKey == ConsoleKey.D1)
            {
                items[index] = null;
                for(index=0; index<items.Length-1; index++)
                {
                    if (items[index] == null)
                    {
                        var temp = items[index + 1];
                        items[index + 1= items[index];
                        items[index] = temp;
                    }
                }
                Console.WriteLine("인벤토리를 정렬하였습니다.");
                Console.WriteLine("{0}을 버렸습니다.", searchName);
            }
        }
 
        public void ResizeArr(string inputSize)
        {
            int parseSize;
            Int32.TryParse(inputSize.ToString(), out parseSize);
            if(parseSize>10)
            {
                Console.WriteLine("값을 잘못 입력하셨습니다.");
            }
            else
            {
                Array.Resize(ref items, items.Length+parseSize);
                Console.Write("가방이 {0}칸 늘어났습니다.", parseSize);
                inventoryCount += parseSize;
            }
        }
 
        //목록출력
        public void GetItemList()
        {
            foreach (Item itemList in items)
            {
                if (itemList == null)
                {
                    break;
                }
                Console.Write("{0}  ", itemList.name);
            }
        }
 
        //인벤토리에 있는 아이템 갯수 가져오기 
        public int GetItemCount()
        {
            //배열안에 있는 값이 null이 아닐경우 카운트 해서 반환함 
            int cnt = 0;
            foreach (var item in items)
            {
                if (item != null)
                {
                    cnt++;
                }
            }
            return cnt;
        }
    }
}
cs




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    class App
    {
        public App()
        {
            this.Start();
        }
        public void Start()
        {
            Inventory inventory = new Inventory() { };
 
            var inputKey = ConsoleKey.D0;
            while (inputKey != ConsoleKey.D5)
            {
                Console.WriteLine("\n1.아이템제작 2.인벤토리 3.아이템검색 4.가방늘리기 5.종료하기");
                inputKey = Console.ReadKey().Key;
                string inputItemName;
                switch(inputKey)
                {
                    case ConsoleKey.D1:
                        Console.Write("제작하실 아이템을 입력하세요 : ");
                        inputItemName = Console.ReadLine();
                        inventory.AddItem(new Item(inputItemName));
                        break;
                    case ConsoleKey.D2:
                        inventory.GetItemList();
                        break;
                    case ConsoleKey.D3:
                        Console.Write("검색하실 아이템 이름을 입력하세요 : ");
                        inputItemName = Console.ReadLine();
                        inventory.GetItemByName(inputItemName);
                        break;
                    case ConsoleKey.D4:
                        Console.Write("얼마나 늘리시겠습니까? (1회 최대 10칸) : ");
                        var inputSize = Console.ReadLine();
                        inventory.ResizeArr(inputSize);
                        break;
                    case ConsoleKey.D5:
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    public class Item
    {
        public string name;
 
        public Item(string name)
        {
            this.name = name;
        }
    }
}
cs


:

제너릭 클래스, 상속을 이용하여 Inventory 만들기

C#/수업내용 2019. 4. 1. 15:37


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    public class HerbItem : Item
    {
        public HerbItem(string name)
        {
            this.name = name;
        }
    }
}
 

cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    public class MagicalItem : Item
    {
        public MagicalItem(string name)
        {
            this.name = name;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    public class Item
    {
        public string name;
 
        public Item()
        {
        }
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    class Inventory<T>
    {
        //Item형식의 값을 저장할 공간 
        private List<Item> items = new List<Item>();
        public int inventoryCount = 10;
 
        //기본 생성자 
        public Inventory()
        {
            Console.WriteLine("Inventory클래스의 생성자");
            Console.WriteLine("items.Length: {0}", items.Count);
        }
 
        //넣고 (매개변수로 Item인스턴스를 받아 배열에 넣는다)
        public void AddItem(Item item)
        {
            //배열의 방에 현재 위치에 있는지 확인후 없으면 다음방에 넣는다.
            //Item, Item, null, null,null, null,null, null,null, null
            //Item, Item, Item, Item,Item, Item,Item, Item,Item, Item
            //더이상 넣을수 없습니다.
            if (this.GetItemCount() == inventoryCount)
            {
                Console.WriteLine("인벤토리가 꽉찼습니다.");
            }
            else
            {
                items.Add(item);
                Console.WriteLine("{0}의 제작이 완료되었습니다.", item.name);
            }
 
 
        }
 
        //뺀다 
        public void GetItemByName(string searchName)
        {
            //배열안에 있는 요소들중에 serachName 문자열과 비교해서 같은거 찾음
            //찾은거 반환, 못찾으면? null반환 
            //같은게 있다면? 하나만 가져오자 
            //돌도끼, 돌도끼, null, null,null, null,null, null,null, null
            //null, 돌도끼, null, null,null, null,null, null,null, null
            //반환값 : 돌도끼
            //null, 돌도끼, null, null,null, null,null, null,null, null
            //null, 돌도끼, null, 장검,null, null,null, null,null, null
            //돌도끼, 장검, null, null, null, ,null, null,null, null,null, null
            //손도끼, 돌도끼, null, null,null, null,null, null,null, null
            int index = 0;
            var readKey = ConsoleKey.D0;
            foreach (Item checkInventory in items)
            {
                if (checkInventory.name == searchName)
                {
                    Console.WriteLine("{0}가 인벤토리에 있습니다. 버리시겠습니까?(1.버린다 2.넣어둔다)", searchName);
                    readKey = Console.ReadKey().Key;
                    break;
                }
                index++;
            }
            if (readKey == ConsoleKey.D1)
            {
                items.RemoveAt(index);
                Console.WriteLine("{0}을 버렸습니다.", searchName);
            }
        }
 
        //목록출력
        public void GetItemList()
        {
            foreach (Item itemList in items)
            {
                if (itemList == null)
                {
                    break;
                }
                Console.Write("{0}  ", itemList.name);
            }
        }
 
        //인벤토리에 있는 아이템 갯수 가져오기 
        public int GetItemCount()
        {
            //배열안에 있는 값이 null이 아닐경우 카운트 해서 반환함 
            int cnt = 0;
            foreach (var item in items)
            {
                if (item != null)
                {
                    cnt++;
                }
            }
            return cnt;
        }
    }
}
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ArrayInventory
{
    class App
    {
        public App()
        {
            this.Start();
        }
        public void Start()
        {
            Inventory<HerbItem> herbInventory = new Inventory<HerbItem>(); //허브인벤토리
            Inventory<MagicalItem> magicInventory = new Inventory<MagicalItem>(); //마부인벤토리
 
            var inputKey = ConsoleKey.D0;
            while (inputKey != ConsoleKey.D4)
            {
                Console.WriteLine("\n1.아이템제작 2.인벤토리 3.아이템검색 4.종료하기");
                inputKey = Console.ReadKey().Key;
                string inputItemName;
                switch(inputKey)
                {
                    case ConsoleKey.D1:
                        Console.WriteLine("제작하실 아이템 종류와 품목을 선택하세요");
                        Console.WriteLine("약초 : 평온초 / 은엽수 / 뱀뿌리 / 마법초 / 무덤이끼");
                        Console.WriteLine("마부 : 가속의 서약 / 원소의 격류 / 치명적인 항해");
                        inputItemName = Console.ReadLine();
                        switch(inputItemName)
                        {
                            case "평온초":
                                herbInventory.AddItem(new HerbItem(inputItemName));
                                break;
                            case "은엽수":
                                herbInventory.AddItem(new HerbItem(inputItemName));
                                break;
                            case "뱀뿌리":
                                herbInventory.AddItem(new HerbItem(inputItemName));
                                break;
                            case "마법초":
                                herbInventory.AddItem(new HerbItem(inputItemName));
                                break;
                            case "무덤이끼":
                                herbInventory.AddItem(new HerbItem(inputItemName));
                                break;
                            case "가속의 서약":
                                magicInventory.AddItem(new MagicalItem(inputItemName));
                                break;
                            case "원소의 격류":
                                magicInventory.AddItem(new MagicalItem(inputItemName));
                                break;
                            case "치명적인 항해":
                                magicInventory.AddItem(new MagicalItem(inputItemName));
                                break;
                            default:
                                Console.WriteLine("제작할 수 없는 아이템입니다.");
                                break;
                        }
                        break;
                    case ConsoleKey.D2:
                        Console.Write("약초 가방 : ");
                        herbInventory.GetItemList();
                        Console.Write("\n마부 가방 : ");
                        magicInventory.GetItemList();
                        break;
                    case ConsoleKey.D3:
                        Console.Write("검색하실 아이템 이름을 입력하세요 : ");
                        inputItemName = Console.ReadLine();
                        herbInventory.GetItemByName(inputItemName);
                        magicInventory.GetItemByName(inputItemName);
                        break;
                    case ConsoleKey.D4:
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
 
cs


: