package models import ( "bytes" "fmt" "github.com/golang/protobuf/proto" "pro2d/common/logger" "pro2d/pb" "strconv" "strings" ) //背包系统 func (m *RoleModel) GetItemCount(key string) uint32 { c, ok := m.Items[key] if !ok { c = 0 } return c } func (m *RoleModel) CostItem(key string, count int32) bool { if uint32(count) > m.GetItemCount(key) { return false } return m.AddItem(key, -count) } func (m *RoleModel) CostItems(params BackPackItems) bool { for k, v := range params { if v > m.GetItemCount(k) { return false } m.AddItem(k, -int32(v)) } return true } func (m *RoleModel) AddItem(key string, count int32) bool { c := m.GetItemCount(key) num := int32(c) + count if num > 0 { m.Items[key] = uint32(num) } else { delete(m.Items, key) } m.SetProperty("items", m.ItemsToString(m.Items)) rsp, err := proto.Marshal(&pb.RoleUpdateItemsRsp{Items: fmt.Sprintf("%s=%d", key, num)}) if err != nil { logger.Error(err.Error()) return true } m.GetConn().Send(0, uint32(pb.ProtoCode_RoleUpdateItemsRsp), rsp) return true } func (m *RoleModel) AddItems(params BackPackItems) bool { tmp := make(BackPackItems) for k, v := range params { c := m.GetItemCount(k) num := c + v if num > 0 { m.Items[k] = num tmp[k] = num } else { delete(m.Items, k) } } m.SetProperty("items", m.ItemsToString(m.Items)) rsp, err := proto.Marshal(&pb.RoleUpdateItemsRsp{Items: m.ItemsToString(tmp)}) if err != nil { logger.Error(err.Error()) return true } if m.GetConn() != nil { m.GetConn().Send(0, uint32(pb.ProtoCode_RoleUpdateItemsRsp), rsp) } return true } func (m *RoleModel) ItemsToString(params BackPackItems) string { var items bytes.Buffer for k, v := range params { items.WriteString(k) items.WriteString("=") items.WriteString(fmt.Sprintf("%d", v)) items.WriteString(" ") } return items.String() } func (m *RoleModel) StringToItems(items string) BackPackItems { backPack := make(BackPackItems) for _, v := range strings.Split(items, " ") { ii := strings.Split(v, "=") if len(ii) < 2 { continue } n, err := strconv.ParseUint(ii[1], 10, 32) if err != nil { continue } backPack[ii[0]] = uint32(n) } return backPack }