Using Data Files

This section discusses using data files - reading, sorting, and randomizing the data in them. We will start with an example of common tasks to use data in your program:

Example Code: Find the Animals

Create a card (mainstack) with 2 buttons and a scrolling field
    button - Open File
    button - Save File As"
    field - "in"

                               

Attach the following scripts to the buttons:

button - "Open File" - asks the user to pick a file using the "answer" dialog box, then puts it into the field "in"

on mouseUp
    answer file "File?:" 
    put it into x
    put url ("file:" & x) into field "in"
end mouseUp

button - "Save file as..." - asks the user to select a file or type a new name, then saves the contents of the field to a file

on mouseUp
    ask file "Save as..."
    put it into x
    put field "in" into url ("file:" & x)
end mouseUp

You can download and use the file below: "Animals_Sorted.txt" for practice

Projects:

1. Make a Guessing Game

        The file "Animals_Sorted.txt" is a fairly complete listing of animals. Make a guessing game where each player tries to guess an animal that is NOT in the list. 

        1. They could just look through the list. 

             So you have 2 options:

        1. Randomize the list every time you read it in 
            by adding the line: 
                sort lines of field "in" by random(the number of lines of field "in")

            e.g.
          button - "Open File" - asks the user to pick a file using the "answer" dialog box, then puts it into the field "in"

on mouseUp
    answer file "File?:" 
    put it into x
    put url ("file:" & x) into field "in"
    sort lines of field "in" by random(the number of lines of field "in")
end mouseUp

    
        2. Delete the field "in" and dp NOT show them the list
            e.g. change the script to read the file into a variable "animals" and use that instead:

            button: "Open File"

on mouseUp
    answer file "File?:" 
    put it into x
    put url ("file:" & x) into animals
end mouseUp

2. Add a button "Guess" that pop-ups a window asking for the name of an animal. Then see if that animal is in the list. If it isn't, then give the player a point and add the animal to that list

Hints: Look up the following: "Repeat" to go through the list looking for the player's guessed animal

            and look up "Put - after" to learn how to add a new animal to the list if it is not already in the list

2. Make a Guessing Game From Scratch - Harder

    Make the same game but start out with a simpler list or no list

3. Make a 2 -Player Guessing Game and keep score - Hardest

                   
ċ
cyril.pruszko@pgcps.org,
Dec 29, 2014, 7:46 AM
ċ
cyril.pruszko@pgcps.org,
Dec 29, 2014, 7:50 AM
Comments