Functional Reactive Python

foremanyellowSoftware and s/w Development

Nov 7, 2013 (3 years and 10 months ago)

69 views

Functional Reactive Python

On Introducing CS to High School
Students

John Peterson

Western State College

Gunnison, CO

Goals


Get high school students excited about
CS with a 1 week summer camp


Bring them to Gunnison in the
summer

Use video gaming as the bait


Lots of outdoor activity


Integrate Math / Physics into the
program

Objectives


Teach basic principles


avoid putting
too much “in a can” or just doing drag &
drop / menu pulling (Not Alice)


Avoid big chunks of code


no time to
teach software engineering


Lots of small projects rather than one
big one


Don’t hide from basic math / physics


Use freely available software


Declarative Language Research

High school students are the best
audience I’ve ever had for exploring new
programming styles


No pre
-
conceived notions about how to
program


Eager to learn


Will tell you what they think


The Game Engine

After considering a few possibilities, we
settled on the Panda3D game engine.


Good support from CMU


Python is a good instructional language


All the basic features we needed were
covered

Modeling

We also chose to cover 3
-
D modeling a bit. We
used Blender but this had some problems
interacting with Panda:


Texture loss (we never figured this out)


Lack of support for joints / animations in the
files exported to Panda


Poorly adapted to the Windows environment

In spite of this, many students spent a lot of
time building Blender models.

Student Work

While building these 3
-
D models isn’t
programming, it did help us get
accustomed to working in 3 space and
allowed students to personalize their 3
-
D
worlds.

Software Issues

Our goal was not to teach any specific
language or software system

We wanted every program to be as
declarative as possible: elegant and
compact

FRP (Functional Reactive Programming)
was used to hide time flow from the
students

Plan A

Write a custom front end (in Haskell of
course) to allow domain
-
specific
semantics and notations, provide
compile
-
time type safety, and give
appropriate error messages.


Probably the right thing to do


Not enough time!


Doesn’t solve the debugging problem


Need to build custom IDE

Plan B

Attempt to recreate FRP using Python
libraries.


Able to use existing IDE (Pydev in
Eclipse), good debugger


Python has lambda (just uglified lisp
after all)


Students are likely to run into Python
later


Much less work!!


Programming Style

Create factory functions for all game objects
(models, lights, gui controls, camera)


these
return an object “handle”

Use python keywords and good defaulting to
avoid complexity in the factory

“Moving parts” are defined by reactive signals

Signals can be defined separately to allow
circular reference

Use signals like “time” to get motion


Functional Reactive Programming

This is work I did back in the Yale (yuck!)
days.

The big idea is to hide time flow


no
event handles, explicit updating.

A “signal” (reactive value) is something
that seems to mutate on its own as time
progresses. Time flow becomes implicit.


Example: Moving Bear

from Panda import *

begin()

p = pandaBear()

p.position = P3(sin(time), 3, cos(time))

world.cameraPos = P3(0,
-
3,0)

start()

Teaching points: sin / cos, coordinate system, trajectories


Demo1.py

More Positioning

p1 = pandaBear()

p2 = pandaBear()

def f(t):


return P3(sin(t), 3, cos(t))

p1.position = f(time)

p2.position = f(time + pi)

p1.HPR = P3(time*2,0,0)

p2.scale = 0.2 * (5 + sin(2*time))

world.cameraPos = P3(0,
-
4,0)

Demo2.py

Adding Controls

Panda3d has lots of user interface devices. We
wrapped these up in FRP style to make them
easy to use.

h = hangglider()

Text("Use slider to adjust heading")

s = Slider(max = 2*pi)

Text(s.value)

h.position = P3(sin(time), 3, cos(time))

h.HPR = P3(s.value, 0, 0)

world.cameraPos = P3(0,
-
5,0)

Demo3.py

Teaching Math

A great thing about 3
-
D gaming is that
you can’t hide from math! Students
needed to pick this up fast.

We covered linear interpolation, basic
trig, paths, periodic functions, and
vector arithmetic (Thanks to Andy Keck
for being a great math teacher!)

We didn’t shy away from calculus


here’s
an example using derivatives.


Point Where You Go

Text("Plane circles while pointing forward")

p = boeing707()

b = P3C(3, time, sin(time*3))

p.position = b

db = deriv(P3(0,0,0), b)

hpr = P3toHPR(db) # Explained in lecture

p.HPR = P3(getX(hpr)
-
radians(90),
-
getY(hpr),
0)

world.cameraPos = P3(0,
-
10,1)

Demo4.py

Teaching Programming

We also wanted to teach basic ideas in
programming

Function definition was easy

We used for loops which arranged objects
in various patterns to talk about
conditional behavior, nested loops,
arrays, and random numbers



Exploding Balls

mycolors = [red, blue, green, yellow, purple, brown, white, black]

bagOfBalls = []

endPos = []

world.cameraPos = P3(0,
-
30,0)

random.seed()

explodeSpeed = 3 #.1 is very slow, 10 is very fast

for p in range(0,getRand(50,88)):


theColor = mycolors[getRand(0,7)]


if getRand(0,1) == 1:


