Sunday, March 30, 2014

Recursion For Kids

There's a bunch of 9th graders at my son's school talking about recursion.  They're not learning this in class.  It's just something to do.   I'm fascinated by their decision to dig into one of the fundamental ideas of computer science on their own.

For kids, recursion is simply calling a function from itself.  It's an easy concept to understand and can be used to create powerful examples in under 15 minutes.

Some of my son's friends entered into a programming contest as a group and won it.  I'm continually impressed with 9th graders.  They're tough, both mentally and physically.  I can't keep up with the teens.  Just as an example of how far behind I'm lagging, all the 14 year old programmers are also running under 5 minute miles for track.  They're fast!  Where do they get all the energy?  I don't think I could finish a mile in under 9 minutes now day with all my injuries.

Since recursion is a hot topic for kids, I introduced recursion to my son.  Here's a recursion example he wrote today.




More examples:


Monday, March 17, 2014

Python Android App Debugging Tip: adb and python print statements

With the phone connected to the USB cable and in debug mode, open a new terminal window and type:

  $ adb logcat |grep python

Update 10/11/2014. Windows users, see below. An alternative to using grep:

$ adb  logcat python *:s


You can now view standard python output from applications running on your android phone with python print statements. Output of logcat
I/python  ( 2392): play sounds
I/python  ( 2392): play sounds
I/python  ( 2392): play sounds



The most common problems with Python Subset for Android Apps dying on the Android phone at startup:
  1. you didn't import the sound mixer module properly
  2. your fonts are not in the main program directory
  3. your sound files are not in the main program directory
  4. your graphic files or map files are not in the main program directory
  5. you are using a python module that is not in your main program directory
Note that there's a common theme here of a desktop program working because the assets exist somewhere on your desktop machine, but those assets don't get transferred to your phone.  Look at your sound, graphic, and font files to make sure they are in your main directory.

In the problems above, the adb logcat command will usually show you what asset the program fails to load.

You'll save time in the debugging process if you open up two terminals at once.  In one terminal, run the adb output.  In the other terminal, build and install your program onto your phone.  With the USB cable connected, run your application on your phone.

Check to make sure you are initializing the android library.


Make sure you are importing the mixer module as shown below. In previous versions of pgs4a, I had problems with audio files that weren't in *.wav format. I only use wav files now.

Another common problem is that your application is not named main.py.

Make sure you have called the application main.py and that you are building the application with the name of the directory that contains your application.

if you are using the sgc gui toolkit with android, you need to make sure that the fonts are loaded prior to setting up the sgc screen. I've had several occasions when I got the order wrong the my application worked on the desktop and crashed on the phone. This code below is only relevant if you use sgc, which is definitely not needed to make games on android. However, if you do use sgc to make your buttons and sliders, it can be a bit tricky to use on android.




