"Father and son of the programming journey-with little Carter to learn Python" 18th Chapter __ Programming

Source: Internet
Author: User
Tags class definition

The 18th chapter: a new input-event

18.1 Events
18.2 keyboard Events
18-01

#-*-coding:utf-8-*-#__author__ = ' janvn ' # 2015/08/04 ' Bounce Ball Program, add animated Sprite and Clock.tick () ' Import Pygame,sys pygame.init () Screen=pygame.display.set_mode ([640,480]) background=pygame.
Surface (Screen.get_size ()) Background.fill ([255,255,255]) Clock=pygame.time.clock () #定义一个时间对象 #Ball类, including the Move () method Class Ball (Pygame.sprite.Sprite): def __init__ (self,image_file,speed,location): pygame.sprite.sprite.__init__ ( Self) self.image=pygame.image.load (image_file) self.rect=self.image.get_rect () #得到图像边界的矩阵 Self.rec T.left,self.rect.top=location self.speed=speed def Move (self): if Self.rect.left<=screen.get_rect (). Left or \ self.rect.right>=screen.get_rect (). right:self.speed[0]=-self.speed[0] New Pos=self.rect.move (self.speed) self.rect=newpos my_ball=ball (' beach_ball.png ', [10,0],[20,20]) #横向速度10, vertical speed 0 run Ning=true while Running:for event in Pygame.event.get (): If Event.type==pygamE.quit:running=false Clock.tick (m) #计算时间 (MS), parameter 30 is the maximum frame rate screen.blit (background, (0,0)) My_ball.mo ve () screen.blit (My_ball.image,my_ball.rect) Pygame.display.flip () Pygame.quit ()

18-02 Key Events

#-*-coding:utf-8-*-#__author__ = ' janvn ' # 2015/08/04 ' Bounce Ball program, add animation Sprite and Clock.tick, add key event ' Import Pygame,sys Pygame . Init () Screen=pygame.display.set_mode ([640,480]) background=pygame.
Surface (Screen.get_size ()) Background.fill ([255,255,255]) Clock=pygame.time.clock () #定义一个时间对象 #Ball类, including the Move () method Class Ball (Pygame.sprite.Sprite): def __init__ (self,image_file,speed,location): pygame.sprite.sprite.__init__ ( Self) self.image=pygame.image.load (image_file) self.rect=self.image.get_rect () #得到图像边界的矩阵 Self.rec T.left,self.rect.top=location self.speed=speed def Move (self): if Self.rect.left<=screen.get_rect (). Left or \ self.rect.right>=screen.get_rect (). right:self.speed[0]=-self.speed[0] New Pos=self.rect.move (self.speed) self.rect=newpos my_ball=ball (' beach_ball.png ', [10,0],[20,20]) #横向速度10, vertical speed 0 run Ning=true while Running:for event in Pygame.event.get (): If event.type==Pygame. Quit:running=false elif Event.type==pygame. Keydown:if Event.key==pygame. K_UP: #按下向上键 my_ball.rect.top=my_ball.rect.top-10 #让球上移10个像素 elif event.key==pygame. K_down: #按下向下键 my_ball.rect.top=my_ball.rect.top+10 Clock.tick (ms), parameter 30 is the maximum frame rate screen.bl It (background, (0,0)) My_ball.move () screen.blit (My_ball.image,my_ball.rect) Pygame.display.flip () Pygame.quit (

 )

Add repeat key

#-*-coding:utf-8-*-#__author__ = ' janvn ' # 2015/08/04 ' Bounce Ball program, add animation Sprite and Clock.tick, add key event ' Import Pygame,sys Pygame . Init () Screen=pygame.display.set_mode ([640,480]) background=pygame. Surface (Screen.get_size ()) Background.fill ([255,255,255]) Clock=pygame.time.clock () #定义一个时间对象 #重复按键 delay=100 #开始重复之 How long before waiting interval=50 #按键要以多快的速度重复 pygame.key.set_repeat (delay,interval) #Ball类, including Move () method class Ball (
        Pygame.sprite.Sprite): Def __init__ (self,image_file,speed,location): pygame.sprite.sprite.__init__ (self) Self.image=pygame.image.load (image_file) self.rect=self.image.get_rect () #得到图像边界的矩阵 self.rect.left,self . rect.top=location Self.speed=speed def Move (self): if Self.rect.left<=screen.get_rect (). Left or \ self.rect.right>=screen.get_rect (). right:self.speed[0]=-self.speed[0] Newpos=self.re Ct.move (self.speed) self.rect=newpos my_ball=ball (' beach_ball.png ', [10,0],[20,20]) #横向速度10, longitudinal speed 0 running=true while Running:for event in Pygame.event.get (): If Event.type==pygame. Quit:running=false elif Event.type==pygame. Keydown:if Event.key==pygame. K_UP: #按下向上键 my_ball.rect.top=my_ball.rect.top-10 #让球上移10个像素 elif event.key==pygame. K_down: #按下向下键 my_ball.rect.top=my_ball.rect.top+10 Clock.tick (ms), parameter 30 is the maximum frame rate screen.bl It (background, (0,0)) My_ball.move () screen.blit (My_ball.image,my_ball.rect) Pygame.display.flip () Pygame.quit (

 )

18.3 Mouse Events

#-*-coding:utf-8-*-#__author__ = ' janvn ' # 2015/08/04 ' Bounce Ball program, add animation Sprite and Clock.tick, add keyboard event ' Import Pygame,sys Pygame . Init () Screen=pygame.display.set_mode ([640,480]) background=pygame. Surface (Screen.get_size ()) Background.fill ([255,255,255]) Clock=pygame.time.clock () #定义一个时间对象 #重复按键 delay=100 #开始重复之 How long before waiting interval=50 #按键要以多快的速度重复 pygame.key.set_repeat (delay,interval) Held_down=false #Ball类, including the Move () method class Ball (
        Pygame.sprite.Sprite): Def __init__ (self,image_file,speed,location): pygame.sprite.sprite.__init__ (self) Self.image=pygame.image.load (image_file) self.rect=self.image.get_rect () #得到图像边界的矩阵 self.rect.left,self . rect.top=location Self.speed=speed def Move (self): if Self.rect.left<=screen.get_rect (). Left or \ self.rect.right>=screen.get_rect (). right:self.speed[0]=-self.speed[0] Newpos=self.re Ct.move (self.speed) self.rect=newpos my_ball=ball (' beach_ball.png ', [10,0],[20,20]) #横向速度10, longitudinal speed 0 running=true while Running:for event in Pygame.event.get (): If Event.type==pygame. Quit:running=false elif Event.type==pygame. Mousebuttondown:held_down=true elif Event.type==pygame. Mousebuttonup:held_down=false elif Event.type==pygame. Mousemotion:if held_down:my_ball.rect.center=event.pos #event. Pos Gets the location of the mouse (x,y) clock.ti CK #计算时间 (MS), parameter 30 is the maximum frame rate screen.blit (background, (0,0)) My_ball.move () Screen.blit (My_ball.image,my_ball.rec

 T) Pygame.display.flip () Pygame.quit ()

Timer Events

#-*-coding:utf-8-*-#__author__ = ' janvn ' # 2015/08/04 ' Use a timer event to move the ball up and down ' import Pygame,sys pygame.init () screen =pygame.display.set_mode ([640,480]) background=pygame.
Surface (Screen.get_size ()) Background.fill ([255,255,255]) Clock=pygame.time.clock () #定义一个时间对象 #Ball类, including the Move () method Class Ball (Pygame.sprite.Sprite): def __init__ (self,image_file,speed,location): pygame.sprite.sprite.__init__ ( Self) self.image=pygame.image.load (image_file) self.rect=self.image.get_rect () #得到图像边界的矩阵 Self.rec T.left,self.rect.top=location self.speed=speed def Move (self): if Self.rect.left<=screen.get_rect (). Left or \ self.rect.right>=screen.get_rect (). right:self.speed[0]=-self.speed[0] New Pos=self.rect.move (self.speed) self.rect=newpos my_ball=ball (' beach_ball.png ', [10,0],[20,20]) #横向速度10, longitudinal speed 0 #创建 A timer 1000ms=1 seconds Pygame.time.set_timer (pygame. userevent,1000) Direction=1 Running=true while running:
    For event in Pygame.event.get (): If Event.type==pygame. Quit:running=false elif Event.type==pygame. 
                userevent:my_ball.rect.centery=my_ball.rect.centery+ (30*direction) if my_ball.rect.top<=0 or \   My_ball.rect.bottom>=screen.get_rect (). Bottom:direction=-direction Clock.tick (30)
    #计算时间 (MS), parameter 30 is the maximum frame rate screen.blit (background, (0,0)) My_ball.move () Screen.blit (My_ball.image,my_ball.rect) Pygame.display.flip () Pygame.quit ()

Final Pypong code:

#-*-Coding:utf-8-*-# author:janvn # 2015/08/04 ' The first version of ' Pypong ' import pygame, sys from pygame.locals import * # Class defintion for the ball class Myballclass (pygame.sprite.Sprite): Def __init__ (self, image_file, speed, location) : pygame.sprite.sprite.__init__ (self) self.image = Pygame.image.load (image_file) self.rect = self.
        Image.get_rect () self.rect.left, self.rect.top = Location Self.speed = Speed def move (self): Global Score,score_font,score_surf Self.rect = Self.rect.move (self.speed) # Bounce off the sides of the WI Ndow if Self.rect.left < 0 or self.rect.right > screen.get_width (): self.speed[0] =-self.speed[ 0] # Bounce off the top of the window if Self.rect.top <= 0:self.speed[1] =-self.speed[ 1] score=score+1 Score_surf=score_font.render (str (score), 1, (0,0,0)) # Class definition for the PA Ddle class Mypaddleclass(pygame.sprite.Sprite): Def __init__ (self, location): pygame.sprite.sprite.__init__ (self) IMAGE_SURFAC
        E = Pygame.surface.Surface ([m]) Image_surface.fill ([0,0,0]) Self.image = Image_surface.convert () Self.rect = Self.image.get_rect () self.rect.left, self.rect.top = Location pygame.init () screen = Pygame.dis Play.set_mode ([640,480]) Clock = pygame.time.Clock () Myball = Myballclass (' wackyball.bmp ', [10,5], [M]) #  Stance of the ball Ballgroup = Pygame.sprite.Group (myball) # Add the ball to a sprite Group paddle = Mypaddleclass ([270, ] # Make a instance of the paddle score=0 Score_font=pygame.font.font (none,50) score_surf=score_font.render (str ( Score), 1, (0,0,0)) score_pos=[10,10] lives=3 done=false running = True #主程序 while Running:clock.tick () screen.f Ill ([255, 255, 255]) Screen.blit (score_surf,score_pos) for I in Range (lives): Width=screen.get_rect (). wid Th Screen.blit (MYBALL.IMAGE,[WIDTH-40*I,20]) for event in Pygame.event.get (): if Event.type = = Quit:running = Fa LSE Elif Event.type = = Pygame. Mousemotion: # Move the paddle if the Paddle.rect.centerx = event.pos[0] # mouse moves if Pygam                      E.sprite.spritecollide (paddle, Ballgroup, False): # Bounce the ball if it myball.speed[1] =-myball.speed[1]
        # hits the paddle myball.move () if not done:screen.blit (Myball.image, Myball.rect)
            Screen.blit (Paddle.image, Paddle.rect) screen.blit (score_surf,score_pos) for I in Range (lives):

    Width=screen.get_width () Screen.blit (myball.image,[width-40*i,20]) Pygame.display.flip () If Myball.rect.top>=screen.get_rect (). bottom:lives=lives-1 if lives = = 0:final_text1 = " Game over "final_text2 =" Your Final score is: "+ str (score) Ft1_font = Pygame.fonT.font (None) Ft1_surf = Ft1_font.render (Final_text1, 1, (0, 0, 0)) Ft2_font = Pygame.font.Font (None) Ft2_surf = Ft2_font.render (final_text2, 1, (0, 0, 0)) Screen.blit (Ft1_surf, [screen.get _width ()/2-ft1_surf.get_width ()/2 (M)) Screen.blit (Ft2_surf, [Screen.get_width ()
        /2-[Ft2_surf.get_width ()/2]) pygame.display.flip () done = True else: #wait 2 seconds, then start the next ball Pygame.time.delay (Watts) myBall.rect.topleft
 = [A] Pygame.quit ()

Related Article

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.