Advertisement
here2share

# Tk_Pong_lite.py

Aug 9th, 2016
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # Tk_Pong_lite.py
  2.  
  3. from Tkinter import *
  4. from random import randint, choice
  5.  
  6. window=Tk()
  7.  
  8. ball_rad=50
  9. paddle_y=100
  10.  
  11. def init():
  12.     global canvas
  13.     canvas=Canvas(window, width=500, height=500, background="green")
  14.     canvas.pack()
  15.     canvas.create_oval(225, 225, 225+ball_rad, 225+ball_rad, fill="blue", tags="ball")
  16.     canvas.create_rectangle(450, 200, 455, 200+paddle_y, fill="red", tags="paddle")
  17.     canvas.create_text(250, 10, tags="score_text", text="Score: 0")
  18.  
  19.     move_ball()
  20.     canvas.focus_set() # for binding the kb
  21.     canvas.bind("<Key>", key)
  22.     canvas.bind('<Motion>', mouse_paddle_move)
  23.  
  24. def key(event):
  25.     canvas.destroy()
  26.     init()
  27.  
  28. def mouse_paddle_move(event):
  29.     mouseY=event.y
  30.     current_coords=canvas.coords("paddle")
  31.     x1=current_coords[0]
  32.     y1=current_coords[1]
  33.     x2=current_coords[2]
  34.     y2=current_coords[3]
  35.     height=(y2-y1)
  36.     canvas.coords("paddle", x1, mouseY-(height/2), x2, mouseY+(height/2))
  37.  
  38. def move_ball(speed_x=-10, speed_y=7, score=0):
  39.     box=canvas.bbox("ball")
  40.     x1=box[0]
  41.     y1=box[1]
  42.     x2=box[2]
  43.     y2=box[3]
  44.  
  45.     box=canvas.bbox("paddle")
  46.     px1=box[0]
  47.     py1=box[1]
  48.     px2=box[2]
  49.     py2=box[3]
  50.     b=(y2-ball_rad / 2)
  51.     p=(py2-paddle_y / 2)
  52.  
  53.     if x2 > px1:
  54.         if y2 > py1 and y1 < py2:
  55.             speed_x=abs(speed_x)*-1
  56.             if speed_x > -54:
  57.                 speed_x += -1.2
  58.             speed_y=(b-p) / 2
  59.             score=score+1
  60.             canvas.itemconfig("score_text", text="Score: "+str(score))
  61.         if x2 > 510:
  62.             canvas.create_text(250, 250, text="Game Over!")
  63.             return
  64.     if x1 <= 0:
  65.         speed_x=abs(speed_x)
  66.         speed_y = choice([20,15,10,-10,-15,-20])
  67.  
  68.     if y2 > 500:
  69.         speed_y=abs(speed_y)*-1
  70.     elif y1 < 0:
  71.         speed_y=abs(speed_y)
  72.  
  73.     canvas.move("ball", speed_x, speed_y)
  74.     canvas.after(40, move_ball, speed_x, speed_y, score)
  75.  
  76. init()
  77.  
  78. mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement