Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng].pdf
Скачиваний:
39
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

unnecessary to specify whether they were to be used for input or output. The FileStream can be used for both input and output, so you must specify whether you are opening the class for input or output. FileMode.Create always creates a new file with the specified name (in this case, Contacts.bin). In this particular situation, I always want the data I’m writing to overwrite any existing file with the same name. FileAccess.Write indicates that the file should be opened in a way that allows it to be written to. If you open a file with write access, you cannot read from it. Likewise, a file opened for read access cannot be written to. Opening a file with read and write access (FileAccess.ReadWrite) is possible. However, in the simple types of file handling you’re learning now, it usually makes sense to open a file for reading only or for writing only and then to close and reopen the file when you want to perform another transaction.

The bf variable is a BinaryFormatter. This is the class that converts the object into a stream of data suitable for file storage. The process of converting an object into a stream of information is called serialization because you’re converting the data to a form that can be passed to the file a bit at a time. BinaryFormatters have two primary methods: Serialize() and Deserialize(). It won’t surprise you that the Serialize() method converts a class to a file−friendly format and the Deserialize() method converts back from the file format to a usable class. The btnSave() method is about saving a class to a file, so I used the Serialize() method. This method takes two parameters: a file stream ready for output and a class to convert. Finally, I close the file stream, and the class data is saved.

Retrieving a Class

The corresponding code to retrieve the class from the file is similar to the btnSave code:

private void btnLoad_Click(object sender, System.EventArgs e) { FileStream s;

s = new FileStream("Contacts.bin", FileMode.Open, FileAccess.Read);

BinaryFormatter bf = new BinaryFormatter(); thePerson = (Contact)bf.Deserialize(s); s.Close();

txtName.Text = thePerson.Name; txtAddress.Text = thePerson.Address; txtPhone.Text = thePerson.Phone;

} // end btnLoad_Click

To load a class from the disk, the order is reversed. First, I created a file stream. I used the same file name, but this time I used FileMode.Open and FileAccess.Read to indicate that I wanted to open the file for read access. I retrieved the object from the file with the Deserialize() method. This method requires only a stream name as a parameter and returns an object. The type of object returned is unspecified, so I cast it to the Contact class. You have done type casting on primitive variable types, but you might be surprised that the technique works on objects. It does, but only in limited circumstances. In essence, you need to know that the cast will be valid. In this case, I know that I stored a Contact to the file, so I’ll have no problem converting the contents of the file to another Contact. I then copied the properties of Contact to the appropriate text boxes.

Returning to the Adventure Kit Program

When I first started thinking about the Adventure Kit project (long before C# was invented), I knew that I wanted a reusable adventure engine. I wanted to have a game engine that was really easy to use with a mouse, and I wanted to encourage users to build their own adventures. The process began by my thinking about how the adventure would be organized. I thought about an adventure

259

as a series of rooms. Each room could have multiple choices, and the user could wander through the rooms to get a sense of space. A group of rooms would form a dungeon (although the game doesn’t have to take place in a dungeon—that just seems like a good collective noun for a bunch of adventure rooms!). The user should be able to move easily between rooms. The game should be edited with an interface similar to the game interface. Because you already saw the game at the beginning of the chapter, you know that I succeeded somewhat. I want to take you through the process, though, because that’s where the real thrill of programming is.

In the Real World

If you’re an experienced programmer, you might be wondering why I haven’t covered random access files yet. The techniques described so far can be used to generate random access files (files that can be read in any order, without necessarily going through each element one at a time). You will find that C# provides other tools including XML and ADO data access. These tools provide all the functionality of random access files and are easier to implement. Still, I’ll show you a way to store and manipulate several classes at once before this chapter is over.

As usual, most of the code for this chapter’s project contains things you have learned in this chapter and earlier chapters. The Adventure Kit is interesting because it has several layers of complexity. The best way to approach this program is to look first at the data structure and then at how that data structure is used in a more complex structure. I’ll take you through the game engine itself, which is surprisingly easy to write when you have thought out the data. Next, I’ll show you how to build the editor, which is similar to the game engine but requires a little more thought to create. Finally, I’ll show you the main program, which attaches the pieces together.

In the Real World

Note that this way of thinking about a program is almost completely opposite of how a user typically sees software. The first thing the user will see is the main screen. The game screen will come next, and for many users, that is all they will ever see. Only the more sophisticated users will try to use the editor, and almost none will think about the underlying data structure. Throughout this book, I’ve been trying to show you how programmers think, which is very different from how users think. If you want to write interesting programs, you need to practice thinking about your programs from the “data up” instead of the way users usually see things.

Examining the Room Class

The first thing I did when designing the Adventure Kit was turn off the computer. I got out some paper and drew a picture, shown in Figure 9.19. I then thought about how I could describe each room. After a couple iterations, I came up with Table 9.2. If you compare Table 9.2 with Figure 9.19, you will see that Table 9.2 describes the information in Figure 9.19.

260

Figure 9.19: I drew a very simple dungeon to get a sense of what kind of data an adventure game requires.

Table 9.2: A Simple Dungeon

Number

Name

Description

N

E

S

W

0

Stuck

Can’t go that way

1

0

0

0

1

Start

Go North

2

0

0

0

2

Room 2

Go East

0

3

1

0

3

Room 3

Go South

0

0

4

2

4

Goal

You Win!

3

0

0

0

As you can see from the table, each room has a number, name, and description. In addition, each room has several direction elements. Each direction box indicates which room the user will encounter if he goes in that direction. For example, if the user is in room 2 and goes north or west, he will be sent to room 0, which tells him that he is stuck. If the user goes east from room 2, he will be sent to room 3. If he goes south from room 2, he will end up in room 1. Compare the chart to the diagram in Figure 9.19 to see how the chart describes the diagram.

Trick I’m using the term room very loosely here. It’s possible that each row of the chart represents an actual room in your game, but that’s not necessarily the case. For example, in the Enigma adventure described at the beginning of this chapter, some rooms are actions and some are decisions. Still, having a consistent vocabulary is convenient, so I’ll consider each node in the adventure a room.

When you have the chart, you will see a data structure to build. It occurred to me that each row represents a room and that building a room class that encapsulates all the data about a room would be easy.

Hint The table I used to design the Enigma game featured at the beginning of this chapter is included on the CD−ROM as Enigma.doc. Take a look at that document to see the data I used for that somewhat more complex program. Be sure you play the game through first, though, because reading the data will spoil the game for you.

261

Here’s my code for the room class: (I showed only the property code for the name property to preserve space. All the other properties work exactly like the name property, with a very standard get and set procedure. Check out the full code on the CD−ROM for the complete code.)

using System;

namespace Adventure

{

///<summary>

///Basic Data class for Adventure Game.

///Dungeon uses an array of these

///No methods, just a bunch of properties and a constructor

///Andy Harris, 3/11/02

///</summary>

[Serializable]

public class Room {

private string pName; private string pDescription; private int pNorth;

private int pEast; private int pSouth; private int pWest;

//Properties

public string Name { set {

pName = value;

}// end set get {

return pName;

}// end get

}// end Name prop

// Other properties not show. See CD−ROM for complete code

//Constructor

public Room(string name,

string description, int north,

int east, int south, int west) {

Name = name;

Description = description; North = north;

East = east; South = south; West = west;

} // end constructor } // end class def

}// end namespace

Room is a simple class. It contains six properties, one for each column of the table. The properties surround private instance variables, and the only constructor for the class requires values for every property. I made the Room class serializable because I’m sure that I’ll need to save and load it down the road. Now that I have a way for my code to describe the most important part of my program, I’ve finished the hard part of the overall design.

262

Соседние файлы в предмете Программирование на C++