Advertisement
Guest User

bounce and paddle game

a guest
Dec 8th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. from tkinter import *
  2. import random
  3. import time
  4. class Ball:
  5.     def __init__(self, canvas, color):
  6.         self.canvas = canvas
  7.         self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
  8.         self.canvas.move(self.id, 245, 100)
  9.         starts = [-3, -2, -1, 1, 2, 3,]
  10.         random.shuffle(starts)
  11.         self.x = starts[0]
  12.         self.y = -3
  13.         self.canvas_height = self.canvas.winfo_height()
  14.         self.canvas_width = self.canvas.winfo_width()
  15.         self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
  16.         self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
  17.  
  18.     def draw(self):
  19.         self.canvas.move(self.id, self.x, self.y)
  20.         pos = self.canvas.coords(self.id)
  21.         if pos[1] <= 0:
  22.             self.y = 1
  23.         if pos[3] >= self.canvas_height:
  24.             self.y = -1
  25.         if pos[0] <= 0:
  26.             self.x = 3
  27.         if pos[2] >= self.canvas_width:
  28.             self.x = -3
  29.            
  30. class Paddle:
  31.     def __init__(self, canvas, color):
  32.         self.canvas = canvas
  33.         self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
  34.         self.canvas.move(self.id, 200, 300)
  35.         self.x = 0
  36.         self.canvas_width = self.canvas.winfo_width()
  37.  
  38.     def draw(self):
  39.         self.canvas.move(self.id, self.x, 0)
  40.         pos = self.canvas.coords(self.id)
  41.         if pos[0] <= 0:
  42.             self.x = 0
  43.         elif pos[2] >= self.canvas_width:
  44.             self.x = 0
  45.  
  46.     def turn_left(self, evt):
  47.         self.x = -2
  48.  
  49.     def turn_right(self, evt):
  50.         self.x = 2
  51.    
  52. tk = Tk()
  53. tk.title("Game")
  54. tk.resizable(0, 0)
  55. tk.wm_attributes("-topmost", 1)
  56. canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
  57. canvas.pack()
  58. tk.update()
  59. paddle = Paddle(canvas, 'blue')
  60. ball = Ball(canvas, 'red')
  61. while 1:
  62.     ball.draw()
  63.     paddle.draw()
  64.     tk.update_idletasks()
  65.     tk.update()
  66.     time.sleep(0.01)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement