在cocos2dxna中保存XML

  这些日子一直在学习cocos2d-xna,因为教程比较少,走了不少的弯路。现在想分享一下我学习的经验,特此开了博客园。从以前的看客变成了博客,希望以后大家多多关注我的博客,也希望我的博客可以给大家带来帮助。

  我在写一个游戏时遇到了一个问题,就是我希望用xml来保存我的游戏得分,以此来创建一个得分榜。

就像这样的比分榜

我起初采用了system.xml来解析xml,后来发现在wp中这样的方法是不可用的,只能采用linq to xml,在采用这种方法之后,我发现还必须用独立储存的方法来储存文件。但是最后依然不能成功,XNA中要求了xml文件的格式,有一套自身的使用方法。

由于xna的资料略少,我只好放弃了用.net本身的方法来解析xml。我搜了一个cocos2d-x中的方法,看看有没有封装好的的工具。后来我发现了CCUserDefault,它提供了对xml的读写方法

public class CCUserDefault
{
    public void flush();
    public bool getBoolForKey(string pKey, bool defaultValue);
    public double getDoubleForKey(string pKey, double defaultValue);
    public float getFloatForKey(string pKey, float defaultValue);
    public int getIntegerForKey(string pKey, int defaultValue);
    public string getStringForKey(string pKey, string defaultValue);
    public void purgeSharedUserDefault();
    public void setBoolForKey(string pKey, bool value);
    public void setDoubleForKey(string pKey, double value);
    public void setFloatForKey(string pKey, float value);
    public void setIntegerForKey(string pKey, int value);
    public void setStringForKey(string pKey, string value);
    public static CCUserDefault sharedUserDefault();
}

大家很容易从函数名中看出他们的功能,需要解释的是pKey为标签名,defaultValue为如果xml中取不到值,函数的默认返回值。flush()为将xml保存到独立储存中,如果不调用flush(),重启游戏后会取不到你之前保存的值。

下面用我游戏中的代码作为实例,让大家了解一下CCUserDefault的使用方法。

namespace ChalkBall.GameLogic
{
    class Record
    {
        public static int[] rank = new int[6]{0,0,0,0,0,0};
        CCUserDefault ccd = CCUserDefault.sharedUserDefault();

        public int[] ReadXML()
        {
            string key = "no.";
            string pkey = "";
            
            for (int i = 0; i < 5; i++)
            {
                pkey = key + (i + 1).ToString();
                rank[i] = ccd.getIntegerForKey(pkey,0);
            }
            return rank;
        }

        public void WriteXML(int newScore)
        {
            string key = "no.";
            string pkey = "";
            rank = ReadXML();
            rank[5] = newScore;
            Array.Sort(rank);
            Array.Reverse(rank);
            CCUserDefault ccd = CCUserDefault.sharedUserDefault();
            for (int i = 0; i < 6; i++)
            {
                pkey = key + (i + 1).ToString();
                ccd.setIntegerForKey(pkey, rank[i]);
            }
            ccd.flush();
        }
    }
}

我这里需要储存的值是int型的,所以只以getIntegerForKey和setIntegerForKey为例,大家看,使用CCUserDefault保存xml文件是不是很简单?

本文地址:http://www.cnblogs.com/jacklandrin/archive/2012/09/15/2687015.html

这是我第一次在园子里发博客,希望大家拍砖~

原文地址:https://www.cnblogs.com/jacklandrin/p/2687015.html