Tkinter Canvas Implementation of bouncing ball design game
In the actual game, if the ball touches the bottom of the canvas should let the game end, at this time first set notTouchBottom to True in the __init__()
function of the Ball class in line 16, in order to let the player can buffer, at this time also set the ball to start the game when the ball is moving up (line 15), as shown below.
self.y = -step # Vertical movement units
self.notTouchBottom = True
Modify the loop of the main program as follows.
while ball.notTouchBottom:
try:
ball.ballMove()
except:
print("Click the Close button to terminate program execution")
break
racket.racketMove()
tk.update()
time.sleep(speed) # Can control the speed of movement
Example#1
Complete bouncing ball design.
from tkinter import *
from tkinter import messagebox
from random import *
import time
cntL = 1
cntR = 1
class Ball:#class Ball(): # It is the same when written like this
def __init__(self,canvas,color,winW,winH,racket):
self.canvas = canvas
self.racket = racket
self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # Create the ball object
self.canvas.move(self.id,winW/2,winH/2) # Set the initial position of the ball
startPos = [-4, -3, -2, -1, 1, 2, 3, 4] # random number of initial x-axis movements of the ball
shuffle(startPos) # upset the ordering
self.x = startPos[0] # initial horizontal movement of the ball in units
self.y = -step # vertical units of movement
self.notTouchBottom = True
def hitRacket(self,ballPos):
racketPos = self.canvas.coords(self.racket.id)
if ballPos[2] >= racketPos[0] and ballPos[0] <= racketPos[2]:
if ballPos[3] >= racketPos[1] and ballPos[3] <= racketPos[3]:
return True
return False
def ballMove(self):
self.canvas.move(self.id, self.x, self.y) # step is a positive value to move down
ballPos = self.canvas.coords(self.id)
if ballPos[0] <= 0: # detect if the ball is over the left side of the canvas
self.x = step
if ballPos[1] <= 0: # detect if the ball is over the top of the canvas
self.y = step
if ballPos[2] >= winW: # detect if the ball goes over the right side of the canvas
self.x = -step
if ballPos[3] >= winH: # detect if the ball is over the bottom of the canvas
self.y = -step
if self.hitRacket(ballPos): # detect if the ball hits the racket
self.y = -step
if ballPos[3] >= winH: # detect if the ball is above the bottom of the canvas
self.notTouchBottom = False
class Racket():
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0,0,100,15,fill=color) # Racket Object
self.canvas.move(self.id, 270, 400)
self.x = 0
self.canvas.bind_all('<KeyPress-Right>',self.moveRight) # Bind Press and hold the right button
self.canvas.bind_all('<KeyPress-Left>',self.moveLeft) # Bind Press and hold the left button
def racketMove(self):
self.canvas.move(self.id,self.x,0)
racketPos = self.canvas.coords(self.id)
# self.x = 0
if racketPos[0] <= 0:
self.x = 0
elif racketPos[2] >= winW:
self.x = 0
def moveLeft(self,event):
global cntL
print("Press the left button",cntL)
cntL += 1
self.x = -3
def moveRight(self,event):
global cntR
print("Press the right button",cntR)
cntR += 1
self.x = 3
winW = 640 # Defines the width of the canvas
winH = 480 # Defines the height of the canvas
step = 3 # Define the speed as a displacement step
speed = 0.01 # Set the speed of movement
tk = Tk()
tk.title(" Pinball game ---- " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # Game window title
tk.wm_attributes('-topmost',1) # Make sure the game window is at the top of the screen
canvas = Canvas(tk,width=winW, height=winH,bg='black') # Create canvas
canvas.pack()
tk.update()
# The order in which the following two lines of code are executed determines which object is obscured when the two overlap
racket = Racket(canvas,'purple') # Define purple racket
ball = Ball(canvas,'yellow',winW,winH,racket) # Defines the ball object
while ball.notTouchBottom:
try:
ball.ballMove()
except:
print("Click the Close button to terminate program execution")
break
racket.racketMove()
tk.update()
time.sleep(speed) # Can control the speed of movement
messagebox.showinfo("Game Over","Game Over!!!")
# tk.mainloop()
Output: