본문 바로가기
프로그래밍

데이타를 스토리지에 저장하기

by 건우아빠유리남편 2009. 7. 9.
반응형

상하좌우키로 그림을 이동시키고 ESC키로 어플리케이션을 종료시키며 종료시의 XY좌표를 저장시키는 어플리케이션을 작성한다.

저장할 파일은 실행파일과 같은 폴더의 text.txt입니다.

 

 

패스 클래스

파일의 path에 관련된 조작을 할 수 있습니다.

static String Combine(String,String)

2개의 파일 path를 이어줍니다.

 

파일 클래스

파일에 관한 조작을 할 수 있습니다.

static FileStream Create(String)

파일생성

static FileStream Open(String,FileMode,FileAccess)

파일을 연다

 

파일모드 구조체

파일모드를 표시합니다.

Append

현재파일에 추가

Create

새로 만들어 작성

CreateNew

새로 만들되 이미 있으면 예외처리

Open

열기

OpenOrCreate

열기. 없으면 만들어서 열기

Truncate

존재하는 파일을 연 후, 사이즈를 0으로 함.

 

파일액세스 열거체

파일액세스를 표시합니다.

Read

읽어오기

ReadWrite

읽고쓰기

Write

쓰기

 

파일스트림 클래스

파일스트림을 조작합니다.

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배열

byte[] w = Encoding.Unicode.GetBytes(str);

byte배열문자

String str = Encoding.Unicode.GetString(w);

※Encoding클래스에는 Unicode이외도 있다.소스코드 편집

Game1.cs를 편집한다.

 


Game1.cs

using System;

using System.IO;

using System.Text;

using System.Collections.Generic;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Storage;

 

//스토리지에 데이터를 저장한다.

namespace XnaImage {

    public class Game1 : Microsoft.Xna.Framework.Game {

        //시스템

        private GraphicsDeviceManager graphics;

        private ContentManager        content;

        private SpriteBatch           spBatch;

        private Texture2D             texture;

 

        //위치와 속도

        private int x = 100; //X좌표

        private int y = 100; //Y좌표

 

        //constructor

        public Game1() {

            //그래픽스와 컨텐츠 지정

            graphics = new GraphicsDeviceManager(this);

            content  = new ContentManager(Services);

 

            try {

                //파일의 path

                String path = Path.Combine(StorageContainer.TitleLocation,"test.txt");

                Console.WriteLine(path);

 

                //바이트 데이타를 읽어들인다.              

                byte[] w = new byte[1024];

                FileStream fs = File.Open(path,FileMode.Open,FileAccess.Read);

                int size = fs.Read(w,0,w.Length);

                fs.Close();

 

                //바이트 데이타를 XY좌표로

                String str=Encoding.Unicode.GetString(w,0,size);

                int idx=str.IndexOf(',');

                x=int.Parse(str.Substring(0,idx));

                y=int.Parse(str.Substring(idx+1));

            } catch (Exception exc) {

                x=100;

                y=100;

                Console.WriteLine(">>>>"+exc.ToString());

            }

           

            IsFixedTimeStep = true;

            TargetElapsedTime = new TimeSpan(500000);          

        }

       

        protected override void Initialize() {

            base.Initialize();

        }

       

        protected override void LoadGraphicsContent(bool loadAllContent) {

            if (loadAllContent) {       

                spBatch = new SpriteBatch(graphics.GraphicsDevice);

                texture = content.Load<Texture2D>("xna");

            }

        }

       

        protected override void UnloadGraphicsContent(bool unloadAllContent) {

            if (unloadAllContent == true) {

                content.Unload();

            }

        }

       

        protected override void Update(GameTime gameTime) {

            //키 상태를 얻어오기

            KeyboardState keyboardState = Keyboard.GetState();

           

            if (keyboardState.IsKeyDown(Keys.Left)) {

                x-=10;

            }           

            else if (keyboardState.IsKeyDown(Keys.Right)) {

                x+=10;

            }           

            if (keyboardState.IsKeyDown(Keys.Up)) {

                y-=10;

            }           

            else if (keyboardState.IsKeyDown(Keys.Down)) {

                y+=10;

            }           

           

            if (keyboardState.IsKeyDown(Keys.Escape)) {

                //파일 path

                String path = Path.Combine(StorageContainer.TitleLocation,"test.txt");

                Console.WriteLine(path);

 

                //XY좌표바이트데이터

                String str=x+","+y;

                byte[] w=Encoding.Unicode.GetBytes(str);

 

                //바이트데이타 쓰기

                FileStream fs = null;

                if (!File.Exists(path)) {

                    fs = File.Create(path);

                } else {

                    fs = File.Open(path,FileMode.Open,FileAccess.Write);

                }

                fs.Write(w,0,w.Length);

                fs.Close();

            

                Exit();

            }

           

            base.Update(gameTime);

        }

      

        protected override void Draw(GameTime gameTime) {           

            graphics.GraphicsDevice.Clear(Color.White);

           

            spBatch.Begin();

            Vector2 pos = new Vector2(x-60,y-60);

            spBatch.Draw(texture,pos,Color.White);

            spBatch.End();

 

                        base.Draw(gameTime);

        }

    }

}

 

초기값은 100 100이고 ESC로 어플리케이션을 종료시키면 종료시점의 위치를 test.txt에 써,

이후 다시 실행하였을때 그때(종료시점)의 위치에서부터 시작하는 것을 볼 수 있습니다.

 

나는 여러분을 그렇게 가르치지 않았어요..ㅋㅋ

이거 안되시는 분들은 왜 안되는지 레포트 써오시길..

 

코드보면 당연히 text.txt필요하고... 또 뭔가가 필요할텐데..;;


반응형

'프로그래밍' 카테고리의 다른 글

사운드를 재생하기  (0) 2009.07.09
XNA Framework 정리  (0) 2009.07.09
마우스 이벤트 처리하기  (0) 2009.07.09
키 이벤트 제어하기  (0) 2009.07.09
이미지에 애니메이션 붙이기  (0) 2009.07.09

댓글