While this guide is slightly outdated, it is still useful to demonstrate how algorithmic complexity depends on implementation. Hopefully it gives you some ideas on how to implement features in an algorithmically complex way!
Here is a version of cmu_cpcs_utils.py. that you can use locally! Make sure this file is in the same folder as your code.
Many students struggle to get pip to install modules into the same Python that they are using (since most computers have several versions of Python installed at any given time). Here is a simple fix. First, in a Python file running the same version of Python as your TP, run the following code:
import sys
print(sys.executable)
Copy the line that is printed, and then run the following in your terminal:
<Insert printed output here> -m pip install <Insert module name here>
For example, your command might look something like
/usr/local/bin/python3 -m pip install pillow
Here is the code you need to read a file:
def readFile(path):
with open(path, "rt") as f:
return f.read()
With that, you can do something like this:
contents = readFile('boards/easy-01.png.txt')
Here is the code you need to write a file:
def writeFile(path, contents):
with open(path, "wt") as f:
f.write(contents)
With that, you can do something like this:
contents = 'This is just a string. Woohoo!'
writeFile('myFileName.txt', contents)
To list the files in a directory (that is, folder), first
import os
, then use os.listdir(path)
,
which returns a list of all the filenames in that directory. So
you can do something like this:
for filename in os.listdir('boards'):
if filename.endswith('.txt'):
pathToFile = f'boards/{filename}'
fileContents = readFile(pathToFile)
doSomething(fileContents)
Windows paths can include backslashes, like 'C:\15-112\term-project\tp.py'. That string will not work as a file path in Python, because backslashes are escape characters. For example, '\t' is the tab character in that string. You can fix this by using '\\', which is the escape character for a backslash! So for each \ in your path, just use two of them. Thus, the above path can be used as 'C:\\15-112\\term-project\\tp.py'.
There are two other ways to handle this. First, you can
generally use forward slashes (like '/') and those should work
in most cases on all platforms. Second, you can use
os.sep
, which is always set to the appropriate file
path separator ('/' on Mac, '\' on Windows). But if you are
intent on using backslashes on Windows, then escape them, as
noted.
In graphical apps, use app.getTextInput(prompt)
instead of input(prompt)
. This will result in a
modal input dialog box (which is desirable), instead of a
text-based input in the console (which is not desirable, not in
a graphical app). Also, do not call this function in
redrawAll
.
Use random.choice(L)
to randomly choose an element
from the list L.
Together, these two functions make it relatively easy to run an
app that uses screens (such as a splash screen, help screen, and
play screen). First, for each screen, define your MVC functions
with that screen (and an underscore) as a prefix. For example,
for the splash screen, we may name it 'splash', and then we
would define splash_onKeyPress
,
splash_redrawAll
, and so on. Note that
splash_onAppStart
is called once when the app
starts, while splash_onScreenActivate
is called
every time the active screen switches to the splash screen.
Next, you have to decide which screen will be the initial screen when the app first launches. Say it is 'splash'. Then, instead of do this:
runApp()
Do this:
runAppWithScreens(initialScreen='splash')
You can still add other keyword parameters, such as to set the width, like so:
runAppWithScreens(initialScreen='splash', width=800)
Finally, once the app is running, just call setActiveScreen(newScreen)
to change which screen is active.
Try running runAppWithScreensDemo1.py. Press 's' to switch between active screens.
As your term project grows, you may wish to place the code for each screen in its own file. Here is an example that shows you how to do that: runAppWithScreensDemo2.zip
Here are some demos that show how to use PIL to work with images: image-demos.zip.
This shows how to draw an image, and to do some basic manipulations (flipping, scaling, rotating).
This shows how to display an animated gif.
This shows how to use a spritesheet image along with
crop()
to animate a sprite.
This shows how to create a new empty image, and then to
use getpixel()
and putpixel()
to edit images. Note that these functions can be a bit slow,
especially if you loop over all the pixels in larger images.
This shows how you can use ImageDraw to draw directly onto an image. The example only draws ovals, but ImageDraw includes a bunch of other shapes. For more on ImageDraw, see here.
This shows how to save one or more images in a PDF.
If you are having issues getting transparent or partially transparent images to work, try the following steps:
import cmu_graphics
print(cmu_graphics.__file__)
You should see a path print that looks something like:
/Users/LaurenMBP/Documents/Python-Path-Files/cmu_graphics/__init__.py
The location of the cmu_graphics folder is that entire path without the __init__.py at the end. So in the example above, the folder is located at:
/Users/LaurenMBP/Documents/Python-Path-Files/cmu_graphics
surfaceFromImage
, and
replace it with this function:
def surfaceFromImage(image):
image = image.convert('RGBA').convert('RGBa')
a = array.array('B', image.tobytes('raw', 'RGBa'))
surface = cairo.ImageSurface.create_for_data(a, cairo.FORMAT_ARGB32, image.size[0], image.size[1])
return surface
Here is a demo that shows how to use sounds in your ap: sound-demo.zip.
If you want to recognize different mouse clicks (eg. right clicks), or key modifiers (eg. holding 'ctrl' or 'command'), take a look at the documentation here! Note that the drawing code in these examples follows CS1 graphics, not CPCS graphics, but the modifiers and button parameters are the same in CPCS and CS1.
If you're having trouble getting fonts to work, make sure the font name is the exact font name you have locally. For example, "Comic Sans MS" instead of just "Comic Sans", or "Impact" instead of "Impact Regular". Windows users can find the list of fonts installed on their system by going to Control Panel > Appearance and Personalization > Fonts, and Mac users can find the list of fonts in their Font Book app.
If you want to use symbols in Desktop CMU Graphics, you need to download the symbols font onto your computer manually. You can do so from this link. Afterwards, instead of specifying your font as 'symbols' like in CS Academy, you need to specify the font as 'Noto Sans Symbols 2':