您的位置:68399皇家赌场 > 集群主机 > Python:pygame游戏编制程序之旅七(pygame基础知识讲

Python:pygame游戏编制程序之旅七(pygame基础知识讲

发布时间:2019-08-31 11:37编辑:集群主机浏览(189)

    动用pygame模块编写贪吃蛇的实例疏解,pygame实例疏解

    python ### 刚学了python不久,发现了三个交相辉映的库pygame

    行使pygame模块 利用面向对象的思维编写贪吃蛇,首要使用pygame.sprite:

    游玩主类

    import pygame,sys
    from snake_sprite import Game_sprite,Snake,Food
    SCREEN_RECT=pygame.Rect(0,0,828,600)
    
    IMG_URL="./image/bg.jpg"
    #主类
    class Snakegame(object):
     def __init__(self):
      self.screen=pygame.display.set_mode(SCREEN_RECT.size)
      self.clock=pygame.time.Clock()
      self.__create_sprites()
    
     def __create_sprites(self):
      bg=Game_sprite(IMG_URL)
      self.snake=Snake()
      for pos in self.snake.snake_point:
       self.screen.blit(self.snake.image,pos)
      food=Food()
      self.bg_group=pygame.sprite.Group(bg)
      self.snake_group=pygame.sprite.Group(self.snake)
      self.food_group = pygame.sprite.Group(food)
     def start_game(self):
      while True:
       #1.时钟设置
       self.clock.tick(30)
       #2.事件监听
       self.__event_handler()
       #3.碰撞检测
       self.__check_collide()
       #4.精灵更新
       self.__update_sprites()
       #5.屏幕更新
       pygame.display.update()
     def __event_handler(self):
      for event in pygame.event.get():
       if event.type==pygame.QUIT:
        Snakegame.__game_over()
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT and 
         self.snake.direction !='L':
        self.snake.speedy = 0
        self.snake.speedx = 1
        self.snake.direction = 'R'
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT and 
         self.snake.direction !='R':
        self.snake.speedy = 0
        self.snake.speedx = -1
        self.snake.direction = 'L'
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP and 
         self.snake.direction !='D':
        self.snake.speedx = 0
        self.snake.speedy = -1
        self.snake.direction = 'U'
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and 
         self.snake.direction !='U':
        self.snake.speedx=0
        self.snake.speedy=1
        self.snake.direction='D'
     def __check_collide(self):
      pass
     def __update_sprites(self):
      self.bg_group.update()
      self.bg_group.draw(self.screen)
      self.snake_group.update()
      self.snake_group.draw(self.screen)
      self.food_group.update()
      self.food_group.draw(self.screen)
     @staticmethod
     def __game_over():
      pygame.quit()
      exit()
    
    #游戏启动
    if __name__ == '__main__':
     snake=Snakegame()
     snake.start_game()
    

    工具类

    import pygame
    import random
    SNAKE_IMG="./image/snake.png"
    FOOD_IMG="./image/food.jpg"
    class Game_sprite(pygame.sprite.Sprite):
     def __init__(self,img_name,speedx=1,speedy=0):
      #调用父类的初始化方法
      super(Game_sprite, self).__init__()
      #属性
      self.image=pygame.image.load(img_name)
      self.rect=self.image.get_rect()
      self.speedx=speedx
      self.speedy=speedy
     def update(self):
      pass
    #蛇实物
    class Snake(Game_sprite):
     def __init__(self,direction='R',snakelist=[[40,40],[80,40]]):
      self.direction=direction
      self.snake_point=snakelist
      super().__init__(SNAKE_IMG)
      self.rect.x=self.snake_point[1][0]
      self.rect.y=self.snake_point[1][1]
     def update(self):
      self.rect.x  = self.speedx
      self.rect.y  = self.speedy
    class Food(Game_sprite):
     def __init__(self):
      super(Food, self).__init__(FOOD_IMG)
      self.rect.x = random.randint(50, 828)
      self.rect.y = random.randint(38, 600)
     def update(self):
      pass
    

    关于这一次demo

    本人发掘自身并不曾弄懂pygame的切实可行画面更新机制,以及Smart的调控,对于贪吃蛇尾部及人身的画面更新并未做出来,还应该有对肉体和头的数据结构如何构建并非很明白。究竟第一次,希望有大佬看到那篇博客能够教导下。

    沾满函数式编程的代码

    import pygame
    import time
    import random
    x = pygame.init()
    white = (255,255,255)
    black = (0,0,0)
    red = (255,0,0)
    green = (0,155,0)
    display_width = 800
    display_height = 600
    gameDisplay = pygame.display.set_mode((display_width,display_height))
    pygame.display.set_caption('Slither')
    gameDisplay.fill(white)
    pygame.display.update()
    block_size = 20
    applethickness = 30
    FPS = 10
    icon = pygame.image.load('appleimage.jpg')
    pygame.display.set_icon(icon)
    img = pygame.image.load('snakeimage.jpg')
    appleimage = pygame.image.load('appleimage.jpg')
    clock = pygame.time.Clock()
    smallfont = pygame.font.SysFont(None,30)
    midfont = pygame.font.SysFont(None,50)
    largefont = pygame.font.SysFont("comicsansms",80)
    direction = "right"
    def pause():
     paused = True
     message_to_screen("暂停",black,-100,"large")
     message_to_screen("空格暂停Q退出",black, 30)
     pygame.display.update()
     while paused:
      for event in pygame.event.get():
       if event.type == pygame.QUIT:
        pygame.quit()
        quit()
       if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
         paused = False
        elif event.key == pygame.K_q:
         pygame.quit()
         quit()
      #gameDisplay.fill(white)
     clock.tick(5)
    
    def score(score):
     text1 = smallfont.render("Score : "   str(score), True, black)
     gameDisplay.blit(text1,(0,0))
    def randApplegen():
     randAppleX = round(random.randrange(0,display_width-applethickness))#/10.0)*10.0
     randAppleY = round(random.randrange(0,display_height-applethickness))#/10.0)*10.0
     return randAppleX, randAppleY
    
    def intro():
     intro = True
     message_to_screen("按c开始游戏",red,150)
     pygame.display.update()
     while intro:
      for event in pygame.event.get():
       if event.type == pygame.QUIT:
        pygame.quit()
        quit()
       if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_c:
         intro = False
        if event.key == pygame.K_q:
         pygame.quit()
         quit()
      clock.tick(15)
    def snake(snakelist):
     for xny in snakelist[:-1]:
      pygame.draw.rect(gameDisplay,green,[xny[0],xny[1],block_size,block_size])
     if(direction == "right"):
      head = pygame.transform.rotate(img,270)
     elif(direction == "left"):
      head = pygame.transform.rotate(img,90)
     elif(direction == "up"):
      head = img
     elif(direction == "down"):
      head = pygame.transform.rotate(img,180)
     gameDisplay.blit(head,(snakelist[-1][0],snakelist[-1][1]))
    def text_objects(text,color,size):
     if(size == "small"):
      textsurface = smallfont.render(text,True,color)
     elif(size == "middle"):
      textsurface = midfont.render(text,True,color)
     elif(size == "large"):
      textsurface = largefont.render(text,True,color)
     return textsurface, textsurface.get_rect()
    def message_to_screen(msg,color,y_displace=0,size="small"):
     textsurf, textsurf_rect = text_objects(msg,color,size)
     textsurf_rect.center = (display_width/2), (display_height/2)   y_displace
     gameDisplay.blit(textsurf,textsurf_rect)
    
    def gameLoop():
     global direction
     direction = "right"
     gameExit = False
     gameOver = False
     lead_x = display_width/2
     lead_y = display_height/2
     lead_x_change = 10
     lead_y_change = 0
     randAppleX, randAppleY = randApplegen()
     snakelist = []
     snakelength = 1
     while not gameExit:
      if gameOver == True:
       message_to_screen("Game Over",red,-50,"large")
       message_to_screen("Press C to play again or Q to quit the game",black,50,"small")
       pygame.display.update()
      while gameOver == True:
       #gameDisplay.fill(white)
       for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_q:
          gameExit = True
          gameOver = False
         if event.key == pygame.K_c:
          gameLoop()
          pygame.quit()
          quit()
        if event.type == pygame.QUIT:
         gameExit = True 
         gameOver = False
         # pygame.quit()
         # quit()
      for event in pygame.event.get():
       if event.type == pygame.QUIT:
        gameExit = True 
       if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT and direction != "right":
         direction = "left"
         lead_x_change = -block_size
         lead_y_change = 0
        elif event.key == pygame.K_RIGHT and direction != "left":
         direction = "right"
         lead_x_change = block_size
         lead_y_change = 0
        elif event.key == pygame.K_UP and direction != "down":
         direction = "up"
         lead_y_change = -block_size
         lead_x_change = 0
        elif event.key == pygame.K_DOWN and direction != "up":
         direction = "down"
         lead_y_change = block_size
         lead_x_change = 0
        elif event.key == pygame.K_SPACE:
         pause()
      if lead_x   block_size/2 >= display_width or lead_x < 0 or lead_y   block_size/2 >= display_height or lead_y < 0:
       gameOver = True
      lead_x  = lead_x_change
      lead_y  = lead_y_change
      gameDisplay.fill(white)
      gameDisplay.blit(appleimage,(randAppleX,randAppleY))
      #pygame.draw.rect(gameDisplay,red,[350,350,100,10])
      # gameDisplay.fill(red, rect=[200,200,50,50])  #good method
      snakehead = []
      snakehead.append(lead_x)
      snakehead.append(lead_y)
      snakelist.append(snakehead)
      if len(snakelist) > snakelength:
       del snakelist[0]
      for each in snakelist[:-1]:
       if each == snakehead:
        gameOver = True
      snake(snakelist)
      score(snakelength-1)
      pygame.display.update()
      if lead_x >= randAppleX and lead_x <= randAppleX   applethickness or lead_x   block_size >= randAppleX and lead_x   block_size <= randAppleX   applethickness:
       if lead_y >= randAppleY and lead_y <= randAppleY   applethickness or lead_y   block_size >= randAppleY and lead_y   block_size <= randAppleY   applethickness:
        randAppleX, randAppleY = randApplegen()
        snakelength  = 1;    
      clock.tick(FPS)
    intro()
    gameLoop()
    
    pygame.quit()
    quit()
    

    以上这篇使用pygame模块编写贪吃蛇的实例批注正是笔者分享给大家的全部内容了,希望能给大家多少个参阅,也指望我们多多协助帮客之家。

    python ### 刚学了python不久,开掘了一个有意思的库pygame 使用pygame模块 利用面向对象的思...

    自己开掘本身并不曾弄懂pygame的具体画面更新机制,以及Smart的主宰,对于贪吃蛇尾部及人身的画面更新并未做出来,还应该有对身体和头的数据结构如何营造并非很理解。终究第一遍,希望有大佬看到那篇博客能够引导下。

    请记住需求传递三个包罗五个整形的元组类型变量给set_mode()函数,并不是多少个独立的数字,正确的调用方法是:pygame.display.set_mode((400, 300))。像pygame.display.set_mode(400,300)将生出二个如TypeError: argument 1 must be 2-item sequence, not int的不当。

    图片 1

    您可能感兴趣的篇章:

    • 50行代码达成贪吃蛇(具体思路及代码)
    • Python编制程序pygame模块达成移动的手推车示例代码
    • Python基于pygame模块播放DVD的主意身体力行
    • python中pygame模块用法实例
    • 依附python中pygame模块的Linux下安装进度(详解)
    • python使用PyGame模块播放音响的法子

     是的,你刚刚制作了世道上最无聊的多少个玩耍,它独有在窗口的标题上出示了“Hello World”,但创立窗口是图形分界面游戏的第一步,当您点击窗口右上角的关闭开关,程序将会脱离,何况窗口未有。

    总结

    import pygame
    import time
    import random
    x = pygame.init()
    white = (255,255,255)
    black = (0,0,0)
    red = (255,0,0)
    green = (0,155,0)
    display_width = 800
    display_height = 600
    gameDisplay = pygame.display.set_mode((display_width,display_height))
    pygame.display.set_caption('Slither')
    gameDisplay.fill(white)
    pygame.display.update()
    block_size = 20
    applethickness = 30
    FPS = 10
    icon = pygame.image.load('appleimage.jpg')
    pygame.display.set_icon(icon)
    img = pygame.image.load('snakeimage.jpg')
    appleimage = pygame.image.load('appleimage.jpg')
    clock = pygame.time.Clock()
    smallfont = pygame.font.SysFont(None,30)
    midfont = pygame.font.SysFont(None,50)
    largefont = pygame.font.SysFont("comicsansms",80)
    direction = "right"
    def pause():
     paused = True
     message_to_screen("暂停",black,-100,"large")
     message_to_screen("空格暂停Q退出",black, 30)
     pygame.display.update()
     while paused:
      for event in pygame.event.get():
       if event.type == pygame.QUIT:
        pygame.quit()
        quit()
       if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
         paused = False
        elif event.key == pygame.K_q:
         pygame.quit()
         quit()
      #gameDisplay.fill(white)
     clock.tick(5)
    
    def score(score):
     text1 = smallfont.render("Score : "   str(score), True, black)
     gameDisplay.blit(text1,(0,0))
    def randApplegen():
     randAppleX = round(random.randrange(0,display_width-applethickness))#/10.0)*10.0
     randAppleY = round(random.randrange(0,display_height-applethickness))#/10.0)*10.0
     return randAppleX, randAppleY
    
    def intro():
     intro = True
     message_to_screen("按c开始游戏",red,150)
     pygame.display.update()
     while intro:
      for event in pygame.event.get():
       if event.type == pygame.QUIT:
        pygame.quit()
        quit()
       if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_c:
         intro = False
        if event.key == pygame.K_q:
         pygame.quit()
         quit()
      clock.tick(15)
    def snake(snakelist):
     for xny in snakelist[:-1]:
      pygame.draw.rect(gameDisplay,green,[xny[0],xny[1],block_size,block_size])
     if(direction == "right"):
      head = pygame.transform.rotate(img,270)
     elif(direction == "left"):
      head = pygame.transform.rotate(img,90)
     elif(direction == "up"):
      head = img
     elif(direction == "down"):
      head = pygame.transform.rotate(img,180)
     gameDisplay.blit(head,(snakelist[-1][0],snakelist[-1][1]))
    def text_objects(text,color,size):
     if(size == "small"):
      textsurface = smallfont.render(text,True,color)
     elif(size == "middle"):
      textsurface = midfont.render(text,True,color)
     elif(size == "large"):
      textsurface = largefont.render(text,True,color)
     return textsurface, textsurface.get_rect()
    def message_to_screen(msg,color,y_displace=0,size="small"):
     textsurf, textsurf_rect = text_objects(msg,color,size)
     textsurf_rect.center = (display_width/2), (display_height/2)   y_displace
     gameDisplay.blit(textsurf,textsurf_rect)
    
    def gameLoop():
     global direction
     direction = "right"
     gameExit = False
     gameOver = False
     lead_x = display_width/2
     lead_y = display_height/2
     lead_x_change = 10
     lead_y_change = 0
     randAppleX, randAppleY = randApplegen()
     snakelist = []
     snakelength = 1
     while not gameExit:
      if gameOver == True:
       message_to_screen("Game Over",red,-50,"large")
       message_to_screen("Press C to play again or Q to quit the game",black,50,"small")
       pygame.display.update()
      while gameOver == True:
       #gameDisplay.fill(white)
       for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_q:
          gameExit = True
          gameOver = False
         if event.key == pygame.K_c:
          gameLoop()
          pygame.quit()
          quit()
        if event.type == pygame.QUIT:
         gameExit = True 
         gameOver = False
         # pygame.quit()
         # quit()
      for event in pygame.event.get():
       if event.type == pygame.QUIT:
        gameExit = True 
       if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT and direction != "right":
         direction = "left"
         lead_x_change = -block_size
         lead_y_change = 0
        elif event.key == pygame.K_RIGHT and direction != "left":
         direction = "right"
         lead_x_change = block_size
         lead_y_change = 0
        elif event.key == pygame.K_UP and direction != "down":
         direction = "up"
         lead_y_change = -block_size
         lead_x_change = 0
        elif event.key == pygame.K_DOWN and direction != "up":
         direction = "down"
         lead_y_change = block_size
         lead_x_change = 0
        elif event.key == pygame.K_SPACE:
         pause()
      if lead_x   block_size/2 >= display_width or lead_x < 0 or lead_y   block_size/2 >= display_height or lead_y < 0:
       gameOver = True
      lead_x  = lead_x_change
      lead_y  = lead_y_change
      gameDisplay.fill(white)
      gameDisplay.blit(appleimage,(randAppleX,randAppleY))
      #pygame.draw.rect(gameDisplay,red,[350,350,100,10])
      # gameDisplay.fill(red, rect=[200,200,50,50])  #good method
      snakehead = []
      snakehead.append(lead_x)
      snakehead.append(lead_y)
      snakelist.append(snakehead)
      if len(snakelist) > snakelength:
       del snakelist[0]
      for each in snakelist[:-1]:
       if each == snakehead:
        gameOver = True
      snake(snakelist)
      score(snakelength-1)
      pygame.display.update()
      if lead_x >= randAppleX and lead_x <= randAppleX   applethickness or lead_x   block_size >= randAppleX and lead_x   block_size <= randAppleX   applethickness:
       if lead_y >= randAppleY and lead_y <= randAppleY   applethickness or lead_y   block_size >= randAppleY and lead_y   block_size <= randAppleY   applethickness:
        randAppleX, randAppleY = randApplegen()
        snakelength  = 1;    
      clock.tick(FPS)
    intro()
    gameLoop()
    
    pygame.quit()
    quit()
    

    本书中的全体游戏均具备while True循环,并申明“main game loop”字样的笺注。二个嬉戏循环首要做以下三件业务:

    你恐怕感兴趣的篇章:

    • python pygame轻易画板达成代码实例
    • 据悉python中pygame模块的Linux下安装进程(详解)
    • python Pygame的切实选用解说
    • Python基于pygame模块播放VCD的章程以身作则
    • 详解Python pygame安装过程笔记
    • 设置Python和pygame及相应的处境变量配置(图像和文字化教育程)
    • Python使用pygame模块编写俄罗丝四方游戏的代码实例
    • Python编制程序pygame模块完结活动的汽车示例代码
    import pygame
    import random
    SNAKE_IMG="./image/snake.png"
    FOOD_IMG="./image/food.jpg"
    class Game_sprite(pygame.sprite.Sprite):
     def __init__(self,img_name,speedx=1,speedy=0):
      #调用父类的初始化方法
      super(Game_sprite, self).__init__()
      #属性
      self.image=pygame.image.load(img_name)
      self.rect=self.image.get_rect()
      self.speedx=speedx
      self.speedy=speedy
     def update(self):
      pass
    #蛇实物
    class Snake(Game_sprite):
     def __init__(self,direction='R',snakelist=[[40,40],[80,40]]):
      self.direction=direction
      self.snake_point=snakelist
      super().__init__(SNAKE_IMG)
      self.rect.x=self.snake_point[1][0]
      self.rect.y=self.snake_point[1][1]
     def update(self):
      self.rect.x  = self.speedx
      self.rect.y  = self.speedy
    class Food(Game_sprite):
     def __init__(self):
      super(Food, self).__init__(FOOD_IMG)
      self.rect.x = random.randint(50, 828)
      self.rect.y = random.randint(38, 600)
     def update(self):
      pass
    

    我们一贯不利用if语句来管理任何的风云,比方鼠标点击、开关等,所以这一个事件固然会产生,但顺序不做管理。

    本文实例主倘诺在示范框里达成三个移动的矩形实例代码,完整代码如下:

    import pygame,sys
    from snake_sprite import Game_sprite,Snake,Food
    SCREEN_RECT=pygame.Rect(0,0,828,600)
    
    IMG_URL="./image/bg.jpg"
    #主类
    class Snakegame(object):
     def __init__(self):
      self.screen=pygame.display.set_mode(SCREEN_RECT.size)
      self.clock=pygame.time.Clock()
      self.__create_sprites()
    
     def __create_sprites(self):
      bg=Game_sprite(IMG_URL)
      self.snake=Snake()
      for pos in self.snake.snake_point:
       self.screen.blit(self.snake.image,pos)
      food=Food()
      self.bg_group=pygame.sprite.Group(bg)
      self.snake_group=pygame.sprite.Group(self.snake)
      self.food_group = pygame.sprite.Group(food)
     def start_game(self):
      while True:
       #1.时钟设置
       self.clock.tick(30)
       #2.事件监听
       self.__event_handler()
       #3.碰撞检测
       self.__check_collide()
       #4.精灵更新
       self.__update_sprites()
       #5.屏幕更新
       pygame.display.update()
     def __event_handler(self):
      for event in pygame.event.get():
       if event.type==pygame.QUIT:
        Snakegame.__game_over()
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT and 
         self.snake.direction !='L':
        self.snake.speedy = 0
        self.snake.speedx = 1
        self.snake.direction = 'R'
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT and 
         self.snake.direction !='R':
        self.snake.speedy = 0
        self.snake.speedx = -1
        self.snake.direction = 'L'
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP and 
         self.snake.direction !='D':
        self.snake.speedx = 0
        self.snake.speedy = -1
        self.snake.direction = 'U'
       elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and 
         self.snake.direction !='U':
        self.snake.speedx=0
        self.snake.speedy=1
        self.snake.direction='D'
     def __check_collide(self):
      pass
     def __update_sprites(self):
      self.bg_group.update()
      self.bg_group.draw(self.screen)
      self.snake_group.update()
      self.snake_group.draw(self.screen)
      self.food_group.update()
      self.food_group.draw(self.screen)
     @staticmethod
     def __game_over():
      pygame.quit()
      exit()
    
    #游戏启动
    if __name__ == '__main__':
     snake=Snakegame()
     snake.start_game()
    

     

    示范如下:

    python ### 刚学了python不久,开采了贰个有趣的库pygame

    此行使用import 语句导入程序中要运用的pygame和sys模块,pygame模块提供了图片、声音等函数。

    #moving rectangle project
    
    import pygame
    
    from pygame.locals import *
    
    pygame.init()
    
    screen = pygame.display.set_mode((600,500))
    
    pygame.display.set_caption("Drawing Rectangles")
    
    pos_x = 300
    
    pos_y = 250
    
    vel_x = 2
    
    vel_y = 1
    
    while True:
    
      for event in pygame.event.get():
    
        if event.type in (QUIT,KEYDOWN):
    
          pygame.quit()
    
      screen.fill((0,0,200))
    
    
    
      # move the rectangle
    
      pos_x  = vel_x
    
      pos_y  = vel_y
    
      # keep rectangle on the screen
    
      if pos_x > 500 or pos_x < 0:
    
        vel_x = -vel_x
    
      if pos_y > 400 or pos_y < 0:
    
        vel_y = -vel_y
    
      # draw the rectangle
    
      color = 255,255,0
    
      width = 0 #solid fill
    
      pos = pos_x,pos_y,100,100
    
      pygame.draw.rect(screen,color,pos,width)
    
      pygame.display.update()   
    

    游戏主类

    3.        在显示屏上制图

    以上正是本文关于Python通过Pygame绘制移动的矩形实例代码的全部内容,希望对大家享有补助。感兴趣的情侣可以继续参照本站其余相关专项论题,如有不足之处,应接留言建议。感激朋友们对本站的支撑!

    选用pygame模块 利用面向对象的思维编写贪吃蛇,重要行使pygame.sprite:

    [python]
    while True: # main game loop  
        for event in pygame.event.get(): 
    while True: # main game loop
     for event in pygame.event.get():

    Pygame是三个多用来游戏开辟的模块。

    沾满函数式编制程序的代码

    第12行调用pygame.display.update()函数来绘制由pygame.display.set_mode()函数再次回到的Surface对象,假设Surface对象未有成形,每回调用pygame.dispaly.update()时一个白手的图像将会在荧屏上绘制。

    以上这篇使用pygame模块编写贪吃蛇的实例批注正是小编分享给大家的全部内容了,希望能给我们三个参照他事他说加以考察,也希望大家多多支持脚本之家。

    接纳Python自带的函数print()和input()来操作文本,你的程序可以将文件呈现在显示屏上并得以让顾客从键盘输入文本,这类的前后相继有所命令行分界面(command line interface, 简称CLI),但它不能显得图像、颜色、可能采纳鼠标,此类型程序仅通过input()函数接收键盘输入,并当顾客按下回车键之后才对输入进行响应,所以它不适合实时CAG游戏的开拓。

    工具类

    [python]
    import pygame, sys 
    from pygame.locals import *  
     
    pygame.init() 
    DISPLAYSURF = pygame.display.set_mode((400, 300)) 
    pygame.display.set_caption('Hello World!') 
    while True: # main game loop  
        for event in pygame.event.get(): 
            if event.type == QUIT: 
                pygame.quit() 
                sys.exit() 
        pygame.display.update() 
    import pygame, sys
    from pygame.locals import *

    关于此次demo

    瞩目,当您导入了pygame模块,你将私下认可地导入了pygame的全数子模块,举个例子pygame.images,pygame.mixer.music等,所以并不供给再导次导入它们。

    GUI和CLI

    本章将陈诉Pygame提供的...

    我们导入pygame.locals的原由是因为它蕴涵了多数Pygame提供的常量。from … import *这种格式使大家不用在常量名称前增多pyame.locals前缀。

    运营程序,出现如下三个空窗口:

     

     

    本文由68399皇家赌场发布于集群主机,转载请注明出处:Python:pygame游戏编制程序之旅七(pygame基础知识讲

    关键词: 68399皇家赌场