PONG
written in
First Python examples
print “hello” > hello
x = 42
print x > 42
x = 41+1
print x try also * /
x = input() < “salut”
print x > salut
# This is a comment
3 * “Cha”
Official Python page: http://www.python.org/
Documentation: http://www.python.org/doc/
Tkinter tutorial: http://www.python.org/doc/lifepreserver/
Flow control
if/elif/else
for/else
while/else
break; continue
def
return
global
del
exec
import <name>
from <name> import <item>
If/elif/else
n = input("Weivill Geld hues de? ") ex. Password
if n < 6:
print "Bleiw doheem"
elif n< 10:
print “Science Club"
else:
print "Science Club oder Kino"
n=3 Smaller than 16
if n < 16:
print "Smaller than 16"
Comperator operators
operator function
< less than # example
<= less than or equal to if x == 2:
> greater than print “x is 2”
>= greater than or equal to else:
== equal print “x not 2”
!= not equal
<> another way to say not equal
For/else
for x in range(1:10):
print “>”+str(x)+”<”
text = “hello folks”
for x in text:
print x
list = [“one”,”two”,”tree”]
for x in list:
print x
For/else
even=[2,4,6,8,10] ex.
for x in even: Enter number: 5
if x==3: 135
text = print
“hello"found"
folks”
for x inbreak
text: # do not use else clause even=[2,4,6]
else:
print x for x in even:
print "3 is not in the list"
print x
# This could also be done with: else:
if even.count(3) > 0: print "done"
print “found”
else
print “3 is not in the list”
While/else
i=0 1
while i < 4: 2
i=i+1 3
print i 4
i=0 1
while i<4: 2
i=i+1 3
print i 4
else: done
print “done”
While/else
i=0
while i<4:
i=i+1
1
print i
break;
else:
print “done”
ex.
Enter number: 5
135
Exec (execute code)
exec(“print 'hello'”) hello
i=4
s=”print 'hello”+str(i)+” ' ”
exec(s) hello4
Import (use library)
import math math.cos(1)
from math import cos Only cos cos(1)
from math import * All from math cos(1)
Functions
def doubleAll(what): Create a reusable function
print what*3 A 'Tab' at the start if the line tells Explain python what the
python that this line still belongs to the function should do
doubleAll(3) function
doubleAll(“cha”)
def shallIBuy(costs):
print “Chocolate costs ”+str(costs)+”.”
if costs > 5:
print “I don't have enough money to buy”
else:
print “I'll buy the chocolate”
Functions may be used
shallIBuy(3)
more than once!
shallIBuy(8)
Types
Numbers: 1,2,3
Strings: "hello folks" 'hello'
Lists [2,3,4] [2,3,[3,4]] ['one','two','tree']
Dictionaries {'prenom':'Andre', 'nom':'Stemper'}
Tuples: (1,2,3) (1,2)
files: text=open('test.txt','r').read()
text=”blah” new string
type(text) <type 'str'>
type(text) is str true
type(text) is list false
Numbers
3*4 12
print "3 * 4 is", 3 * 4 3 * 4 is 12
Operation Symbol Example ex. write program
Exponentiation ** 5 ** 2 == 25 that outputs a
Multiplication * 2 * 3 == 6 sequence like this:
Division / 14 / 3 == 4 .....#.....#.....#.....#
Remainder % 14 % 3 == 2
Addition + 1 + 2 == 3
Subtraction 4 3 == 1
Numbers
1/2 == 0 ; 1.0/2.0 == 0.5 !!!
(1+2j)/(1+1j) == (1.5+0.5j) Complex numbers
a=1.5+0.5j
a.real a.real == 1.5
a.imag a.imag == 0.5
1. parentheses ()
2. exponents **
3. multiplication *, division / and remainder %
4. addition + and subtraction
Mathematiques
from math import *
sin(pi/2) 1.0
cos(pi) 1.0
import math
math.sin(pi/2) 1.0
math.cos(pi) 1.0
dir(math) returns list of
functions
Strings
“Hello folks!”
'Hello folks!'
'''Hello folks'''
3 * “Cha”
“Hello ” + “Folks” + “!”
i=4
print “The number is” + str(i) The number is 4
String Operators
ex. Anagram
text = “hello folks”
text[0] H
text[1] e
text[2:6] llo f
text[1] s
len(text) 11
len(text[1:3]) 2
text.replace(“folks”,”people”) Hello people
text.split() ['Hello', 'people']
text.upper() HELLO PEOPLE
dir(text) List of functions
Lists
list=[1,2,”hello”]
list[0] 1
list[1] 2
list[2] Hello
list[1:3] [2, ”Hello”]
list[1] “Hello”
len(list) 3
list=[1,[2,3],4]
list[0] 1
list[1] [2,3]
list[2] 4
list[1][1] 3
Lists
list=[1,2,”hello”]
dir(list) list of functions
list.append(“go”) [1,2,”hello”,”go”]
list.remove(“hello”) [1,2,”go”]
del list[1] [1,”go”]
list.extend( [1,4]) [1,”go”,1,4]
list.append([3,6]) [1,”go”,1,4,[3,6]]
list.count(1) # number of 1's in list 2
list.reverse() [[3,6],4,1,”go”,1]
list.sort()
list.__doc__ Documentation
ex. Talker
list.count.__doc__
import random
r=random.random()
Dictionaries
d={“prename”:”Andre”, 20:”Stroumpf”}
dir(d) list of functions
d[“prename”] Andre
d[20] Stroumpf
d[“test”]=”works” {“test”:”works”, “prename”:”Andre”,
20:”Stroumpf”}
del d[“hello”] {“prename”:”Andre”, 20:”Stroumpf”}
d.keys() Keys
d.values() Values
len(d)
Dictionaries
lista = [“a”,”b”,”c”] {“a”:”AAA”,
listb = [“AAA”,”BBB”,”CCC”] “b”:”BBB”,
d = dict(zip(lista,listb)) “c”:”CCC”}
d[“b”] “BBB”
ex. Phonebook
Tuples
t = (1,2,3) (1,2,3)
t[1] 2
(x,y,z) = t x=1; y=2; z=3
(x,y)=(y,x) exchange x and y
Files
f = file(“test.txt”,”w”) open file for writing
f.write(“hello”) write “hello” to file
f.close() close the file
f = file(“test.txt”,”r”) open file for reading
s= f.read() read from file
print s write to screen
f.close() close the file
s= f.readlines()
f.writelines([“hello”,”world”])
dir(f) ex. autotext
TK widget ToolKit
http://wiki.python.org/moin/TkInter
First Tkinter program
#!/usr/bin/python
from Tkinter import *
win=Tk()
win.mainloop()
Tkinter Overview
Choices: Windows / Frames:
Button Toplevel
Radiobutton Frame
Checkbutton Canvas
Menubutton
Menu
Textentry / Display
Label
Message
Entry
Listbox
Text
Tkinter Button
#!/usr/bin/python
from Tkinter import *
def hit():
print "hit"
win=Tk()
b=Button(win,text="text",command=hit)
b.pack()
win.mainloop()
Button(text="Button,command=sys.exit)
# exits program on click
Tkinter Options
Tree methods to set Widget options:
b = Button(self, fg = "red", bg = "blue") ex. Button changes
fred["fg"] = "green" color if pressed
fred.config(fg = "yellow", bg = "red”)
Options:
bg Backgroundcolor
bd Border width
height Height
width Width
underline Underline font
textvariable Variable that holds the displayed text
relief RAISED, FLAT, SUNKEN, ...
Tkinter Label
#!/usr/bin/python ex. Label changes text
from Tkinter import * if Button has been pressed
win=Tk()
l = Label(win, text="Hello, world!")
l.pack()
win.mainloop()
Tkinter Checkbutton
from Tkinter import *
win=Tk()
var1=StringVar()
c1=Checkbutton(text="Checkbutton",variable=var1, \
onvalue="Selected",offvalue="Not selected")
c1.pack()
Label(win, textvar=var1).pack()
win.mainloop()
More than one button may be
selected at the same time.
Tkinter Radiobutton
from Tkinter import *
win=Tk()
var1=StringVar()
c1=Radiobutton(text="Radio1button",variable=var1,value=1)
c2=Radiobutton(text="Radio1button",variable=var1,value=2)
c1.pack()
c2.pack()
Label(win, textvar=var1).pack()
win.mainloop()
Only one button may be
selected at the same time.
Tkinter Bind Key
from Tkinter import * <Enter>
<Leave>
Enter widget
Leave widget
def hit(): <Button1> Mouse button 1 (try 13)
<DoubleButton1> Double click on button 1
print “hit” <B1Motion> Button1 pressed and
mouse move
win=Tk() <Return> The <Enter> key
win.bind('<q>',hit) <Key> (replace key with the KEY)
<KeyRelease> Key has been released
win.mainloop()
If the key <q> is pressed, the function “hit()” is called.
This can also be used to bind special keys like <Enter>
or even mouse movement to an function.
Tkinter Bind Mouse
from Tkinter import *
def move(event):
print "Mouse X="+str(event.x)+" Y="+str(event.y)
win=Tk()
win.bind('<Motion>',move)
<Enter> Enter widget
win.mainloop() <Leave> Leave widget
<Button1> Mouse button 1 (try 13)
<DoubleButton1> Double click on button 1
<B1Motion> Button1 pressed and
mouse move
<Return> The <Enter> key
<Key> (replace key with the KEY)
<KeyRelease> Key has been released
Tkinter Canvas
from Tkinter import *
win = Tk();
can = Canvas(win, bg='white', height=200, width=200)
can.pack()
ball = can.create_oval(100, 100, 150, 150, width=2, fill='red')
line = can.create_line(20, 25, 110, 110, width=2, fill="blue", dash=(4, 8))
rect = can.create_rectangle(50, 25, 150, 75, fill="green")
win.mainloop()
can.coords(ball, 10, 10, 30, 30) # Change coordinates of widget
The window
from Tkinter import *
#
win = Tk(); # Create new window
win.title("Pong") # Name it "Pong"
win.mainloop() # redraw window, watch for keys...
pongframe.py
The window
from Tkinter import *
#
gwidth = 800; gheight = 400 # Size of the playground
ballsize = 20; # Ball size
#
x1, y1 = 0,0
win = Tk();
win.title("Pong")
can = Canvas(win, bg='black',height=gheight, width=gwidth)
can.pack(side=LEFT)
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
win.mainloop()
Oval options: Canvas options:
bg Background color bg Background color
fill Fill color bd Border width
outline Color of the line height Height
width width of the line width Width
Test: Moving the circle
...
def move(): Define a function
global x1
Add 1 to x at every step
x1 = x1 + 1
can.coords(oval1, x1, 0, x1+30, 30) Change position of oval (leave
win.after(50, move) Next step in 50 ms
x1=0; y1=0
win = Tk() Start position of the circle
can = Canvas(win, bg='white', height=400, width=800)
can.pack()
oval1 = can.create_oval(x1, y1 ,x1+30,y1+30, width=2, \
fill='white') Create the circle at positon 0
move() Animate the circle
win.mainloop()
Animate !!!
Test: Moving in two dimensions
#!/usr/bin/python
from Tkinter import *
def move():
global x1, y1
x1 = x1 + 1
y1 = y1 + 1 Add 1 to y at every step
can.coords(oval1, x1, y1, x1+30, y1+30) Change position of oval (leave
win.after(50, move)
Start position of the circle
x1=0; y1=0
win = Tk()
can = Canvas(win, bg='white', height=400, width=800) Initialize y
can.pack()
oval1 = can.create_oval(x1, y1, x+30, y1+30, width=2, \
fill='red') Create at position (x, y)
move()
win.mainloop()
Change speed?
Change direction?
Test: Changing speed / direction
#!/usr/bin/python
from Tkinter import *
def move():
global x1, y1, dx, dy
x1 = x1 + dx Add dx instead of “1”
y1 = y1 + dy
can.coords(oval1, x1, y1, x1+30, y1+30)
win.after(50, move)
x1=0; y1=0
Speed in both directions
dx=10; dy = 12
win = Tk()
can = Canvas(win, bg='white', height=400, width=800)
can.pack()
oval1 = can.create_oval(x1, y1, x1+30, y1+30, width=2, fill='red')
move()
win.mainloop()
Test: Bounce at boundry
#!/usr/bin/python
from Tkinter import *
def move():
global x1, y1, dx, dy
x1 = x1 + dx 770 = width of field – width of the ball
y1 = y1 + dy This way the ball stays in the field.
if x1 >770:
dx = dx 370 = height of field – height of the ball
if y1 >370:
dy = dy
if x1 <0: 30 = width of the ball
dx = dx
if y1 <0: 30 =height of the ball
dy = dy
can.coords(oval1, x1, y1, x1+30, y1+30)
win.after(50, move)
Rest of the program has not been changed ...
from Tkinter import *
#All together: Moving the ball
def move():
global x1, y1, dx, dy, gwidth, gheight, ballsize
x1, y1 = x1 +dx, (y1+dy) # calculate the next ball position
if y1 > (gheightballsize):
y1, dy = gheightballsize, dy
if y1 < 0:
y1, dy= 0, dy
if x1 > (gwidthballsize):
x1,dx = gwidthballsize, dx
if x1 < 0:
x1,dx = 0 , dx
can.coords(oval1, x1, y1, x1+ballsize, y1+ballsize) # change ball position
win.after(50, move) # call the function move in 50
dx, dy = 15, 15 # Directions of the ball milliseconds again
gwidth = 800; gheight = 400 # Size of the playground
ballsize = 20; # Ball size
x1, y1 = 0,0
win = Tk();
win.title("Pong")
can = Canvas(win, bg='black',height=gheight, width=gwidth)
can.pack(side=LEFT)
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
move() # draw next sequence
win.mainloop() pongnomidline.py
Adding the midline
...
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
move() # draw next sequence
win.mainloop()
Line options:
fill Fill color
outline Color of the line
width width of the line
dash dashing of the line
pongnorackets.py
Adding the rackets
... 1/2
#
dx, dy = 15, 15 # Start directions of the ball
gwidth = 800; gheight = 400 # Size of the playground
ballsize = 20; rfb = 20; rs = 60 # Ball size, racket from border, racket size
#
x1, y1 = rfb, (gheightballsize)/2
rpos=lpos=(gheightrs)/2
win = Tk(); # Create new window
win.title("Pong") # Name it "Pong"
can = Canvas(win, bg='black',height=gheight, width=gwidth)
can.pack(side=LEFT)
# Create the ball
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
# Create mid line
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")
rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")
move() # draw next sequence
win.mainloop()
pongnocontrol.py
Adding the rackets
def move(): 2/2
global x1, y1, dx, dy, gwidth, gheight, ballsize, rfb
global rpos, lpos, rs
x1, y1 = x1 +dx, (y1+dy)
if y1 > (gheightballsize):
y1, dy = gheightballsize, dy
if y1 < 0:
y1, dy= 0, dy
if x1 > (gwidthballsize):
x1,dx = gwidthballsize, dx
if x1 < 0:
x1,dx = 0 , dx
can.coords(oval1, x1, y1, x1+ballsize, y1+ballsize)
# Change the positon of the two rackets
can.coords(rracket, gwidthrfb, rpos, gwidthrfb, rpos+rs)
can.coords(lracket, rfb, lpos, rfb, lpos+rs)
win.after(50, move)
pongnocontrol.py
...
dx, dy = 15, 15
Adding Control
# Start directions of the ball
gwidth = 800; gheight = 400 # Size of the playground
1/3
ballsize = 20; rfb = 20; rs = 60 # Ball size, racket from border, racket size
rspeed = 20 # Speed of the racket
#
x1, y1 = rfb, (gheightballsize)/2
rpos=lpos=(gheightrs)/2
win = Tk();
win.title("Pong")
can = Canvas(win, bg='black',height=gheight, width=gwidth)
can.pack(side=LEFT)
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")
rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")
# Use the following keys to move the racket
win.bind('q', lup)
win.bind('p', ldown)
win.bind('<B1Motion>', rmove)
move() # draw next sequence
win.mainloop() # redraw window, watch for keys... pongnostart.py
Adding Control
2/3
#
def lup(event):
global lpos, rspeed
if lpos > rspeed:
lpos=lposrspeed
def ldown(event):
global lpos, gheight, rspeed, rs
if lpos < (gheightrsrspeed):
lpos=lpos+rspeed
def rmove(event):
global rpos, gheight, rs
ypos = event.y
if ypos > 0 and ypos < (gheightrs): # if in range
rpos = ypos
#
pongnostart.py
def move():
global x1, y1, dx, dy, gwidth, gheight, ballsize, rfb
global rpos, lpos, rs Adding Control
3/3
x1, y1 = x1 +dx, (y1+dy)
if y1 > (gheightballsize):
y1, dy = gheightballsize, dy
if y1 < 0:
y1, dy= 0, dy
# if the ball passed the right border of the field give it to the left player
if x1 > (gwidthballsize):
x1, y1 = rfb, (gheight/2)
# if the ball passed the left border give it to the right player
if x1 < 0:
x1, y1 = gwidthrfb, (gheight/2)
# test if the ball hits the left racket let it bounce back
if x1 <= rfb:
if y1>lpos and y1 < (lpos+rs):
x1, dx = rfb+5, dx
# test if the ball hits the right racket let it bounce back
if x1 >= (gwidthrfbballsize):
if y1 >= rpos and y1 <= (rpos+rs):
x1, dx = (gwidthrfbballsize5), dx
pongnostart.py
...
def move():
global x1, y1, dx, dy, playing, gwidth, gheight, ballsize, rfb
global nextplayer, rpos, lpos, rs
# position the ball on the playground Adding Start
if playing > 0:
x1, y1 = x1 +dx, (y1+dy)
else: # follow racket
1/3
if nextplayer==0: # if the next player is the right player give him the ball
x1,y1,dx = rfb+10, lpos+(rsballsize)/2, abs(dx)
else: # otherwise give the left player the ball
x1,y1,dx = gwidthrfb10, rpos+(rsballsize)/2,abs(dx)
if y1 > (gheightballsize):
y1, dy = gheightballsize, dy
if y1 < 0:
y1, dy= 0, dy
if x1 > (gwidthballsize):
x1, y1 = rfb, (gheight/2) # give right player the ball
nextplayer = 0
playing =0 # stop the game
if x1 < 0:
x1, y1 = gwidthrfb, (gheight/2) # give left player the ball
nextplayer = 1
playing =0 # stop the game
... pongnoscore.py
...
x1, y1 = rfb, (gheightballsize)/2
rpos=lpos=(gheightrs)/2 Adding Start
2/3
nextplayer = 0 # next player: 0=right, 1=left
playing = 0 # Do not play when starting the program
win = Tk();
win.title("Pong")
can = Canvas(win, bg='black',height=gheight, width=gwidth)
can.pack(side=LEFT)
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")
rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")
win.bind('q', lup)
win.bind('p', ldown)
win.bind('<B1Motion>', rmove)
win.bind('<space>', startit) # start game by hitting space
move() # draw next sequence
win.mainloop() # redraw window, watch for keys...
pongnoscore.py
Adding Start
3/3
def startit(event):
global playing
playing = 1
pongnoscore.py
Pong
def move():
global x1, y1, dx, dy, playing, gwidth, gheight, ballsize, rfb
1/3
global lplayer, rplayer, nextplayer, counter, rpos, lpos, rs
if playing > 0:
x1, y1 = x1 +dx, (y1+dy)
else:
if nextplayer==0:
x1,y1,dx = rfb+10, lpos+(rsballsize)/2, abs(dx)
else:
x1,y1,dx = gwidthrfb10, rpos+(rsballsize)/2,abs(dx)
if y1 > (gheightballsize):
y1, dy = gheightballsize, dy
if y1 < 0:
y1, dy= 0, dy
...
pong.py
...
# give the left player a point
if x1 > (gwidthballsize): Pong
lplayer=lplayer+1 # increment score for left player
x1, y1 = rfb, (gheight/2)
nextplayer = 0
# give right player the ball 2/3
playing = 0 # stop the game
if x1 < 0:
rplayer=rplayer+1 # increment score for right player
x1, y1 = gwidthrfb, (gheight/2) # give left player the ball
nextplayer = 1
playing = 0 # stop the game
if x1 <= rfb:
if y1>lpos and y1 < (lpos+rs):
x1, dx = rfb+5, dx
if x1 >= (gwidthrfbballsize):
if y1 >= rpos and y1 <= (rpos+rs):
x1, dx = (gwidthrfbballsize5), dx
# draw ball position
can.coords(oval1, x1, y1, x1+ballsize, y1+ballsize)
# draw current score
score = str(lplayer) + ":" + str(rplayer)
can.itemconfigure(counter, text=score)
...
pong.py
...
#
dx, dy = 15, 15 # Start directions of the ball Pong
gwidth = 800; gheight = 400 # Size of the playground
ballsize = 20; rfb = 20; rs = 60 # Ball size, racket from border, racket size
rspeed = 20 # Speed of the racket
3/3
lplayer=rplayer=0 # Start with no points
#
x1, y1 = rfb, (gheightballsize)/2
rpos=lpos=(gheightrs)/2
nextplayer = 0 # next player: 0=right, 1=left
playing = 0
win = Tk();
win.title("Pong")
can = Canvas(win, bg='black',height=gheight, width=gwidth)
can.pack(side=LEFT)
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
line = can.create_line(gwidth/2, 0, gwidth/2, gheight, width=4, fill="white", dash=(4, 8))
lracket = can.create_line(rfb, lpos, rfb, lpos+rs, width=10, fill="white")
rracket = can.create_line(gwidthrfb, rpos, gwidthrfb, rpos+rs, width=10, fill="white")
# Create the score text
font=('courier', 20)
counter=can.create_text(gwidth/2, 20, text='0:0', font=font, fill="white")
win.bind('q', lup)
win.bind('p', ldown) pong.py
...