Python Pong
Python Pong
written in
First Python examples
print “hello” > hello
x = 42
print x > 42
x = 41+1
print x try also * /
# This is a comment
3 * “Cha”
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"
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
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()
3*4 12
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
import math
math.sin(pi/2) 1.0
math.cos(pi) 1.0
“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
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
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
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()
x1=0; y1=0
win = Tk() Start position of the circle
can = Canvas(win, bg='white', height=400, width=800)
can.pack()
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)
...
oval1 = can.create_oval(x1, y1, x1+ballsize, y1+ballsize, width=2, fill='white')
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")
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)
win.bind('q', lup)
win.bind('p', ldown)
win.bind('<B1Motion>', rmove)
win.bind('<space>', startit) # start game by hitting space
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
...