▼XNA Game Studioメモ▼
ストレージへの保存
上下左右キーで画像を移動させ、Aボタンで位置情報の保存、Bボタンで位置情報の読み込みを行うプログラムを作成する。
ストレージやダイアログを表示するにはゲームコンポーネントが必要なので「Components.Add(new GamerServicesComponent(this));」と記述する。
リソースの追加
- 「はじめてのXNAアプリの作成」で作成したフォントプロセッサ「DefaultFont.spritefont」をソリューションエクスプローラのContentに追加する。
- 「グラフィックスの描画」で作成した「Graphics.cs」をプロジェクトに追加する。
- 「ゲームパッドの利用」で作成した「KeyManager.cs」をプロジェクトに追加する。
- 画像「heniheni.png」をソリューションエクスプローラのContentに追加する。
![]()
Pathクラス
ファイルのパスに対する操作を行う。
static String Combine(String,String) 2つのファイルのパスを繋げる
Fileクラス
ファイルに対する操作を行う。
static FileStream Create(String) ファイルの生成 static FileStream Open(String,FileMode,FileAccess)
ファイルを開く
FileMode列挙体
ファイルモードを表す。
Append 既存のファイルに追加 Create 新規作成 CreateNew 新規作成。すでに存在時は例外 Open 開く OpenOrCreate 開く。存在しない時は新規作成 Truncate 既存ファイルを開いた後、サイズを0にする
FileAccess列挙体
ファイルアクセスを表す。
Read 読み込み ReadWrite 読み書き Write 書き込み
FileStreamクラス
ファイルストリームの操作を行う。
void Close() 切断 int Read(byte[],int,int) 読み込み void Write(byte[],int,int) 書き込み
文字列を数値型に変換
文字列⇒int int i = int.Parse("1"); 文字列⇒long long l = long.Parse("1"); 文字列⇒float float f = float.Parse("1.1"); 文字列⇒double double d = double.Parse("1.1"); 文字列⇒bool bool b = bool.Parse("True");
文字列とbyte配列の変換
※EncodingクラスにはUnicode以外もある。
文字列⇒byte配列 byte[] w = Encoding.Unicode.GetBytes(str); byte配列⇒文字 String str = Encoding.Unicode.GetString(w);
ソースコードの編集
GameMain.cs using System; using System.IO; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; //ストレージの利用 namespace StorageEx { public class Game : Microsoft.Xna.Framework.Game { //変数 private Graphics g; //グラフィックス private KeyManager km; //キーマネージャ private StorageManager sm; //ストレージマネージャ private Texture2D image; //イメージ private int imageX;//イメージX座標 private int imageY;//イメージY座標 //コンストラクタ public Game() { g=new Graphics(this); km=new KeyManager(KeyDown,null); sm=new StorageManager(); Content.RootDirectory="Content"; } //初期化 protected override void Initialize() { //ゲームサービスコンポーネント Components.Add(new GamerServicesComponent(this)); //ベースの初期化 base.Initialize(); //ストレージデータのロード imageX=50; imageY=50; sm.Load("StorageEx","data.dat",LoadComplete); } //グラフィクスコンテントの読み込み protected override void LoadContent() { g.LoadContent(); image=g.LoadImage("heniheni"); } //グラフィクスコンテントの解放 protected override void UnloadContent() { } //更新 protected override void Update(GameTime gameTime) { if (!Guide.IsVisible) { //キーイベントの配信 km.Update(); //ゲームパッド状態の取得 GamePadState gp=GamePad.GetState(PlayerIndex.One); if (gp.IsConnected) { imageX+=(int)(gp.ThumbSticks.Left.X*10); imageY-=(int)(gp.ThumbSticks.Left.Y*10); } } //ベースの更新 base.Update(gameTime); } //キーダウン private void KeyDown(PlayerIndex index,int keyType) { if (index==PlayerIndex.One) { //終了 if (keyType==KeyManager.BACK) Exit(); //ストレージデータの書き込み if (keyType==KeyManager.A) { byte[] data=new byte[4]; data[0]=(byte)(imageX/256); data[1]=(byte)(imageX%256); data[2]=(byte)(imageY/256); data[3]=(byte)(imageY%256); sm.Save("StorageEx","data.dat",data,SaveComplete); } //ストレージデータの読み込み else if (keyType==KeyManager.B) { sm.Load("StorageEx","data.dat",LoadComplete); } //位置情報の初期化 else if (keyType==KeyManager.START) { imageX=50; imageY=50; } } } //ストレージデータの書き込み完了 private void SaveComplete(int state) { if (state==StorageManager.SUCCESS) { Util.ShowMessageDialog("情報","書き込み完了"); } else { Util.ShowMessageDialog("エラー","書き込み失敗"); } } //ストレージデータの読み込み完了 private void LoadComplete(int state,byte[] data) { if (state==StorageManager.SUCCESS) { imageX=data[0]*256+data[1]; imageY=data[2]*256+data[3]; } } //描画 protected override void Draw(GameTime gameTime) { //背景の描画 g.SetColor(255,255,255); g.Clear(); //イメージの描画 g.SetColor(255,255,255); g.DrawImage(image,imageX,imageY); //ベースの描画 base.Draw(gameTime); } } }
StorageManager.cs using System; using System.IO; using System.Xml.Serialization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; //ストレージマネージャ public class StorageManager { //定数 public static readonly int SUCCESS=0; public static readonly int ERROR =1; //デリゲート public delegate void SaveComplete(int state); public delegate void LoadComplete(int state,byte[] data); private SaveComplete saveComplete; private LoadComplete loadComplete; //ストレージ private String storageName;//ストレージ名 private String fileName; //ファイル名 private byte[] storageData;//ストレージデータ //==================== //初期化 //==================== //初期化 public StorageManager() {} //データの書き込み public void Save(String storageName,String fileName, byte[] storageData,SaveComplete saveComplete) { if (!Guide.IsVisible) { this.storageName =storageName; this.fileName =fileName; this.storageData =storageData; this.saveComplete=saveComplete; Guide.BeginShowStorageDeviceSelector(SaveDone,null); } } //データの書き込み実行 private void SaveDone(IAsyncResult result) { StorageDevice device=Guide.EndShowStorageDeviceSelector(result); if (device!=null && device.IsConnected) { StorageContainer container=null; FileStream fs=null; try { container=device.OpenContainer(storageName); String path=Path.Combine(container.Path,fileName); fs=File.Open(path,FileMode.OpenOrCreate,FileAccess.Write); fs.Write(storageData,0,storageData.Length); fs.Close(); container.Dispose(); if (saveComplete!=null) saveComplete(SUCCESS); } catch (Exception) { if (fs!=null) fs.Close(); if (container!=null) container.Dispose(); if (saveComplete!=null) saveComplete(ERROR); } } } //ストレージデータの読み込み public void Load(String storageName,String fileName, LoadComplete loadComplete) { if (!Guide.IsVisible) { this.storageName =storageName; this.fileName =fileName; this.storageData =null; this.loadComplete=loadComplete; Guide.BeginShowStorageDeviceSelector(LoadDone,null); } } //ストレージデータの読み込み実行 private void LoadDone(IAsyncResult result) { StorageDevice device=Guide.EndShowStorageDeviceSelector(result); if (device!=null && device.IsConnected) { StorageContainer container=null; FileStream fs=null; try { container=device.OpenContainer(storageName); String path=Path.Combine(container.Path,fileName); if (File.Exists(path)) { fs=File.Open(path,FileMode.OpenOrCreate,FileAccess.Read); storageData=new byte[fs.Length]; fs.Read(storageData,0,storageData.Length); fs.Close(); } container.Dispose(); if (loadComplete!=null) loadComplete(SUCCESS,storageData); } catch (Exception) { if (fs!=null) fs.Close(); if (container!=null) container.Dispose(); if (loadComplete!=null) loadComplete(ERROR,null); } } } }
Util.cs using System; using System.IO; using System.Xml.Serialization; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; //ユーティリティ public class Util { //乱数 private static Random random=new Random(); //フレームレートの指定 public static void setFrameRate(Game game,int frameRate) { game.IsFixedTimeStep=true; game.TargetElapsedTime=new TimeSpan(frameRate*10000); } //メッセージダイアログの表示 public static void ShowMessageDialog(String title,String text) { if (!Guide.IsVisible) { Guide.BeginShowMessageBox( PlayerIndex.One,title,text, new String[]{"OK"},0,MessageBoxIcon.None,null,null ); } } //乱数の取得 public static int rand(int num) { return random.Next(num); } }