OrangoMango

PongTutorial-1

May 12th, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. from tkinter import *
  2. import time, random
  3.  
  4. class Game:
  5.     def __init__(self):
  6.         self.tk = Tk()
  7.         self.tk.title("Pong tutorial")
  8.         self.tk.resizable(0,0)
  9.         self.tk.wm_attributes("-topmost", 1)
  10.         self.canvas = Canvas(self.tk, width=500, height=500)
  11.         self.canvas.pack()
  12.     def mainloop(self):
  13.         while True:
  14.             b.draw()
  15.             self.tk.update()
  16.             time.sleep(0.01)
  17.        
  18. class Ball:
  19.     def __init__(self, game):
  20.         self.tk = game
  21.         self.id = self.tk.canvas.create_oval(20, 20, 38, 38, fill="red")
  22.         l = [-3, -2, -1, 1, 2, 3]
  23.         x = random.choice(l)
  24.         self.x, self.y = x,-3
  25.     def draw(self):
  26.         self.tk.canvas.move(self.id, self.x, self.y)
  27.         pos = self.tk.canvas.coords(self.id) #[x, y, x1, y1]
  28.         if pos[0] <= 0: #x
  29.             self.x = 3
  30.         elif pos[1] <= 0: #y
  31.             self.y = 3
  32.         elif pos[2] >= 500: #x1
  33.             self.x = -3
  34.         elif pos[3] >= 500: #y1
  35.             self.y = -3
  36.            
  37. if __name__ == "__main__":
  38.     g = Game()
  39.     b = Ball(g)
  40.     g.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment