Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_Pong_lite.py
- from Tkinter import *
- from random import randint, choice
- window=Tk()
- ball_rad=50
- paddle_y=100
- def init():
- global canvas
- canvas=Canvas(window, width=500, height=500, background="green")
- canvas.pack()
- canvas.create_oval(225, 225, 225+ball_rad, 225+ball_rad, fill="blue", tags="ball")
- canvas.create_rectangle(450, 200, 455, 200+paddle_y, fill="red", tags="paddle")
- canvas.create_text(250, 10, tags="score_text", text="Score: 0")
- move_ball()
- canvas.focus_set() # for binding the kb
- canvas.bind("<Key>", key)
- canvas.bind('<Motion>', mouse_paddle_move)
- def key(event):
- canvas.destroy()
- init()
- def mouse_paddle_move(event):
- mouseY=event.y
- current_coords=canvas.coords("paddle")
- x1=current_coords[0]
- y1=current_coords[1]
- x2=current_coords[2]
- y2=current_coords[3]
- height=(y2-y1)
- canvas.coords("paddle", x1, mouseY-(height/2), x2, mouseY+(height/2))
- def move_ball(speed_x=-10, speed_y=7, score=0):
- box=canvas.bbox("ball")
- x1=box[0]
- y1=box[1]
- x2=box[2]
- y2=box[3]
- box=canvas.bbox("paddle")
- px1=box[0]
- py1=box[1]
- px2=box[2]
- py2=box[3]
- b=(y2-ball_rad / 2)
- p=(py2-paddle_y / 2)
- if x2 > px1:
- if y2 > py1 and y1 < py2:
- speed_x=abs(speed_x)*-1
- if speed_x > -54:
- speed_x += -1.2
- speed_y=(b-p) / 2
- score=score+1
- canvas.itemconfig("score_text", text="Score: "+str(score))
- if x2 > 510:
- canvas.create_text(250, 250, text="Game Over!")
- return
- if x1 <= 0:
- speed_x=abs(speed_x)
- speed_y = choice([20,15,10,-10,-15,-20])
- if y2 > 500:
- speed_y=abs(speed_y)*-1
- elif y1 < 0:
- speed_y=abs(speed_y)
- canvas.move("ball", speed_x, speed_y)
- canvas.after(40, move_ball, speed_x, speed_y, score)
- init()
- mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement