OrangoMango

PongTutorial-2

May 13th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 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.             p.draw()
  16.             self.tk.update()
  17.             time.sleep(0.01)
  18.        
  19. class Ball:
  20.     def __init__(self, game):
  21.         self.tk = game
  22.         self.id = self.tk.canvas.create_oval(20, 20, 38, 38, fill="red")
  23.         l = [-3, -2, -1, 1, 2, 3]
  24.         x = random.choice(l)
  25.         self.x, self.y = x,-3
  26.     def draw(self):
  27.         self.tk.canvas.move(self.id, self.x, self.y)
  28.         pos = self.tk.canvas.coords(self.id) #[x, y, x1, y1]
  29.         if pos[0] <= 0: #x
  30.             self.x = 3
  31.         elif pos[1] <= 0: #y
  32.             self.y = 3
  33.         elif pos[2] >= 500: #x1
  34.             self.x = -3
  35.         elif pos[3] >= 500: #y1
  36.             self.y = -3
  37.  
  38. class Paddle:
  39.   def __init__(self, game):
  40.     self.tk = game
  41.     self.id = self.tk.canvas.create_rectangle(0, 0, 100, 10, fill="blue")
  42.     self.tk.canvas.move(self.id, 200, 400)
  43.     self.x, self.y = 0, 0
  44.     self.tk.canvas.bind_all("<KeyPress-Right>", self.right)
  45.     self.tk.canvas.bind_all("<KeyPress-Left>", self.left)
  46.   def draw(self):
  47.     self.tk.canvas.move(self.id, self.x, self.y)
  48.   def left(self, event):
  49.     self.x = -2
  50.   def right(self, event):
  51.     self.x = 2
  52.            
  53. if __name__ == "__main__":
  54.     g = Game()
  55.     b = Ball(g)
  56.     p = Paddle(g)
  57.     g.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment