Monday, November 3, 2014

Sunday, November 2, 2014

Pygame Virtual Controller Update

I worked with my son for about 2 hours today on the Pygame virtual controller for Android.   The main challenge with the controller is the use of sine, cosine, and tangent.  Although we all learn trigonometry in school, how often do you use it?  Outside of making games, I never use it.

Another challenge is getting comfortable with sprites and sprite groups for the bullets.  Since the bullets are simple, we could easily make the game without sprites.  It's possible to use rectangles stored in lists.  Sprites have a number of advantages over rectangles.  I like to use sprites because its a concise way to organize all the bullets into a single sprite group and then use bullet_group.update() and bullet_group.draw() to manage all the bullets on the screen.

The first time you type in a sprite class, it looks a bit odd.  I think the oddness of the line pygame.sprite.Sprite.__init__(self) makes the sprite more intimidating than it really is.



class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((6,6))
        self.rect = self.image.get_rect()



After getting the bullets to fire properly with sprite groups, the next challenge was to get the player to move around the screen with a secondary virtual controller.  Although we built the code to calculate the angle of the controller for firing in the previous lesson, the player wasn't moving.  Once the player starts moving, the angle needs to be calculated from the center point of the player.  The modification to the code is minimal, but the conceptual leap of thinking of the opposite, adjacent and hypotenuse sides can be daunting when the triangle is moving all around the screen.  

Once you get the angle and the center, the code to move the player is straightforward.

def move(angle, center):
    hypotenuse = 10.0
    adjacent = math.cos(angle) * hypotenuse
    x = int(adjacent + center[0])
    opposite = math.sin(angle) * hypotenuse
    y = int(center[1] - opposite)
    return ((x, y))
At the end of the lesson, he had a working app with 360 degree firing and movement.

The next step is to get this working on his accelerometer game.  We're bumping up into the limitations of single-point touch and are trying to use the accelerometer for movement.  It's easy to access the Android accelerometer, but it's uncertain how playable the game will be.  We're using Cube Runner as a model for playability.


Saturday, November 1, 2014

Dart and StageXL Versus Python and Pygame for Teaching Children

I've used Python, Pygame, and pgs4a for several years.  I've been using Dart and StageXL for less than a month.  So far, I like Dart more than Javascript, Ruby, or Java.  The combination of Dart and StageXL is more friendly than Kivy.

Python and Pygame are completely different from Dart and StageXL.  This is okay with me as I'm focused on teaching children to program.  I'm not concerned about the end product.  The main criteria is what is a good language to teach programming concepts and what will keep their interest.

With this criteria in mind, I'll give my opinion.  Python and Pygame is the easiest path.  As proof of how easy it is to learn, my 9 year daughter can create games with Pygame using the PyCharm IDE and starting with a blank screen.  This is not unusual.  She's also learning Python at school in the 4th grade.  However, she's focused on turtle, not Pygame at school.   At home, she uses Pygame.  She can get through the lessons thanks to the awesome code completion of PyCharm.

My son can build complex apps on the Android phone with Python, Pygame and pgs4a.  He's actually pushing some of the limits of this stack and encountering known bugs.  I don't want to list all the bugs with pgs4a on Android, but from looking at StackOverflow and the questions I get by email, I know that multiple people are having problem with the sound mixer causing slowdown of the main while loop in some circumstances.  There are screen resizing problems on the Moto-G.  The lack of multi-point touch is causing a lot of usability problems for many people.

Although we looked at Kivy to solve some of these problems, I also evaluated Dart as a teaching alternative.  So far, I like it quite a bit.   This StageXL cookbook is quite fun.  Dart also has these cool Polymer.dart and AngularDart pieces.  There's info to get the Dart app running on Android as a web app.  I'm sure all of these will get better.

I'm planning to move to Dart as the basis for future curriculum for my son.  There's some downsides compared to Python.
  • The Dart Editor is pretty cool, but it doesn't do split-screen.  I can't view the same file in two windows at the same time.
  • PyCharm Pro can handle Dart, but it's not as smooth as the Dart Editor
  • The debug info of the Dart Editor is confusing
  • There's less Dart documentation geared for children.   There's a ton of Python information designed specifically for kids
  • Python and Pygame is easier.  
    • You can run everything in a single block of code without any functions or classes.  You can then go back and organize the code into classes when the kid gets it running.
    • You've got to deal with HTML, CSS in addition to Dart
  • The student may spend more of their time with HTML and CSS instead of learning programming concepts.  Tweaking the visual design of the app with HTML and CSS is more accessible and more rewarding than dealing with lists, parsing, and classes.   Designing the interface is not the purpose of these lessons.  The goal is to learn about data structures, classes, methods, functions, types.
  • Using the Python console or iPython is pretty awesome.  
Although I've been going fairly light on design, I think it's time to incorporate more design elements into his games.

There are many advantages to Dart:

  • The optional typing is really nice to isolate errors, especially for teaching purposes.
  • It returns a floating point if you do something like 1/3.  Python 2.7 will return 0.  Python 3.4 will return 0.33333, which is what you expect.  pgs4a will only work with Python 2.7.
  • Dart can be used on the server and the browser.  It also feels natural to do this.
  • Building Python strings with "string_here {}".format(var)  isn't as nice as Dart's "string_here$var"
  • Dart has this quick little "assert" statement to check for errors.
  • The graphics and UI components are pretty awesome on Dart.  With Pygame/pgsa, the only GUI toolkit I got to work was SGC and it was still a bit funky with things like text input on the phone.  My son was starting to waste a lot of time building his own button widgets.   Pygame is really designed for games.  It's not that great with the buttons, menus, text.  It's usable, but I think my son is ready for more UI work
  • The huge advantage to Dart is the distribution mechanism.  The Android apk file produced by pgs4a is big.  While it can be put into the Google Play store, it's a bit of a hassle, so much so that he's never put it into Google Play.  Also, his friends can't play the game on their iPhone, which is still in use by about half the teenagers.  He's still at the stage of only sharing games with friends and family, but I'm hoping that a web app will make it easier.


Fun and fast little exercises.






import 'dart:html' as html;
import 'package:stagexl/stagexl.dart';
import 'dart:math';

void main() {
  makeCanvas("4");
  html.querySelector("#button").onClick.listen(grabSize);
}

void makeCanvas(var radius){
  var canvas = html.querySelector('#stage');
  var stage = new Stage(canvas);
  var renderLoop = new RenderLoop();
  renderLoop.addStage(stage);

  List shapes = new List();
  var c_color = Color.Black;
  
  var rad = int.parse(radius);
  rad = rad * 4;
  print("the radius is $rad");

  
  for (int i = 50; i < 800; i= i + 50){
  
    for (int y = 50; y < 600; y = y +50){
      var r = new Random();
      int r_dec = r.nextInt(255);
      var r_g = new Random();
      int g_dec = r_g.nextInt(255);
      var b = new Random();
      int b_dec = b.nextInt(255);
      String a_hex_str = 255.toRadixString(16);
      String r_hex_str = r_dec.toRadixString(16);
      String g_hex_str = g_dec.toRadixString(16);
      String b_hex_str = b_dec.toRadixString(16);
      String col_hex = ('0x$a_hex_str$r_hex_str$g_hex_str$b_hex_str');
      int col = int.parse(col_hex);
      var circ = new Shape();
      circ.graphics.circle(i,  y,  rad);
      circ.graphics.fillColor(col);
      shapes.add(circ);

    }
  }
  
  for (var my_shape in shapes){
    stage.addChild(my_shape);
  }
}

void grabSize(html.MouseEvent event) {
  String the_name = (html.querySelector("#name_box") as html.InputElement).value;
  the_name = the_name.toUpperCase();
  html.querySelector("#name").text = the_name;
  String n_radius = (html.querySelector("#name").text);
  print(n_radius);
  makeCanvas(n_radius);
}


Saturday, October 25, 2014

