자료구조
ArrayList로 인벤토리 만들기
hyunjin-dev-log
2021. 12. 25. 22:03
앱
using System;
using System.Collections;
namespace HelloWorld
{
class App
{
public App()
{
Inventory inventory = new Inventory();
Item item = new Item("도끼");
inventory.AddItem(item);
Console.WriteLine();
inventory.PrintInventory();
Console.WriteLine();
Item foundItem = inventory.GetItem("도끼");
Console.WriteLine();
inventory.EquipItem(foundItem);
Console.WriteLine();
inventory.PrintInventory();
Console.WriteLine();
foundItem = inventory.GetItem("활");
inventory.EquipItem(foundItem);
Console.WriteLine();
Item item1 = new Item("활");
Console.WriteLine();
inventory.AddItem(item1);
inventory.PrintInventory();
Console.WriteLine();
Item item2 = new Item("창");
inventory.AddItem(item2);
inventory.PrintInventory();
Console.WriteLine();
Item item3 = new Item("장검");
inventory.AddItem(item3);
inventory.PrintInventory();
Console.WriteLine();
inventory.GetItem("활");
inventory.GetItem("창");
inventory.GetItem("장검");
}
}
}
아이템
using System;
namespace HelloWorld
{
class Item
{
//멤버 변수
public string name;
//생성자
public Item(string name)
{
this.name = name;
Console.WriteLine("{0}이 생성되었습니다.", this.name);
}
}
}
인벤토리
using System;
using System.Collections;
namespace HelloWorld
{
class Inventory
{
//멤버 변수
public ArrayList list;
//생성자
public Inventory()
{
this.list = new ArrayList();
}
//멤버 메서드
//아이템을 인벤토리에 추가한다
public void AddItem(Item item)
{
this.list.Add(item); //인벤토리 리스트에 받은 매개변수 item을 추가
}
//아이템을 꺼낸다 : 이름으로 찾아서.
public Item GetItem(string name)
{
Console.WriteLine("{0}을 찾아봅니다.", name);
Item foundItem = null;
Item item;
for (int i = 0; i < this.list.Count; i++)
{
item = (Item)this.list[i];
if (item.name == name)
{
foundItem = item;
}
}
if (foundItem != null)
{
Console.WriteLine("{0}을(를) 꺼냈습니다", foundItem.name);
}
else
{
Console.WriteLine("{0}을 찾지못했습니다.", name);
}
Console.WriteLine();
this.list.Remove(foundItem);
Console.WriteLine("인벤토리 내 아이템 개수 : {0}", this.list.Count);
return foundItem;
}
public void PrintInventory() //현재 인벤토리 출력
{
Console.WriteLine("보유 아이템 개수: {0}", this.list.Count);
Console.Write("보유 아이템: ");
for (int i = 0; i < this.list.Count; i++)
{
Item item = (Item)this.list[i];
Console.Write("{0} ", item.name);
}
Console.WriteLine();
}
public void EquipItem(Item foundItem)
{
if (foundItem != null)
{
Console.WriteLine("{0}을(를) 착용했습니다.", foundItem.name);
}
}
}
}