bagOfBalls.append(volleyBall(color = theColor))


else:


bagOfBalls.append(soccerBall(color = theColor))


endPos.append(P3(getRand(
-
5,5), getRand(
-
5,5), getRand(
-
5,5)))

startPos = P3(0,0,0)

for index in range(0, len(endPos)):


d = endPos[index]


bagOfBalls[index].position = startPos + time*explodeSpeed*d


Demo5.py

Teaching Physics

Finally, we were able to get to some simple physics.
Here’s a bouncing ball:

def launch(p0, v0):


a = P3(0,0,
-
g)


v = v0 + integral(a)


p = p0 + integral(v)


return react(p, when(getZ(p) < 0, bounce, p, v))


def bounce(p0, v0):


return launch(P3(getX(p0), getY(p0),
-
getZ(p0)),


0.9*P3(getX(v0), getY(v0),


-
getZ(v0)))


And the Roller Coaster

def f((t0, p0, v0), t1):


deltaT = t1
-

t0


pe = scaleP3(deltaT, v0) + p0


p1 = P3(getX(pe), getY(pe), coasterPath(getX(pe)))


dir = p1
-

p0


oldv = absP3(v0)


deltaz = getZ(p1)
-

getZ(p0)


s1 = oldv*oldv
-

2 * g * deltaz


if s1 < 0:


newv =
-

sqrt(
-
s1)


else:


newv = sqrt(s1) * 0.999


v1 = scaleP3(newv, normP3(dir))


return ((t1, p1, v1), p1)

Demo6.py

Roller Coaster Notes

We covered the basic physics to make
this understandable

Students can explore changes to the
physical laws

Needed to “crack open” the underlying
signal extrapolation function. That was
tough since you see the signal state and
delta t. But you can also use this to
explain how integral and derivitave work

Panda Effects

Effects are fun for the students even
though they don’t contribute to the
core subject material.

We did lighting, particle effects
(explosions, sparkles, flames, ..), and
retexturing

Check out our disco

Demo7.py

Character Animation

Panda has a number of built
-
in jointed
characters. These are easy to control


they have additional signals to set joint
angles.

What we didn’t do was introduce a way to
create animations easily. No easy way
to save a pose or sequence poses.

Games???

OK


I haven’t showed you any games. No
paddleball or asteroids or shooting
gallery or space invaders or doom.

Why? Because we didn’t get them
working yet. There was plenty to do
without gaming but next time this needs
to be fixed.

There were FRP problems, notational
problems, and time problems.

Game Engine Issues


Any game engine has a huge API


it’s a lot of
work to build on such a big base


Need to “normalize” existing models. We
wanted to use a common size / orientation so
students could swap models easily.


No 3
-
D design environment for positioning
models or creating animations.


Many high level abstractions are hard to
encapsulate. We avoided many of these
(collisions, tasks, animations).


Things the Worked


Gaming as a way to unify math, cs, and physics


Wide appeal


gamers and non gamers both
had fun


Lots of assistants


kept students from
getting frustrated (thanks to Kate, Darek,
and Stephan)


FRP made programs small and easily
understood


Great source of projects for CS students


Summer employment for CS students

Things That Didn’t Work Well


Blender (too complex, importing
problems)


FRP “in the large”


not sure how to do
this yet


Python


not really a great language for
non
-
programmers. Notational issues
kept coming up (no user
-
definable infix
operators, couldn’t get field selection to
lift, overloading problems, …)



For Next Year


More gaming!


Better publicity


it’s hard to get students in the
door.


Better software


too much time in the debugger,
poor notations, no type checking


Better preparation


more examples, better lesson
planning (especially for math / physics integration
into the CS stuff)


Music videos


this is something that we definitely
need to get to that leads nicely up to games. We
used Haskore to teach music but didn’t get the sound
to synch correctly with the action



Programming Language Issues

Making time flow implicit is a big win.

Laziness is crucial. We spent way to much time
having to re
-
invent lazy evaluation. Forward
reference was a big problem

Python’s O
-
O system kept getting in the way

Python lacks the syntactic flexibility that we
really needed

Good type systems make things a LOT easier.
We did some “load time” type checking but
didn’t get full H
-
M. Students didn’t
understand the debugger.


Multi
-
Disciplinary Education

CS instruction suffers from tunnel vision


we don’t do a
good job with students that are not going all the way
into CS.

Integrating the math and physics into our curriculum
broadens the appeal and sends a message to future
CS students

The creative side of CS is often hidden in CS1


the
game engine gives us a chance to work in a more
creative environment

We were able to cover a wide range of math


not just
one specific topic. The visual nature of the system
helps a lot.

We hope to sell this beyond just CS instruction

Conclusions

Game engines are an appealing way to get students in
the door to CS departments

The broad range of topics helped keep all of the
students on board

3
-
D modeling was a nice contrast to programming


it let
students blow off steam when programming got hard

CS needs to better serve students in other disciplines

We need to get students interested in CS earlier

The 2 girls at the camp enjoyed it as much as the hard
core gamers.

Scenes from Camp

The Last Conclusion

A good recreational program will make
students forget the frustration of
software development.