Virtual Controller Angle Tutorial


This is part of an educational curriculum to teach 9th and 10th grade students how to build mobile games on Android. The student needs to be familiar with trigonometry. The primary target student is in 10th grade.
There are two examples. The main lesson is in main.py and focuses on the getting the angle from the virtual controller. The second lesson is in bullet.py and shows how to fire bullets from a moving player. There is sound generated each time a bullet is fired.
Here's a video snippet showing the 360 degree movement and independent firing.
Screen shot of virtual controller with bullets
Additional sounds can be downloaded from SoundBible.
Since the player is moving, I also implemented a rudimentary bounds detection so that the player doesn't move off the screen.

Create the Controller

In this lesson, the controller is a circle of radius 50. The main objective is to calculate the angle of the player's right thumb in relation to the center of the circle. Since we're running this on a desktop computer before loading it onto an Android phone, the mouse will represent the point the thumb touches the screen.
 pygame.draw.circle(SCREEN, RED, v_control.center, 50, 2)
 pygame.draw.circle(SCREEN, RED, v_control.center, 3)
There is a rectangle called, v_control that I'm using with colliderect.
 v_control = pygame.Rect(650, 450, 100, 100)
Before I calculate the angle, I make sure that the thumb is inside of the rectangle for the virtual controller.
if v_control.collidepoint(pos):
    rad = get_angle(pos, v_control.center)

Review Your Trigonometry

You'll need to use arc tangent to calculate the angle in radians. You'll also need to use sine and cosine. If your trigonometry is a rusty, review it now.
math.atanmath.sin, and math.cos are in the python math standard library. You'll need to addimport math at the top of your program.
Review of sine, cosine, and tangent
To use arc tangent you'll need to calculate the lengths of the opposite and adjacent sides of a right triangle. Since the formulas to calculate the lengths of the sides of a triangle are slightly different depending on where the thumb is on the controller, I've divided the controller into four quadrants, starting with quadrant one in the upper right and rotating counter-clockwise.
For each quadrant, you'll need to adjust the formula to calculate the opposite and adjacent sides of the triangle. For example, if the mouse is above the center of the controller, you'll need to subtract the mouse y position from the centery of the controller.

Define Each Quadrant

Diagram of characteristics of each quadrant
For the y-axis, the mouse point is either:
  1. above the center of the controller
  2. below the center of the controller
  3. at the same height of the center of the controller

Quandrants 1 and 2

Mouse Point Located Above Controller Center
If the mouse point is above the center of the controller, than check for one of three conditions:
  1. x is to the right of the controller
  2. x is to the left of the controller
  3. x is at the same point as the centerx of the controller

Quadrant 1

Mouse point is located above and to the right of controller
Diagram of Quadrant 1
Example code. Note that you need to convert to floating point.
center is a two number tuple (400,300), the center of the player. x, y is the mouse position.
    opposite = float(center[1] - y)
    if x > center[0]:
        adjacent = float(x - center[0])
        rad = math.atan(opposite/adjacent)
Here's what it looks like with the game running. Note that the angle of the mouse pointer relative to the center of the virtual controller is the same as the angle of the beam relative to the center of the player.
Screenshot of game with beam in quadrant 1


Quadrant 3

Mouse point is below and to the left of the controller center
If the mouse pointer is not in quadrant 1, add the appropriate radian value. For example, if the mouse pointer is in quadrant 3, then add pi (3.14) to the radian value.
calculation of quadrant 3

Using Radian Angle to Control Beam

Creating a beam is easier than a bullet. It is a line with the starting point at the center of the player and the end point 30 pixels out from the center.  In the next lesson, the beam becomes the gun turret.  I increased the width of the line to 6 pixels.  The end point of the gun turret will become the starting point of the bullet.  
Once you have the angle, use sine and cosine to calculate the length of opposite and adjacent sides of the triangle.
def beam(angle, center):
    """
    :param angle: radians calculated from the virtual controller
    :return: x,y coordinates of the end-point
    Start with the center of the player.  The end of the beam is 100 pixels
    away from the center.  To make a bullet instead of beam, create a class
    for bullet and have the hypoteneuse be an attribute that increases
    in size.  Remember to delete the bullet from the sprite group or list
    when it goes off the screen.
    """
    hypoteneuse = 30.0
    adjacent = math.cos(angle) * hypoteneuse
    x = adjacent + center[0]
    opposite = math.sin(angle) * hypoteneuse
    y = center[1] - opposite
    beam_end = (x, y)
    return beam_end

Shoot Bullets Instead of a Beam

If you want to shoot bullets, I'm using sprites. Don't be intimidated by sprites even though the code looks a bit funky. The bullet moves forward by increasing the length of the hypotenuse by 5 pixels.
class Bullet(pygame.sprite.Sprite):
    def __init__(self, angle, p_pos):
        YELLOW = (250, 223, 65)
        RED = (200, 10, 10)
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((6,6))
        pygame.draw.circle(self.image, YELLOW, (3, 3), 3)
        pygame.draw.circle(self.image, RED, (3,3), 1)
        self.rect = self.image.get_rect()
        self.hypotenuse = 30.0
        self.angle = angle
        self.cent = p_pos

    def update(self):
        adjacent = math.cos(self.angle) * self.hypotenuse
        x = adjacent + self.cent[0]
        opposite = math.sin(self.angle) * self.hypotenuse
        y = self.cent[1] - opposite
        self.rect.center = (x, y)
        self.hypotenuse += 5

You'll need to set up a timer for the creation of new bullets so that the bullets don't clump together in a mass of destruction every time you press the fire button.  See the code in bullet.py for an example in how to create the delay between bullet creation.

Move The Player

In the second example, I'm using almost the same code to move the player around the screen.
Move on to the second lesson on virtual controller angle tutorial.


More games with Python, Pygame, and pgs4a written by a boy in middle school and high school are available for reference to see what a typical child is doing.  It's important to understand that the examples don't show the best way to do things.  They just show a way that a child is getting stuff done. One of the problems I've found with most tutorials is that the examples are best-practice perfect for adults.  I have a theory that children also learn by thinking about how to improve on another child's code.  Additional examples are available
The most likely scenario is to start with Swarm and build from there.
My son is planning to try something with the Android accelerometer.

Saturday, October 11, 2014

Using Android Accelerometer with Pygame

My son recently started to use the accelerometer functions in his Android phone to develop games with Python. He's building a variation of Swarm, a 2D tile map game that he wrote in middle school.

The accelerometer is easy to get working with pgs4a.

To pull the x,y,z axis, use this:


You will get a floating point number for each of the three axises.

Here's a simple way to set four directions, up, down, left, right:


In the example above, I'm holding the phone sideways, in landscape mode.  The left-right movement is controlled by the 2nd value in the list and the up-down movement is controlled by the 1st item in the list.

It would easy to set up 8 direction movement or even a greater range of movement.  Unlike Swarm, which used only 8 directions for bullets, we're using sin and cos to give the bullets a greater range of movement.

In order to test the application on my desktop, I've also created a virtual controller to simulate the accelerometer.

Here's the application running on my desktop with the virtual controller.


After you install the application on your Android phone, it is a bit more difficult to debug and test the accelerometer.   You can print out the value of the accelerometer and then tune your game so that the player moves with the sensitivity that works for your game. If you print out the accel_reading, you will see a three number tuple, with the numbers all in floating point.


I/python  (21058): Initialize Python for Android
I/python  (21058): ['/data/data/org.pychildren.accel/files/lib/python2.7/site-packages', '/data/data/org.pychildren.accel/files/lib/site-python']
I/python  (21058): Opening APK '/data/app/org.pychildren.accel-1.apk'
I/python  (21058): (-3.8019924163818359, -0.31603461503982544, 8.7819318771362305)
I/python  (21058): (-3.8019924163818359, -0.31603461503982544, 8.7819318771362305)
I/python  (21058): (-3.8019924163818359, -0.31603461503982544, 8.7819318771362305)

If you don't know how to see the output from your app when it is running on your phone, read my   post explaining how you can see the output of your print statements with adb.

Here's a demo of the character running on an old Samsung phone without the flock.   The controller in the lower right is for 360 degree bullet firing.


Organizing Pygame Programs Into Separate Files - Getting Started With Basics

Everyone starts off with one long block of code in a main.py file. At some point, we break the program into separate files. In python, the separate file is called a module. Within each module, you can put functions and classes. As soon as you start to break up the program into separate files, everyone wonders how to get the variables from the main while loop in pygame to the module that is drawing something to the screen.  There are many ways to do this.  The easiest is to pass the main screen to your module as a global variable.

In this example, I call my main program main.py and I call my module draw.py.

craig@ubuntu-desktop:~/Development/dad/screens$ lsdraw.py  draw.pyc  main.py 
Ignore the file, draw.pyc.  It is created automatically when you run the program.

From main.py, you can access draw.py using import draw



My draw module just puts two graphics to the screen, one with a function and with with a class.

To access the module from the program, you can either call the function directly with draw.dot(SCREEN) or instantiate the class.
Here's the full code listing:



Image of program showing how main.py calls up the draw function from draw.py.


Sunday, September 21, 2014

Pygame on Android - What to Do When Your Android App Dies Soon After Startup

You can use adb to get console error messages and print statement output from your pygame app on Android phones.  One of the most frustrating thing for beginners to pygame on Android is when the app runs fine on their desktop, but dies soon after startup on their Android phone.  Usually, you click on the app, the splash screen comes up, then the Android app silently dies.  Unless you're using adb, corrently you could be stuck.

With the usb cable connected between your phone and desktop, run 

adb logcat |grep python

Here's the output I got today.

I/python  (  580): 
Opening APK '/data/app/org.pychildren.surfsc-2.apk'I/python  (  580): 
Traceback (most recent call last):I/python  (  580):   
File "main.py", line 323, in <module>I/python  (  580):     
main()I/python  (  580):   
File "main.py", line 296, in mainI/python  (  580):     
pprint.pprint(weather.w_dict)I/python  (  580): 
NameError: global name 'pprint' is not definedI/python  (  580): 
Python for android ended.I/ActivityManager( 7163): Process org.pychildren.surfsc:python (pid 580) has died.

It is clear that there's a problem with the pprint.pprint statement that I was using to display the Python dictionary of weather data.  It even gives me the line number in my source code.  I simply commented out the line and the app started working again on my Android phone.



I've added basic weather information to my version.  My son's version has a cleaner interface and better colors.


Tuesday, September 16, 2014

Sphinx Documentation System

I've started to encourage my son to focus on code that is easier to read by humans.  There are three parts to this:

  1. choose variable, class, and function names that are easy to understand;
  2. break the code into functions and classes instead of one long block and use local variables;
  3. comment the code
For the last part, I started off using pydoc -w filename to extract the docstrings into a document.  This didn't give me as nice a document as I wanted.  I ended up using Sphinx with the autodoc extension

$ sphinx-quickstart

I took all the defaults except for autodoc.
In conf.py, I edited the sys.path

# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
I just uncommented the line above.

I then edited index.rst
.. automodule:: main   :members:
I then edited the docstrings in my python main.py file.




Monday, September 15, 2014

Overview of Teaching Python to Graph Output from Cloud API - Spitcast Surf


I've been working with my son to build a mobile app that displays graphs of tide charts and tables of surf forecasts for the Santa Cruz region.  The app runs on his Android Motorola Moto-G phone and my Samsung Galaxy Note 2.  He grabs the data using the Spitcast API and displays the output using Pygame.


The tide has a huge influence on the quality of surf in Eastside Santa Cruz.  The optimal tide conditions at my favorite spot is a tide that is rising from 2 feet to 3.5 feet.  The swell height and direction also plays a big role.  In the future, we'll use the API from OpenWeatherMap to pull the sunrise, sunset, and wind.

The steps are:
  1. Pull data from Spitcast using urllib2
  2. Read JSON data from API into program and then convert to a list of Python dictionaries using the json library


The lesson gets off to an exciting start. The student will realize the potential of accessing cloud-based APIs. Assuming the student has a basic understanding of Python data structures lists and dictionaries, they'll also understand how easy it is to parse the data. The simple idea to convert the tide values of feet into pixels is just to multiply feet by a constant number. In this case, I multiply the height of the wave in feet by 50 to get a pixel value. For example, a wave height of 5 feet will correspond to a screen height of 250 pixels. To generate the y coordinate for the Pygame screen, I subtract the pixel height from 550. Remember that a y value of 0 is the top of the screen. I set my screen height on the phone to 500 pixels. A wave height of 1 foot will equal screen height of 50 pixels. Subtracting this from 550 will yield a y position of 500.
  1. Build start and end points for a series of 23 vertical lines spaced evenly apart to create the x axis grid. 
  2.  Create a point list that will be used by pygame.draw.lines in a future section.



At this point, the student will have a list of points that they can then draw with pygame.draw.lines for the tide graph or pygame.draw.line x, y axis grids.
Here's the basic algorithms with a bit more bells and whistles.

In the main while loop, I have this code.
This is the android-presplash.jpg screen of the application.


In the future, we'll merge the features from my son's Weather App project into Santa Cruz Surf.





Below is a shot of the app developer benefiting from the application.




Installing POSIX Man Pages on Ubuntu

I was fairly surprised to find that $ man jobs didn't work on Ubuntu 14.04.  When I looked at the installed man pages, I realized that the sections 1, 6, and 8 of the UNIX manual pages were missing.  These correspond to the user commands, games, and system admin commands.  I was able to install the man pages with:

 $ sudo apt-get install manpages-posix

This made me wonder if the current group of Linux users were using basic UNIX commands like fg, bg, jobs.  I then realized that the full set of document was available with info.  Many years ago, the man pages were in better shape then the info pages.  I now see that there's more documentation in info.  Despite being a heavy user of Emacs, I've never really warmed to the navigation commands in info and prefer the interface for less and man.  I'll give info another try over the next few months.


Saturday, September 13, 2014

Fixing Emacs ctrl-space (set mark) on Ubuntu 14.04 Trusty Tahr

The Emacs ctrl-space stopped working for me.  I'm not sure if it was related to my upgrade to Ubuntu 14.04 or if it was related to my switching from Unity to LXDE.   I fixed the problem by running ibus-setup from the command line, then changing the default keymap for input method.  The main problem is that the Intelligent Input Bus or ibus, takes over the keymap for ctrl-space.


I've found LXDE to be faster than Unity on my Lenovo laptop with 4 GB of RAM and a Celeron processor.

I've had some problems with Xfce in the past, primarily related to the HDMI port coming out of sleep mode.  

Saturday, June 21, 2014

Code Rush Documentary - Netscape / Mozilla / Silicon Valley Ups and Downs


As my son worked on file I/O in Python, I decided to watch Code Rush, a documentary that covers the amazing story of Netscape and its path to open source their core product Navigator as Mozilla.

The Code Rush story is filled with millionaires, epic stories of how people changed the world, intense human bonding, and an amazing legacy.  There was also a high human cost, with strained marriages and emotional suffering. 

The film resonated with me.  I feel that it accurately portrayed the hectic culture of the time, the belief in the Internet to radically change society, and the hope that open source with its implied philosophy of freedom and sharing was about to improve our lives. 
  
The documentary covers the time period from March 1998 to April 1999, a formative time in my life.  While the team at Netscape was changing the future of the Internet, I was on my own adventure.  During that time, I sold my Internet company, an online community in Tokyo, to PSINet, moved to Silicon Valley to kickstart the US office for Turbolinux, helped the CEO raise a ton of money, and most importantly and magically, had a child.

