Prompt Title: Inventory

Created 1 year ago
Votes 0
Views 89 times
0

Prompt Detail:

Đây là đoạn mã Unity C# để tạo một cái Inventory có 2 túi, mỗi túi có 77 slot, và slot chưa vật phẩm có 3 loại là thuôc, trang bị và đá:

csharp
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Inventory : MonoBehaviour { public int numBags = 2; public int numSlots = 77; public List<Item>[] bags; public enum ItemType { Potion, Equipment, Gem } void Start() { bags = new List<Item>[numBags]; for (int i = 0; i < numBags; i++) { bags[i] = new List<Item>(); for (int j = 0; j < numSlots; j++) { bags[i].Add(null); } } } public bool AddItem(Item item) { for (int i = 0; i < numBags; i++) { for (int j = 0; j < numSlots; j++) { if (bags[i][j] == null) { bags[i][j] = item; return true; } } } return false; } public bool RemoveItem(Item item) { for (int i = 0; i < numBags; i++) { for (int j = 0; j < numSlots; j++) { if (bags[i][j] == item) { bags[i][j] = null; return true; } } } return false; } public bool CheckItemType(ItemType type, Item item) { switch (type) { case ItemType.Potion: return item is Potion; case ItemType.Equipment: return item is Equipment; case ItemType.Gem: return item is Gem; default: return false; } } public int CountItemType(ItemType type) { int count = 0; for (int i = 0; i < numBags; i++) { for (int j = 0; j < numSlots; j++) { if (bags[i][j] != null && CheckItemType(type, bags[i][j])) { count++; } } } return count; } } public class Item { public string name; public int value; } public class Potion : Item { public int healAmount; } public class Equipment : Item { public int attackBonus; public int defenseBonus; } public class Gem : Item { public int gemLevel; }

Trong đó, Inventory là class để quản lý inventory, Item là class để đại diện cho các vật phẩm, và Potion, Equipment, và Gem là các class con của Item để biểu diễn cho các loại vật phẩm thuôc, trang bị, và đá.

Trong class Inventory, có các hàm sau:

  • Start(): khởi tạo các túi và các slot trong chúng.
  • AddItem(Item item): thêm một vật phẩm vào inventory. Nếu inventory không đầy, vật phẩm sẽ được thêm vào và trả về true, nếu không trả về false.
  • RemoveItem(Item item): x
avatar
Tuan
Shared 2 prompts
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
Unity Political Party
1 year ago 2023-04-06 13:33:42 Firkus