C# 将用户数据输出到XNA文件 命名空间高分 { 公共类游戏1:Microsoft.Xna.Framework.Game { //高分数据资料 公共结构HighScoreData { 公共字符串[]PlayerName; 公共int[]分数; 公共整数计数;
将用户数据输出到XNA文件C# 将用户数据输出到XNA文件 命名空间高分 { 公共类游戏1:Microsoft.Xna.Framework.Game { //高分数据资料 公共结构HighScoreData { 公共字符串[]PlayerName; 公共int[]分数; 公共整数计数; ,c#,file-io,xna,C#,File Io,Xna,将用户数据输出到XNA文件 命名空间高分 { 公共类游戏1:Microsoft.Xna.Framework.Game { //高分数据资料 公共结构HighScoreData { 公共字符串[]PlayerName; 公共int[]分数; 公共整数计数; 公共高分数据(整数计数) { PlayerName=新字符串[计数]; 分数=新整数[计数]; 计数=计数; } } /*更多分数变量*/ 高分数据; 公共字符串HighScoresFilename=“highscores.dat”; int
命名空间高分
{
公共类游戏1:Microsoft.Xna.Framework.Game
{
//高分数据资料
公共结构HighScoreData
{
公共字符串[]PlayerName;
公共int[]分数;
公共整数计数;
公共高分数据(整数计数)
{
PlayerName=新字符串[计数];
分数=新整数[计数];
计数=计数;
}
}
/*更多分数变量*/
高分数据;
公共字符串HighScoresFilename=“highscores.dat”;
int PlayerScore=0;
弦乐演奏者姓名;
弦乐记分板;
字符串typedText=“”;
智力得分=0;
公共静态字体;
公共静态纹理2D textBoxTexture;
公共静态纹理2D caretTexture;
bool-txt;
//获取名称的字符串
string cmdString=“输入您的玩家姓名并按Enter键”;
//我们将要显示的字符串–最初是一个空字符串
字符串messageString=“”;
雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧雪碧;
图形管理器图形;
键盘状态oldKeyboardState;
键盘状态currentKeyboardState;
私有字符串textString;
公共游戏1()
{
graphics=新的GraphicsDeviceManager(此);
Content.RootDirectory=“Content”;
#如果是XBOX
添加(新GamerServicesComponent(this));
#恩迪夫
currentKeyboardState=Keyboard.GetState();
}
///
///允许游戏在开始运行之前执行任何需要的初始化。
///在这里,它可以查询任何必需的服务,并加载任何非图形化的服务
///相关内容。调用base.Initialize将枚举所有组件
///并对它们进行初始化。
///
受保护的覆盖无效初始化()
{
txt=真;
//当玩家在键盘上键入内容时,向typedText字符串追加字符。
KeyGrabber.InboundCharEvent+=(inboundCharacter)=>
{
//仅附加spritefont中存在的字符。
如果(边界字符<32)
返回;
如果(inboundCharacter>126)
返回;
typedText+=边界内字符;
};
//获取保存游戏的路径
字符串fullpath=“highscores.dat”;
//检查保存是否存在
#如果窗口
如果(!File.Exists(完整路径))
{
//如果文件不存在,请制作一个假文件。。。
//创建要保存的数据
数据=新的高分数据(5);
data.PlayerName[0]=“neil”;
数据.得分[0]=2000;
data.PlayerName[1]=“barry”;
数据.得分[1]=1800;
data.PlayerName[2]=“标记”;
数据.得分[2]=1500;
data.PlayerName[3]=“cindy”;
数据.得分[3]=1000;
data.PlayerName[4]=“sam”;
数据.得分[4]=500;
保存高分(数据、高分文件名);
}
#elif XBOX
使用(IsolatedStorageFile iso=IsolatedStorageFile.GetUserStoreForApplication())
{
如果(!iso.FileExists(fullpath))
{
//如果文件不存在,请制作一个假文件。。。
//创建要保存的数据
数据=新的高分数据(5);
data.PlayerName[0]=“neil”;
数据.得分[0]=2000;
data.PlayerName[1]=“shawn”;
数据.得分[1]=1800;
data.PlayerName[2]=“标记”;
数据.得分[2]=1500;
data.PlayerName[3]=“cindy”;
数据.得分[3]=1000;
data.PlayerName[4]=“sam”;
数据.得分[4]=500;
保存高分(数据、高分文件名、设备);
}
}
#恩迪夫
base.Initialize();
}
#区域节约
/*保存高分*/
公共静态void SaveHighScores(HighScoresData数据,字符串文件名)
{
//获取保存游戏的路径
字符串fullpath=“highscores.dat”;
#如果窗口
//打开文件,必要时创建它
FileStream stream=File.Open(完整路径,FileMode.Create);
尝试
{
//将对象转换为XML数据并将其放入流中
XmlSerializer serializer=新的XmlSerializer(typeof(HighScoreData));
序列化器。序列化(流、数据);
}
最后
{
//关闭文件
stream.Close();
}
#elif XBOX
使用(IsolatedStorageFile iso=IsolatedStorageFile.GetUserStoreForApplication())
{
使用(IsolatedStorageFileStream=新的IsolatedStorageFileStream(完整路径,FileMode.Create,iso))
{
XmlSerializer serializer=新的XmlSerializer(typeof(HighScoreData));
序列化器。序列化(流、数据);
}
}
#恩迪夫
}
/*加载高分*/
公共静态HighScore数据加载HighScores(字符串文件名)
{
高分数据;
//获取保存游戏的路径
字符串fullpath=“highscores.dat”;
#如果窗口
//打开文件
FileStream stream=File.Open(完整路径,FileMode.OpenOrCreate,FileAccess.Read);
尝试
{
//从文件中读取数据
XmlSerializer serializer=新的XmlSerializez
namespace highscores
{
public class Game1 : Microsoft.Xna.Framework.Game
{
//Stuff for HighScoreData
public struct HighScoreData
{
public string[] PlayerName;
public int[] Score;
public int Count;
public HighScoreData(int count)
{
PlayerName = new string[count];
Score = new int[count];
Count = count;
}
}
/* More score variables */
HighScoreData data;
public string HighScoresFilename = "highscores.dat";
int PlayerScore = 0;
string PlayerName;
string scoreboard;
string typedText = "";
int score = 0;
public static SpriteFont font;
public static Texture2D textBoxTexture;
public static Texture2D caretTexture;
bool txt;
// String for get name
string cmdString = "Enter your player name and press Enter";
// String we are going to display – initially an empty string
string messageString = "";
SpriteBatch spriteBatch;
GraphicsDeviceManager graphics;
KeyboardState oldKeyboardState;
KeyboardState currentKeyboardState;
private string textString;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if XBOX
Components.Add(new GamerServicesComponent(this));
#endif
currentKeyboardState = Keyboard.GetState();
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
txt = true;
//Append characters to the typedText string when the player types stuff on the keyboard.
KeyGrabber.InboundCharEvent += (inboundCharacter) =>
{
//Only append characters that exist in the spritefont.
if (inboundCharacter < 32)
return;
if (inboundCharacter > 126)
return;
typedText += inboundCharacter;
};
// Get the path of the save game
string fullpath = "highscores.dat";
// Check to see if the save exists
#if WINDOWS
if (!File.Exists(fullpath))
{
//If the file doesn't exist, make a fake one...
// Create the data to save
data = new HighScoreData(5);
data.PlayerName[0] = "neil";
data.Score[0] = 2000;
data.PlayerName[1] = "barry";
data.Score[1] = 1800;
data.PlayerName[2] = "mark";
data.Score[2] = 1500;
data.PlayerName[3] = "cindy";
data.Score[3] = 1000;
data.PlayerName[4] = "sam";
data.Score[4] = 500;
SaveHighScores(data, HighScoresFilename);
}
#elif XBOX
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!iso.FileExists(fullpath))
{
//If the file doesn't exist, make a fake one...
// Create the data to save
data = new HighScoreData(5);
data.PlayerName[0] = "neil";
data.Score[0] = 2000;
data.PlayerName[1] = "shawn";
data.Score[1] = 1800;
data.PlayerName[2] = "mark";
data.Score[2] = 1500;
data.PlayerName[3] = "cindy";
data.Score[3] = 1000;
data.PlayerName[4] = "sam";
data.Score[4] = 500;
SaveHighScores(data, HighScoresFilename, device);
}
}
#endif
base.Initialize();
}
#region saving
/* Save highscores */
public static void SaveHighScores(HighScoreData data, string filename)
{
// Get the path of the save game
string fullpath = "highscores.dat";
#if WINDOWS
// Open the file, creating it if necessary
FileStream stream = File.Open(fullpath, FileMode.Create);
try
{
// Convert the object to XML data and put it in the stream
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
serializer.Serialize(stream, data);
}
finally
{
// Close the file
stream.Close();
}
#elif XBOX
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fullpath, FileMode.Create, iso))
{
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
serializer.Serialize(stream, data);
}
}
#endif
}
/* Load highscores */
public static HighScoreData LoadHighScores(string filename)
{
HighScoreData data;
// Get the path of the save game
string fullpath = "highscores.dat";
#if WINDOWS
// Open the file
FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read);
try
{
// Read the data from the file
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
data = (HighScoreData)serializer.Deserialize(stream);
}
finally
{
// Close the file
stream.Close();
}
return (data);
#elif XBOX
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fullpath, FileMode.Open,iso))
{
// Read the data from the file
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
data = (HighScoreData)serializer.Deserialize(stream);
}
}
return (data);
#endif
}
/* Save player highscore when game ends */
private void SaveHighScore()
{
// Create the data to saved
HighScoreData data = LoadHighScores(HighScoresFilename);
int scoreIndex = -1;
for (int i = data.Count - 1; i > -1; i--)
{
if (score >= data.Score[i])
{
scoreIndex = i;
}
}
if (scoreIndex > -1)
{
//New high score found ... do swaps
for (int i = data.Count - 1; i > scoreIndex; i--)
{
data.PlayerName[i] = data.PlayerName[i - 1];
data.Score[i] = data.Score[i - 1];
}
data.PlayerName[scoreIndex] = PlayerName; //Retrieve User Name Here
data.Score[scoreIndex] = score; // Retrieve score here
SaveHighScores(data, HighScoresFilename);
}
}
/* Iterate through data if highscore is called and make the string to be saved*/
public string makeHighScoreString()
{
// Create the data to save
HighScoreData data2 = LoadHighScores(HighScoresFilename);
// Create scoreBoardString
string scoreBoardString = "Highscores:\n\n";
for (int i = 0; i < 5; i++) // this part was missing (5 means how many in the list/array/Counter)
{
scoreBoardString = scoreBoardString + data2.PlayerName[i] + "-" + data2.Score[i] + "\n";
}
return scoreBoardString;
}
#endregion
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>("Spritefont1");
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
oldKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
//UpdateInput();
score = 100;
if(typedText != "")
PlayerName = typedText;
if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed)
{
SaveHighScore();
txt = false;
}
base.Update(gameTime);
}
//ignore this method
private void UpdateInput()
{
oldKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
Keys[] pressedKeys;
pressedKeys = currentKeyboardState.GetPressedKeys();
foreach (Keys key in pressedKeys)
{
if (oldKeyboardState.IsKeyUp(key))
{
if (key == Keys.Back) // overflows
textString = textString.Remove(textString.Length - 1, 1);
else
if (key == Keys.Space)
textString = textString.Insert(textString.Length, " ");
else
textString += key.ToString();
}
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
if (txt == true)
{
spriteBatch.DrawString(font, typedText, new Vector2(0, graphics.GraphicsDevice.PresentationParameters.BackBufferHeight * .5f), Color.White);
}
else if (txt == false)
{
spriteBatch.DrawString(font, makeHighScoreString(), new Vector2(500, 300), Color.Red);
}
//spriteBatch.DrawString(font, textString, new Vector2(256, 300), Color.Red);
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
public class HighScore
{
public String Name { get; set; }
public int Score { get; set; }
}
XmlSerializer serializer = new XmlSerializer(typeof(List<HighScore>));
List<HighScore> _highScores = new List<HighScore>();
void LoadData()
{
//...
Stream dataStream = //whichever way you open it
XmlSerializer serializer = new XmlSerializer(typeof(List<HighScore>));
_highScores = serializer.Deserialize(dataStream) as List<HighScore>;
}
_highScores.Add(new HighScore(){ Name = someName, Score = someScore });
var orderedScores = _highScores.OrderByDescending(s=>s.Score);
HighScore bestScore = orderedScores.FirstOrDefault();
String dirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GameName");
DirectoryInfo directory = new DirectoryInfo(dirPath);
if (!directory.Exists)
directory.Create(); //so no exception rises when you try to access your game file
this.SavegamePath = Path.Combine(dirPath, "Savegame.xml");