I started this blog to chronicle my childrens' progress to learn to program and to understand the culture of their home, Silicon Valley.  Part of what I hope to teach them is to find their own balance in a town filled with extremes.  If they are lucky, they will each have at least 10 jobs in their lives, ranging from a baker, a designer, a landscaper, therapist, a commercial fisherman, or even a programmer.  Technology could be an enabler in their future.  Or, they could never use it.

As you watch Code Rush, I encourage you to think about your own strategy to define your goals and find balance.  It's a wonderful window into the past that could help you plan your future.


Saturday, May 31, 2014

Still Keeping to Pygame Despite Great New Kivy O'Reilly Book (for now)


Since I wrote about Kivy six months ago, my son and daughter have continued to make strong progress with Pygame.  For IDEs, they've both moved to PyCharm with its awesome code completion and easy integration with GitHub.  My son is making progress with object oriented programming and recursion.

Kivy is much more powerful than Pygame.  It is also harder to use.  Although the documentation is comprehensive, only the tutorials on Pong and Paint are geared toward beginners.  It also not designed to teach programming concepts to new programmers.  Kivy is geared more toward intermediate to advance programmers that want to get a mobile app up quickly. The new O'Reilly book, Creating Apps in Kivy,  by Dusty Phillips is great.  However, most people new to programming will get stalled around chapter 4.  Although the text is easy to follow and the code examples are clear, the concepts are dense.  Just as an example, in chapter 2 of this thin book, Dusty rips into list comprehensions.  While the example is easy to understand, a new programmer is better off dealing with for loops and list iteration.

There's many other places where Dusty teaches us a valuable concept, but I think it is too much, too soon for young developers.  This said, I've been gearing up for my son''s summer by going through the Kivy book and I plan to introduce him to Kivy later in June.

Kivy makes use of a Python file, which works great in PyCharm, and a kv language file, which does not work great by default.  To get the kv language syntax highlighting and tabs working properly in PyCharm, you need to install the kv settings file.  This makes the development process much easier.  I could never get the kv language settings working properly in Emacs.    After 20 years of using Emacs, I find myself grabbing PyCharm more and more.  It's amazing to me that even at my age, I find myself moving to new tools.  I've even moved off of the Emacs key mappings and am using the default PyCharm keymaps.  JetBrains has done a nice job.

I've also gone through the Packt Publishing book, Kivy: Interactive Applications in Python.  The O'Reilly book is much better, clearer, easier to read, with less errors in grammar.  It's also newer.  The O'Reilly book does focus on Python 3, which I don't think is a good thing since most Kivy development is still done with Python 2.7.  Though, I haven't run into any problems following the Python 3 examples.


Saturday, May 17, 2014

Magic and The 3rd Grade Girl Programmer

Somewhere along our path to adulthood, we stop believing in magic.  What would make us start believing again?

It seems improbable for a 9 year old girl to program.  Yet, I see it.  As she sits in front of a Linux computer slowly typing out code in PyCharm, I think that this tiny 3rd grade girl either represents the future of computer programming or a failed opportunity for everyone.

Adjust the y axis to move the character down the screen with keyboard input, I say.  I do not expect her to succeed.  She does it with the aid of PyCharm's fantastic code completion, happily typing in:



There's a moment of magic.  I imagine every girl in America, daintily typing out our future.  In her face, I see the things that adults would pay a fortune to capture, wonderment, belief, excitement in the aha instant of understanding.  The gears click in her head, she presses the Run button on PyCharm, a Pygame window starts up with a pink girl character in the center of the screen.  Then, the 3rd grade girl coder presses the down arrow key on her Logitech keyboard.  And, the girl on the screen moves down.

  First Hacker in History
She talks about Barbie, My Little Pony, Hello Kitty, and Ada Lovelace, creator of the world's first computer algorithm.  She knows about Ada Lovelace's work on the Babbage Analytical Engine, because girls talk in 3rd grade, letting the boys know that the world's first computer programmer was female.  I hope that their girl power feeling of superiority continues on through high school.



I let her know about the Top Secret Rosies documentary of the heroic women programmers during WW II.  She wasn't surprised.


