Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import *
- import time, random
- class Game:
- def __init__(self):
- self.tk = Tk()
- self.tk.title("Pong tutorial")
- self.tk.resizable(0,0)
- self.tk.wm_attributes("-topmost", 1)
- self.canvas = Canvas(self.tk, width=500, height=500)
- self.canvas.pack()
- def mainloop(self):
- while True:
- b.draw()
- p.draw()
- self.tk.update()
- time.sleep(0.01)
- class Ball:
- def __init__(self, game):
- self.tk = game
- self.id = self.tk.canvas.create_oval(20, 20, 38, 38, fill="red")
- l = [-3, -2, -1, 1, 2, 3]
- x = random.choice(l)
- self.x, self.y = x,-3
- def draw(self):
- self.tk.canvas.move(self.id, self.x, self.y)
- pos = self.tk.canvas.coords(self.id) #[x, y, x1, y1]
- if pos[0] <= 0: #x
- self.x = 3
- elif pos[1] <= 0: #y
- self.y = 3
- elif pos[2] >= 500: #x1
- self.x = -3
- elif pos[3] >= 500: #y1
- self.y = -3
- class Paddle:
- def __init__(self, game):
- self.tk = game
- self.id = self.tk.canvas.create_rectangle(0, 0, 100, 10, fill="blue")
- self.tk.canvas.move(self.id, 200, 400)
- self.x, self.y = 0, 0
- self.tk.canvas.bind_all("<KeyPress-Right>", self.right)
- self.tk.canvas.bind_all("<KeyPress-Left>", self.left)
- def draw(self):
- self.tk.canvas.move(self.id, self.x, self.y)
- def left(self, event):
- self.x = -2
- def right(self, event):
- self.x = 2
- if __name__ == "__main__":
- g = Game()
- b = Ball(g)
- p = Paddle(g)
- g.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment