SoFunction
Updated on 2024-11-19

python implementation of a bouncing ball

preamble

In the process of learning Python, I prefer to consolidate my learning through practical small projects, and decided to write a program to bounce a small ball. This practical routine is seen in the public number, his writing process is more complete, step by step clear, paste the code is not complete, but I still decided to try, in the process of trying due to their own basics and did not learn the class here, so it is in the fumbling stage, while learning the basics, while writing this routine, and finally it is still given to the completion of the process, although the back of the code in the Internet to see. Fortunately, I didn't see it in advance, I still learned a lot in this day.

Create a window

 from tkinter import Tk
 import tkinter
 import random
 import time
 def main():
 
 #Creating Tk objects
 tk = ()
 # Window named "Ball" #
  ("Ball")
 #. Notify the window manager to resize the layout,0,0 means it can't be pulled up
  (0,0)
 # Create an interface of length 400*500, with the default background color.
 tk.wm_attributes("-topmost",1)
 canvas = (tk, width=500, height=400, bd=0)
 # Notification Window Manager Registration Component
 ()
 # Refresh the interface
 ()

Clicking Run brings up a blank window for Ball

Classes that create a Ball

If here, for the time being, do not post the code of the writing process bit by bit, directly post the code it

class Ball():
 #Note: The special method "init" has two underscores, and the first argument is always self.
 # Since classes can act as templates, instances can be created with the
 # Force in some properties that we think must be bound. This is accomplished by defining a
 # special init method that binds the canvas, color, etc. to the instance when it's created
 def __init__(self,canvas,paddle,color):  
   = canvas
  # missing this line, keeps reporting error 'Ball' object has no attribute 'paddle'
   = paddle
   = canvas.create_oval(10,10,25,25,fill=color)
  (,245,100)

  starts=[-3,-2,-1,-1,1,1,2,3]
  (starts)
   = starts[0]# Take a random one from the list
   = -2#-2 represents the speed of y-axis motion
  self.canvas_height = .winfo_height()
  self.canvas_width = .winfo_width()
  self.hit_bottom = False # Set the initial value of hit_bottom to false
  
  
 def hit_paddle(self,pos):
  paddle_pos = ()
  if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
   if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
    return True
  return False

 def draw(self):
  # (,0,-1) # indicates upward motion
  (,,)#,,
  pos = ()
  if pos[0]<=0:
    = 2
  if pos[1]<=0:
    = 2
  # If the ball touches the right side of the canvas, change the speed to 2 pixels to the left each time.
  if pos[2]>=self.canvas_width:
    = -2
  #Returns hit_bottom as True if the ball touches the bottom of the canvas.
  if pos[3]>=self.canvas_height: 
   self.hit_bottom = True
   
  #To determine if the ball has hit the board
  if self.hit_paddle(pos) == True:
    = -3

planks

#How do I add the ability to move the board a bit with a keystroke?
class Paddle:
 def turn_left(self, evt):
   = -2
 def turn_right(self, evt):
   = 2
  
 def __init__(self,canvas,color):
   = canvas
   = canvas.create_rectangle(0,0,150,10,fill=color)
  (,200,300)
   = 0
  self.canvas_width = .winfo_width()
  .bind_all('<KeyPress-Left>',self.turn_left)
  .bind_all('<KeyPress-Right>',self.turn_right)
  
 def draw(self):
  (,,0)
  pos = ()
  if pos[0] <= 0:
    = 0
  if pos[2] >= self.canvas_width:
     = 0
   


paddle = Paddle(canvas,"blue")
ball = Ball(canvas,paddle,"red")
while 1:
 if ball.hit_bottom==False: #Execute the following statement if the bottom is not touched
  () # Call the ball object's function draw()
  ()# Call the paddle object's function draw()
  tk.update_idletasks() 
  () #Update the framework
  (0.01) #Sleep 0.01 seconds
 elif ball.hit_bottom==True: # If the ball touches the bottom
  canvas.create_text(200,100,text='Aha,you lose it,\nHow about try again?',font=('Times',22)) # Create text '...' at (200, 100) coordinates , font size 22
  () #Updates
 
()
main()

The finalization is like this, use the left and right controls of the keyboard to catch the ball on the blue planks

If you accidentally miss it, the game is over!

Finally, I feel that a lot of features are not perfect, such as not clicking the button to start again or something, later will be perfected step by step, adding the game start, score, level, difficulty, etc., when I write a completed record of the preparation process!

This is the whole content of this article.