Leading ENIAC hackers mid to late 1940s

Grace Hopper in 1952 with a UNIVAC 1


More links to great female programmers.

Thursday, May 15, 2014

Windows 8.1 and Pygame Subset for Android (pgs4a)

I recently got asked a question about Windows installation on the PyChildren forum.

Here's the question:

When I touch the icon, the screen turns black, and then it goes back to my apps page in my phone. I then run the logcat to find the problem, but all it gives me is this:


V/python ( 676): Extracting private assets.
I/python ( 676): extracting private.mp3 to /data/data/com.bennybear.fungame/files
The user was not using an mp3 sound file.  When the person extracted the Windows compressed package for pgs4a, the file got added into a sub-directory of the build.    Since I was helping my son to install pgs4a on his Windows 8.1 computer, I was able to replicate the problem.   I think that the process of unzipping or extracting the pgs4a file partially failed.  When I compared the pgs4a files on two different Windows 8.1 computers, I noticed they were different.

I then went to the pgs4a site and downloaded a tar.bz2 archive.  I used tar jxvf on cygwin to extract the files.

A working directory is shown below.




Note that inside of the pgs4a-0.9.6 directory, there is not another sub-directory called pgs4a-0.9.6.  In the failed builds, I noticed that there was a temporary pgs4a-0.9.6 file created in the same directory and all the files from that directory were not properly copied into the main directory.

Once I had the files properly extracted, I noticed that the python android.py installsdk script was giving me error messages.  The script was failing to install android-api-15 and android-api-8.  I used the android.bat program in the android-sdk\tools directory to update the android SDK APIs.  

If you get an error message indicating that ant cannot find the build.xml file, this usually indicates that you don't have the proper Google APIs installed from the Android SDK (not the pgs4a android.py installsdk script).  In almost all cases, I've had to install the Google APIs with the android sdk.  On windows, the android sdk manager is called android.bat

There is another pgs4a tool called android.py.  These tools are completely unrelated.

Once I had those installed, the build went fine.  In order to connect the Windows 8.1 laptop to my son's Motorola Moto G Android phone, I had to go to the Motorola site and install the driver.  With driver from Motorola, adb was able to detect the phone and install went smoothly.

I also installed it on my Samsung Galaxy phone from his Windows 8.1 laptop.


This seems like a pain in the rear, but I encourage you to keep going.  Pygame is fun because it makes it easy to bring the creative ideas from your brain into reality very quickly.   By putting these ideas, your works of art, on a phone, you can show your friends and help them to understand a bit more about how you think as a person.

My long term goal for my children is for technology to serve as a tool for creative expression, not a barrier.  It should be fun and frivolous.  Games are great learning tools.  The work and lessons here should not be viewed through the lens of making money or job-training.  These experiments with children are about developing creative thinking and techniques to express ideas.  Sure, it's a pain to get pgs4a to install sometimes.  I agree.  But, I still think it's the best way to get kids and adults up to speed to be able to take their ideas and prototype them on a mobile phone.  

Have fun!

If you have questions or would like to join the discussion, go to the PyChildren Forum.



Sunday, May 4, 2014

Installing Pygame Subset for Android on Windows 8.1

I documented an epic tale of installing pgs4a on Windows 8.1.

Although it took more time than I anticipated, I successfully installed a Pygame application from Windows 8.1 to my Samsung Galaxy Note 2.

 I previously wrote about Shems Eddine tutorial on pgs4a installation and always assumed that the process was easy on Windows.  Wow, now I realize that there are a few hurdles.  Although several people had asked me about pgs4a installation and configuration, I could never replicate these problems on Linux.

I was able to install a rudimentary version of Asteroids that my son and I are working on.  A big part of the lesson is using sine and cosine to rotate the ship in all 360 degrees.



I've also been encouraging him to move to PyCharm.

The screenshot below shows how to start android.bat from within the pgs4a\android-sdk\tools\ directory.



View of the Android-SDK package manager showing the API 17 packages installed.