Update: 10/11/2014 As my son is starting to do some development on Windows 8.1, I realized that he didn't have grep installed and didn't really need to go through the hassle of installing grep with cygwin. I looked at the filter options for adb logcat. The key is to set everything to silent except for strings containing python. Here's some docs built into adb that are somewhat difficult to understand. The only one that you need to use is the -s or *:s
Usage: logcat [options] [filterspecs]
options include:
  -s              Set default filter to silent.
                  Like specifying filterspec '*:s'
  -f    Log to file. Default to stdout
  -r []   Rotate log every kbytes. (16 if unspecified). Requires -f
  -n       Sets max number of rotated logs to , default 4
  -v      Sets the log print format, where  is one of:

                  brief process tag thread raw time threadtime long

  -c              clear (flush) the entire log and exit
  -d              dump the log and then exit (don't block)
  -t       print only the most recent  lines (implies -d)
  -g              get the size of the log's ring buffer and exit
  -b      Request alternate ring buffer, 'main', 'system', 'radio'
                  or 'events'. Multiple -b parameters are allowed and the
                  results are interleaved. The default is -b main -b system.
  -B              output the log in binary
filterspecs are a series of
  [:priority]

where  is a log component tag (or * for all) and priority is:
  V    Verbose
  D    Debug
  I    Info
  W    Warn
  E    Error
  F    Fatal
  S    Silent (supress all output)

'*' means '*:d' and  by itself means :v

If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.
If no filterspec is found, filter defaults to '*:I'

If not specified with -v, format is set from ANDROID_PRINTF_LOG
or defaults to "brief"

Monday, March 10, 2014

Program Arcade Games Pygame/Pygame Book by Dr. Paul Craven


Dr. Paul Craven has written a nice book and site for college students learning to program.  He focuses on Python and Pygame.

It looks like a great curriculum for adults.

It's quite different from my curriculum which is targeted at children between 9 and 16.   The upper end of my curriculum is a moving target as my son gets older.

Since Dr. Craven is teaching computer science at Simpson College, he has a great pool of students ages 18 to 22 to experiment with and refine his curriculum.  It looks like a great class for college students.

His lessons on classes and sprites look like they're a nice next steps for more advanced children that have completed my curriculum.  I've been teaching my son about modules and libraries.  I've taken a different approach from Dr. Craven, but his approach seems fine for adults and possibly some children.



Sunday, March 9, 2014

Update on 9 Year Old Girl Learning Python

March 5th and 6th, 2014

Lessons focused on using blit to get a graphic of a girl onto the screen instead of a rectangle.  The lessons went smoothly.  I was surprised that she wasn't as excited about the graphic as I had thought she was going to be.  The standard rectangle may be sufficient to keep her attention.

She's still having challenges with manipulating the mouse for copy and paste techniques.  Her use of the keyboard is improving.

I realized that the use of pos = pygame.mouse.get_pos() to control onscreen graphics is easier than using the keyboard and then manipulating  x +=1 , y +=1 to move the rectangle around the screen.

Other tasks she accomplished:

  • created map background with Tiled map editor.  Began to learn about game tiles.  The map background does not have collision detection.  It is just one image that is blitted to the screen.
  • basics of map layers and graphic layers


March 9, 2014

I'm starting to learn more about her personality based on what graphics and sounds she chooses.  A big part of the lessons is the experience of a father/daughter bonding activity.  In a way, it doesn't matter if she learns programming or not.  Though, it is gratifying that she is interested in the activity and seems to have a knack for it.

Mouse manipulation and typing ability are vastly improved.  I'm shocked at how fast she's learning things, including the physical skill of typing.  If I didn't actually see a kid this age use PyCharm, I wouldn't believe that it was possible.  As I don't have another 9 year old kid to experiment with, I am assuming that she is typical and am using her as the baseline with only one data point.

Topics covered:
  • Use of gimp to edit graphic files.  
    • Add alpha transparency layer to graphics by using magic select and deleting the background.  
    • Scale image to fit on screen.  Learn more about pixel size for both image and screen.
  • Use of audacity to record and edit sound files
  • Load sound files with mixer.Sound()
  • Play sound files with name.play()
  • Collision detection with rect.collidepoint(pos)
  • I loaded the game on an Android phone for her so that she can see how easy it is to create these game on a mobile device.  She seemed to favor the desktop.  She's too young to use a mobile phone and doesn't have too much experience using them.
Video with sounds.



Game running on Android phone.





The code that the 9 year old girl wrote in PyCharm is shown below. Note that she starts with a completely blank editor screen at the start of each lesson. This means that she's repeated typing in the exact same base code from lesson 2 five times so far and has typed in the base code from lesson 1 an additional five times. I've started to modify the lesson so that she can extend the base code of lesson 2 to do what she wants.  It is important to note that up to this point, she has not used any math.  There are no addition or subtraction formulas.

The primary mathematical concept so far is for her to understand which of two numbers are greater than the other.  I am purposely using a screen that is 480 x 320 so that she can deal with manageable numbers, keeping integers under 1,000.

In the example below, she just needs to understand the following:

  • screen is 320 pixels high and 480 pixels wide
  • the middle point of the height is 160 pixels
  • the middle point of the width is 240
  • if the she wants the heart, zebra, and chipmunk to be at the same height, the center y coordinates need to all be 160 pixels down from the top of the screen
  • making the x axis smaller moves things to the left (note that be aware that the child may not know left and right.  Take this into account in your teaching.  Point to the appropriate direction if needed).
  • making the x axis larger moves things to the right (IMO, still too early for addition at this lesson.  Just use a single point.  In this case, heart, zebra, chipmunk)
  • similar concept to for the y axis
  • variable is used to hold the image after loading (handle)
  • variable is used to hold the sound after loading (handle)
  • once the image and sound are loaded, she can use the asset handle to make it do things like display to the screen or play the sound
  • collision detection is used to trigger an action.
There's quite a bit of concepts here.  I suggest repeating these concepts multiple times before extending it to addition and subtraction.


Monday, March 3, 2014

Day 8 Girl Learning Python at Age 9

I’m surprised that I’ve needed to increase the difficulty of the lessons for my daughter. Her typing is getting better. The code completion of PyCharm is awesome.
I’ve developed five drills based on this experience.

Drill 2.5

import pygame,sys  import random    pygame.init()  clock = pygame.time.Clock()    size = (480,320)  screen = pygame.display.set_mode(size)    while True:      for event in pygame.event.get():          if event.type == pygame.QUIT:              pygame.quit()              sys.exit()      p = pygame.mouse.get_pos()      c1 = random.randrange(20, 255)      c2 = random.randrange(20, 255)      c3 = random.randrange(20, 255)      color = (c1, c2, c3)      pygame.draw.circle(screen, color, p,10)      clock.tick(30)      pygame.display.update()  

Drill 2.4

import pygame,sysimport random    pygame.init()  clock = pygame.time.Clock()    size = (480,320)  screen = pygame.display.set_mode(size)    while True:      for event in pygame.event.get():          if event.type == pygame.QUIT:              pygame.quit()              sys.exit()      c1 = random.randrange(20, 255)      c2 = random.randrange(20, 255)      c3 = random.randrange(20, 255)      color = (c1, c2, c3)      x = random.randrange(0, 480)      y = random.randrange(0, 320)      pygame.draw.circle(screen, color, (x,y),20)      clock.tick(3)      pygame.display.update()  

Sunday, March 2, 2014

First Week of Python for 9 Year Old Girl

My 9 year old daughter is on day 7 of her Python learning experiment. The classes are going extremely well. Her typing is still the biggest obstacle, especially when she tries to hit ( ) with the correct fingers. The = sign is also a bit of an issue.
I reviewed lesson 2, drill 1 with her tonight. She’s completed 5 drills from lesson 1, which means that I had her start from a blank screen five times and type the same code in. It’s been smooth. I’m surprised.
Since lesson 2 is almost the same as lesson 1, she’s typed basically the same code in six times. I keep waiting for her to get bored. It hasn’t happened yet. She seems strangely interested in the IDE, mouse and keyboard.
She wanted to extend lesson 2 with different colored rectangles. In order to generate the colors, she used an online color generator. I’ve since installed both Gpick and Gcolor2 to allow her to pick the colors from the desktop.
import pygame,sys

pygame.init()

size = (480, 320)
screen = pygame.display.set_mode(size)

RED = (255,0, 0)
GREEN = (0, 200, 0)
PURPLE = (157, 0, 254)
player_rect = pygame.Rect(150, 160, 80, 80)
r = pygame.Rect(10, 160, 80, 80)
r2 = pygame.Rect(300, 160, 80, 80)


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.draw.rect(screen, GREEN, player_rect)
    pygame.draw.rect(screen, RED, r)
    pygame.draw.rect(screen, PURPLE,r2)
    pygame.display.update()