Sunday, 8 February 2015

Scratch style programming in Python? - A simple Pong game

I've been attempting to make Scratch style programming in Python possible -- in response to the question: "What shall I try after Scratch". Kids eventually outgrow Scratch, but the move up to Python can be big, so I'm aiming for something that's mid way between the two.

So I'm building a suite of libraries that:
  • Makes it easy to get visual or audio effects
  • Gives immediate results (like Scratch does), type some commands, press run, see results
  • Runs easily on the Raspberry Pi
  • Has depth with plenty to explore.

I've started with a game of Pong - just a bat and ball, and some bricks to knock out. Here's an example of an early version, with just the bat and ball:

import random
from geekclub.pyscratch import *


ball_img = PhotoImage(file='geekclub/images/face.gif')
bat_img = PhotoImage(file='geekclub/images/bat.gif')

ball = Sprite(ball_img)
ball.speed_x = random.randint(-4,4) * 2
ball.speed_y = random.randint(-4,4) * 2

bat = Sprite(bat_img)

def bat_follows_mouse():
    bat.move_to(mousex(), mousey())

def bounce_ball():
    if ball.touching(bat):
        ball.speed_y = -abs(ball.speed_y)
forever(bat_follows_mouse, 20)
forever(bounce_ball, 20)

There's still a fair bit to simplify, e.g. PhotoImage, create_canvas and mainloop -- but hopefully you can see that the main body of code is easy enough to read.

The full version is on Github together with more examples.

Inspired by MIT Scratch: