File Handling - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

File Handling

Description:

... one line, separated by commas or something, and then count the number of ... The solution to this is to make sure the method that opens the file is the same ... – PowerPoint PPT presentation

Number of Views:22
Avg rating:3.0/5.0
Slides: 36
Provided by: awo4
Category:
Tags: file | handling | how | make | something | to

less

Transcript and Presenter's Notes

Title: File Handling


1
File Handling
  • CSE 203 Lecture 7
  • Annatala Wolf

2
Static Data
  • Most games make use of large amounts of static
    data! Examples
  • A game map or screen
  • Sprites of characters and enemies
  • Dialogue in the form of text boxes
  • Locations and amounts of treasure
  • Generally, the only time static data isnt used
    is when the data is produced randomly, or from
    user inupt

3
Managing Static Data
  • There are two ways to handle static data
  • 1) Declare constants explicitly in your code.
    This is called hard-coding the data, because
    youre actually writing it into code.
  • Constant mapData As Integer
  • 3, 12, 9, 8, 7,
  • 2) Store the data in files, and load up the data
    from files. This is more appropriate for
    handling large amounts of data.

4
Kinds of Files
  • A file is just a bunch of data stored in
    permanent memory. Files are stored as binary
    numbers (strings of 0s and 1s), but files can
    appear in different formats.
  • One of the most common formats is text (either as
    ASCII or Unicode), because its human
    readablebut it also wastes space (think about
    why this is).
  • Anything that isnt in text format is referred to
    as being in binary format.

5
Using Text Files
  • Text files are easy to work with because theyre
    human readable.
  • As it turns out, text files are also the only
    files (other than images and sounds) that
    Phrogram lets you open and work with. So that
    settles that problem.
  • So the big question is how can you best store
    your needed information in text format?

6
Text Conversions
  • To save information as text, well need to be
    able to convert between various Phrogram types
    and String types. Specifically, we need to be
    able to turn Integer, Decimal, and Boolean into
    Strings, and then back again.
  • Well store all kinds of data as Strings, but
    convert it back to Integer, Decimal, and Boolean
    when we read it.

7
Converting to String
  • Converting to String is easy, because Phrogram
    does it for you automatically. (Technically this
    is a bad idea because it wont catch certain
    kinds of errors.)
  • Define num As Decimal 3.1416
  • Define line As String
  • line num
  • Print(line) // prints 3.1416

8
Converting from String
  • To convert from Strings to other types, we use
    the following static functions from the Shell
    library
  • ConvertToBoolean( thing-to-convert )
  • ConvertToInteger( thing-to-convert )
  • ConvertToDecimal( thing-to-convert )
  • These operations arent smart enough to know if
    the thing youre converting is convertible until
    runtime, so they can cause errors if it cant be
    converted.

9
Conversion Examples
  • Define line As String 3.14
  • Define frac As Decimal
  • frac ConvertToDecimal(line)
  • Define bool As Boolean
  • bool ConvertToBoolean(True)
  • // This will produce an error!
  • bool ConvertToBooloan(12)

10
FileIO Library
  • To read and write text files, well use the
    FileIO Library. It includes
  • TextInputFile a class that holds an input stream
    (used to read from a text file)
  • TextOutputFile a class that holds an output file
    (used to write to a text file)
  • Three static functions that produce TextInputFile
    and TextOutputFile objects
  • FileExists( FileName As String) As Boolean a
    static method that tells you if a file exists

11
Using Text Files Directly
  • Youre more likely to use text files for input
    than output. You can edit the text files
    directly, then load them into your program at the
    beginning of the game or level (whenever you need
    the data).
  • To do this, you need to plan a format for your
    text file. Youll need to tell the program how
    to interpret the text it finds in the file.

12
Text File Formats
  • There are two easy ways to separate data elements
    in a text file.
  • Make each line a separate data element. (When
    you read from a text file, youre going to read
    in one line at a time.)
  • Use a delimiting character, like a comma or a
    slash, to separate data elements. Be sure that
    the character doesnt appear elsewhere in your
    data, though!
  • You can use both methods together.

13
Example Text File
  • Different kinds of data can be mixed together as
    long as we know how to sort it out. For example,
    we might plan for every level of the game to take
    up three lines of text an array of Integer, a
    String, and a line with enemy info.
  • We could ignore lines starting
  • with , like theyre comments
  • 3,4,10,-12,9,18,13,0
  • Level 1 Training Mode
  • 4.50,6.6,Armored Guy,3,True,True

14
Variable-Length Fields
  • We may want to store a variable amount of
    information (different numbers of enemies per
    level, etc.). There are different ways to handle
    this.
  • We could store the number of things at the top of
    the file or top of each section of the file, so
    well know how many things will follow.
  • We could just store fields up until the end of
    the file, and look for the end of file to stop.
  • We could store a bunch of data on one line,
    separated by commas or something, and then count
    the number of elements after we read it.

15
ArrayLength()
  • ArrayLength() is a static function in the Shell
    library that you should be aware of. It allows
    you to determine the length of an array.
  • This is important because some functions will
    return an array of variable length, and you wont
    know how long the array is unless you check.
  • Define items As String
  • items Split(bigText, ,)
  • Define size As Integer
  • size ArrayLength(items)

16
Reading Text Files
  • First, we need to open the file. We can use the
    static function OpenTextFile to do this.
  • Constant inFile As String L1.txt
  • Define in As TextInputFile
  • in OpenTextFile(inFile)
  • While (Not in.EndOfFile)
  • // Run some procedure we wrote
  • ReadEnemy(in)
  • End While
  • in.Close() // always close your files

17
Closing Files
  • An important note on file operations always
    remember to close your files.
  • Since a file can be opened in one operation and
    closed in another, you can end up with errors
    when passing files around.
  • The solution to this is to make sure the method
    that opens the file is the same one that closes
    it. Thus, responsibility for closing a file lies
    with the code that opened it.

18
TextInputFile
  • (The important properties ops are in bold.)
  • Created by using the static function
    OpenTextFile( Filename As String )
  • Property Filename a String
  • Property IsOpen a Boolean
  • Property EndOfFile a Boolean
  • Close() closes an open input file
  • ReadLine() As String reads in next line
  • ReadToEnd() As String reads in the whole
    remainder of file (not recommended)

19
Large Example
  • Well use a text file which holds information
    about the starting positions of five enemies on
    the screen.
  • The file format will be one line with the number
    of enemies, followed by that many enemies. Each
    enemy will consist of the following three lines
  • Filename of the enemy
  • Animation timeline
  • Starting x, starting y, x-speed, y-speed

20
Level1.txt
  • 3
  • UFO.gif
  • 100,100,100,100,50,50,50,50
  • 0,0,100,30
  • ball.jpg
  • 1
  • 100,120,-20,3.5
  • player.gif
  • 20,20,20,10,20,10
  • 50,210,0,0

21
Wheres the format?
  • Its important to remember that theres nothing
    magical about selecting a file format.
  • In order for you to read or write files in a
    predictable way, the programmer needs to ensure
    that the format you chose is read in correctly,
    and that your data files correctly follow the
    format.
  • If you do this right it can be a valuable
    time-saver. You can assume that the data is in
    the right format when you read a file, and you
    wont have to check it first.

22
GetOneSprite
  • // This procedure makes one new sprite according
    to the text file.
  • // Its only supposed to work if the next three
    lines in the file
  • // hold data in the correct format, so we can
    assume this is true.
  • Method GetOneSprite(spr As MySprite, in As
    TextInputFile)
  • Define filename As String in.ReadLine()
  • Define line As String in.ReadLine()
  • Define words As String Split(line,,)
  • Define anim As IntegerArrayLength(words)
  • Define i As Integer
  • For i 1 To ArrayLength(words)
  • animi ConvertToInteger(wordsi)
  • Next
  • line in.ReadLine()
  • words Split(line, ,)
  • Define xPos As Decimal ConvertToDecimal(word
    s1)
  • Define yPos As Decimal ConvertToDecimal(word
    s2)
  • Define xSpd As Decimal ConvertToDecimal(word
    s3)
  • Define ySpd As Decimal ConvertToDecimal(word
    s4)
  • spr New MySprite(filename, anim, xPos,
    yPos, xSpd, ySpd)

23
First Part
  • The first part of the procedure reads in two
    lines of text. We can do this without checking
    for the end of the file, because the procedure
    description requires that the next three lines of
    the input stream contain data in the right
    format. (This means its the clients
    responsibility to check the one who calls the
    op.)
  • Then we split the second line into an array using
    the static Split function. Split removes the
    commas and returns an array of Strings, one for
    each space between the commas.
  • Define filename As String in.ReadLine()
  • Define line As String in.ReadLine()
  • Define words As String Split(line,,)

24
Second Part
  • We use the static ArrayLength function to get the
    length of the words array, and then we set an
    Integer array to the same length.
  • Then we use a For loop to convert each String in
    words to an Integer, to create our animation
    timeline, anim.
  • Define anim As IntegerArrayLength(words)
  • Define i As Integer
  • For i 1 To ArrayLength(words)
  • animi ConvertToInteger(wordsi)
  • Next

25
Third Part
  • The last line of data for a sprite contains four
    values. We use Split again, and just set the
    values directly. This time we need
    ConvertToDecimal to help us.
  • line in.ReadLine()
  • words Split(line,,)
  • Define xPos As Decimal ConvertToDecimal(words1
    )
  • Define yPos As Decimal ConvertToDecimal(words2
    )
  • Define xSpd As Decimal ConvertToDecimal(words3
    )
  • Define ySpd As Decimal ConvertToDecimal(words4
    )

26
Final Part
  • Finally, we call the constructor for our MySprite
    class. This will create a new MySprite object
    and overwrite whatever was in spr before.
  • spr New MySprite(filename, anim,
  • xPos, yPos, xSpd, ySpd)

27
Using Our Procedure
  • Heres an example of how we might use the
    procedure to load sprites, given the data format
    we described.
  • Define in As InputTextFile
  • in OpenTextFile(filename)
  • Define numSprites As Integer
  • // Get number of enemies for this level
  • numSprites ConvertToInteger(in.ReadLine())
  • Define enemies As MySpritenumSprites
  • // Build all enemies from input file
  • Define i As Integer
  • For i 1 To numSprites
  • GetOneSprite(enemiesi, in)
  • Next
  • in.Close() // remember to close your files!

28
File Output
  • You may find it valuable to be able to handle
    text file output, too
  • To create save-files for a long game
  • To create a logfile
  • If you want to write a separate program that you
    use to build your levels (a game level editor,
    for example)
  • Text file output is less likely to be useful but
    it is just as simple to do.

29
TextOutputFile
  • (The important properties ops are in bold.)
  • Created by using the static function
    CreateTextFile( Filename As String)
  • Add new text to end of file by using the static
    function AppendTextFile(Filename As String)
  • Property Filename a String
  • Property IsOpen a Boolean
  • Property AppendMode Boolean
  • Close() closes an open input file
  • Write( text As String ) writes text to file
  • WriteLine( text As String ) writes, a newline

30
Output Example
  • // This method of MySprite outputs the MySprite
  • // data to file. It assumes the file is open.
  • Method PutToFile( out TextOutputFile )
  • out.WriteLine(fileName)
  • Define i As Integer
  • For i 1 To ArrayLength(anim)
  • out.Write(animi)
  • If (i lt ArrayLength(anim)) Then
  • out.Write(,)
  • End If
  • Next
  • out.WriteLine()
  • out.Write(spr.X , spr.Y ,)
  • out.WriteLine(xSpeed , ySpeed)
  • End Method

31
First Line
  • The procedure were writing assumes that the
    TextOutputFile is already open to a file and in
    the right spot to have text added, so we dont
    have to check.
  • Here, fileName is a private data member of
    MySprite.
  • out.WriteLine(fileName)

32
Second Line
  • To output the animation timeline (which is stored
    in the private data member anim), we use Write()
    to write to the same line. (Note we avoid a
    comma at the very end, and call WriteLine() to
    end the line.)
  • Define i As Integer
  • For i 1 To ArrayLength(anim)
  • out.Write(animi)
  • If (i lt ArrayLength(anim)) Then
  • out.Write(,)
  • End If
  • Next
  • out.WriteLine()

33
Third Line
  • We can use the operator to concatenate Strings
    together, to make it easier to assemble the third
    line. Here, spr, xSpeed, and ySpeed are private
    data members.
  • Again, we call Write() first, then WriteLine()
    only when were ready to end the line.
  • out.Write(spr.X , spr.Y ,)
  • out.WriteLine(xSpeed , ySpeed)

34
Using PutToFile
  • A client might use PutToFile() like so
  • Define out As TextOutputFile
  • out CreateFile(outputFilename)
  • out.WriteLine(ArraySize(enemies))
  • Define i As Integer
  • For i 1 To ArraySize(enemies)
  • enemiesi.PutToFile(out)
  • Next
  • out.Close() // remember to close

35
Your Project
  • You will probably want to use one or more files
    to hold static data for your game.
  • Youll probably want to edit the text files by
    hand, and load them in at the beginning of the
    game (or the beginning of each level).
  • You dont need to use a complicated data format
    if a simple one will do. If its easier for you
    to use multiple lines than to use a
    comma-separated list, use multiple lines.
Write a Comment
User Comments (0)
About PowerShow.com