In this assignment, you will write a toy program that allows the user to draw some dots on the screen and save their progress!
Create a file called yourname-saveprogress.rkt. Implement the big-bang program described below, and save your work. Upload to Google Classroom.
Write a world program that works as follows:
When the program starts up, an empty screen appears. The user can click or drag the mouse to add small dots to the screen.
There are two keyboard commands the user can invoke:
Pressing S (for “save”) causes the current state—that is, the current list of positions—to be saved to a file called drawing.csv. The file format is up to you, but I recommend a CSV, as discussed in class.
Pressing L (for “load”) loads the drawing in drawing.csv and sets the current world state to equal that list of positions.
That’s it!
This assignment requires you to pull together a few things we’ve covered only briefly in class. Here are some reminders.
The teachpack. Remember to include the 2htdp/batch-io teachpack!
Doing multiple things. You may find it helpful to use a feature called begin. It allows you to do multiple things in one function, for example, writing data to a file and computing a new worldstate. It works like this:
1 2 3 4 5 | (begin thing1 thing2 ... thingN) |
This code will evaluate thing1, thing2, and so on, all the way down the list. But only the last thing, thingN, is actually returned.
The reason this is useful is because you can use it with the write-file function, to write data to a file and then do something else. For example, here is a tock function that writes its current worldstate out to a file, then increases the worldstate by 1:
1 2 3 4 | (define (tock ws) (begin (write-file "how-many-tocks.txt" (number->string ws)) (+ 1 ws))) |
The begin form will first evaluate the write-file expression, then the (+ 1 ws) expression, finally returning the result of the addition.
Writing to files. In case you need a reminder of how write-file works:
Use the write-file function to write a string to a file. Running
1 | (write-file "some-file.txt" "some file contents") |
writes the text some file contents to the file some-file.txt.
If some-file.txt already exists, its contents are completely erased and overwritten with the new contents.
If it does not yet exist, a new file some-file.txt is created and filled with the desired contents.
In the contents string, every time "\n" appears, it is converted into a newline (like pressing Enter) in the file.
Reading from files. Use the read-csv-file function to read the contents of a CSV file. It returns a list of lists of strings. If the CSV file looks like this:
1 2 3 | 7,10 20,100 65,32 |
then read-csv-file will return
1 2 3 4 | (list (list "7" "10") (list "20" "100") (list "65" "32")) |
Note that you may have to use string->number to convert these strings to numbers before using them.