The fifth stage of the fun-to-learn Python pinball game-Add a racket

Source: Internet
Author: User

This time, I followed the "Fun learning python--teach children to learn programming", to add a program to use the keyboard around the key control of the racket.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/8B/57/wKiom1hKBgSB9RGVAAA8pOc-p98581.jpg "title=" Paddle.jpg "alt=" Wkiom1hkbgsb9rgvaaa8poc-p98581.jpg "/>


#引入下列模块from  tkinter import *                                                    #画图模块import  random                                                            #随机数模块import  time                                                              #时间模块 # Create a game window and Canvas tk = tk ()                                                                  #用Tk () class creates a Tk object, which is a basic window on which you can add something else tk.title ("Game")                                                          #给Tk对象窗口加一个标题tk. Resizable (0,0)                                                         #tk窗口大小不可调整tk. Wm_attributes ("-topmost", 1)                                            #告诉tkinter把窗口放到最前面canvas  = canvas (tk,width=500,heigh=400,bd=0,highlightthickness=0)      #Canvas是一个画布类canvas. Pack ()                                                             #按照上面一行指定的宽度高度参数调整其自身大小tk. Update ()                                                               #update强制更新屏幕, re-painting # Create Ball Class class ball:    def __init__ (Self,canvas,color):                                    #初始化函数, including canvas and color parameters          self.canvas = canvas                                           # Assign the parameter canvas to the object variable canvas         self.id = canvas.create_oval (10,10,25,25,fill=color)            #创建椭圆, Upper-left and lower-right XY coordinates, returning id        representing the graphic  self.canvas.move (self.id,245,100)                              # The center of the canvas in which the ellipse (ball) is moved, the graphic is represented by an ID         starts = [-3,-2,-1,1,2,3]                                      # Give the starting value of the X component (x and y represent the horizontal and vertical components)         random.shuffle (starts)                                           #随机混排序, assign a value to the object variable x to get the random component value when it starts. Cause the ball to start at different angles each time         self.x = starts[0]                                               #对象变量x就是水平分量移动的初始值, equivalent to move left and right, the value represents how many pixels to move          self.y = -3                                                    # The object variable y is the initial value of the vertical component movement, which is equivalent to moving up and down, and the value represents how many pixels are moved         self.canvas_height =  self.canvas.winfo_height ()                #获取画布的高度, the canvas height is measured from top to bottom                         self.canvas_width = self.canvas.winfo_width ()                   #获取画布的宽度     def draw (self ):                                                     #定义小球的画图动作          self.canvas.move (SELF.ID,SELF.X,SELF.Y)                        # Move the ball by the pixel values defined by x and Y, such as 3 to move the 3 pixel position &NBSp;        pos = self.canvas.coords (self.id)                                #coords函数通过id返回画布球的坐标列表, Pos[x1,y1,x2,y2], representing the XY coordinates of the lower-right corner of the ellipse, respectively         if pos[1] <= 0:                                                  #当球左上角y1坐标小于等于0, which touches the top of the canvas              self.y = 3                                                  #重新设置对象变量y为3, start the vertical component Move down          if pos[3] >= self.canvas_height:                                #当球右下角y2坐标超过画布高度 (bottom)              self.y = -3                                                # Reset object variable y to-3, start vertical component Move up         if pos[0] <= 0:                                                  #当球左上角x1坐标小于等于0, which touches the left border of the canvas              self.x = 3                                                 # Reset object variable x to 3, start horizontal component Move right         if pos[2] >=  self.canvas_width:                                #当球右下角x2坐标超过画布有边框             self.x = -3                                                  #重新设置对象变量x为-3, start horizontal component Move left # Create paddle class class paddle:    def __init__ (self, Canvas,color):                                   #初始化函数, Contains canvas and color parameters         self.canvas = canvas                                             #把参数canvas赋值给对象变量canvas         self.id =  Canvas.create_rectangle (0, 0,100,10,fill=color)       #创建长方形, upper-left and lower-right XY coordinates, returning id      representing the graphic    self.canvas.move (self.id,200,300)                                The initial position of the #把长方形 (beat) movement, the graph is represented by the ID         self.x = 0                                                       #设置对象变量x, with an initial value of 0. That is, the graph does not move first          self.canvas_width = self.canvas.winfo_width ()                   #获取画布的宽度         &Nbsp;self.canvas.bind_all (' <KeyPress-Left> ', self.turn_left)        # Initialize event ' Press left key ' and function left to move binding         self.canvas.bind_all (' <keypress-right > ', self.turn_right)       #初始化时将事件 ' press right ' and the function to move the binding to the right              def turn_left (SELF,EVT):                                           # Define a function that moves the beat to the left         self.x = -2                                                      #每次向左移动2个像素, more and more left on the canvas, the values are getting smaller, so a negative number is required         def  turn_right (SELF,EVT):                                           #定义使拍子向右移动的函数          self.x = 2                                                       #每次向右移动2个像素, more and more to the right on the canvas, the values are getting bigger, so you need a positive number              def draw (self):                                                     #定义拍子的画图动作          self.canvas.move (self.id,self.x,0)                               #和小球配置大致相同, the paint move moves only around the horizontal, so the Y component is set to 0        pos =  Self.canvas.coords (self.id)                               #获取拍子的左上和右下角坐标值         if pos[0] <= 0:                                                # If the upper-left corner of the horizontal component x, that is, the left side of the beat has reached the left border             self.x =  0                                                  #拍子不像小球一样需要自动回弹, so set the horizontal component x to 0, i.e. let it stop moving         elif pos[2] >= self.canvas_width:                               #如果右下角水平分量x, i.e. the right side of the beat has reached the right border              self.x = 0                                                  #同样设置为0, Stop movement # Draw a small ball and beat Ball = ball (canvas, ' red ')                                               # Draw a red ball on the canvas with balls paddle = paddle (canvas, ' Blue ')                                           #用Paddle类在画布上画一个蓝色的拍子                                           #主循环, let Tkinter continue to redraw the screen while 1:     ball.draw ()                                                           #调用Ball类的作画函数     paddle.draw ()                                                         #调用Paddle类的作画函数      Tk.update_idletasks ()                                                #updata_idletasks和updata这两个命令     tk.update ()                                                         # Get Tkinter to paint something on the canvas.     time.sleep (0.01)                                                      #延时让动画效果慢一点


The fifth stage of the fun-to-learn Python pinball game-Add a racket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.