10多个Pygame样本例子程序_More than 10 template pygame programe

"""the simplest pygame example program,最简pygame示例,生成红色的图像"""

import pygame

image = pygame.Surface((100,100)) # 实例化一个图像

image.fill((255,0,0))             # 给图像所有像素填充为红色

pygame.image.save(image,"red.png")# 保存此图像
"""the simplest pygame image process  program,add noise,给图像增加燥音
   本程序会在图像上印10X10的蓝色像素点,然后在一个窗口中显示出来。
"""

import pygame

width,height = 100,100

image = pygame.Surface((width,height)) # 实例化一个图像

image.fill((255,0,255))                # 给图像所有像素填充为品红色

for x in range(width):
    for y in range(height):
        if x % 10 ==0 and y % 10 == 0:   # or x == y ,etc
            image.set_at((x,y),(0,0,255))# 重写像素点值
       
screen = pygame.display.set_mode((width,height))
screen.blit(image,(0,0))
pygame.display.update()
 
"""the simplest pygame font render  program,word2image!
   本程序会在青色的背景上显示红色的Python Pygame Font这几个字。
   最后会把这个图像保存为文件。
"""

import pygame
 
pygame.init()
font_filename = pygame.font.get_default_font()  # 得到缺省的字体文件名
myfont = pygame.font.Font(font_filename,120)    # 新建字体对象
myword = myfont.render("Python Pygame Font",True,(255,0,0))   # 渲染一个字体图层
width,height =myword.get_size()                        # 得到字体面的宽度和高度
 
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
screen.fill((0,255,255))                        # 填充screen为青色 
screen.blit(myword,(0,0))                       # 把myword渲染到screen上
pygame.image.save(screen,"lixingqiu.png")       # 保存图像
pygame.display.update()                         # 更新显示
 
"""the simplest pygame loop template code,basic game loop by lixingqiu
   pygame最基本的游戏循环样本代码。
   
"""

import pygame
from pygame.locals import *           # 导入常量

width,height = 480,360

pygame.init() 
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame最基本的游戏循环样本代码")

running = True
clock = pygame.time.Clock()          # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == QUIT:running = False

    # 这里是游戏逻辑,如碰撞检测会改变个各图像的坐标


    # 渲染各个图像,一般首先渲染screen,它做为背景
    screen.fill((0,0,0))

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""the simple pygame program code,red square animation,move a object
   pygame实现最简单的图像缓慢移动代码。原理是不断填充背景,不断重画矩形。
   
"""

import pygame
from pygame.locals import *           # 导入常量

width,height = 480,360

pygame.init() 
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame实现最简单的图像移动代码")

redsquare = pygame.Surface((50,50)) # 新建方块图
redsquare.fill((255,0,0))           # 填充为红色
x = 0

running = True
clock = pygame.time.Clock()         # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == QUIT:running = False

    # 这里是游戏逻辑,如碰撞检测会改变个各图像的坐标
    x = x + 1

    # 渲染各个图像,一般首先渲染screen,它做为背景
    screen.fill((0,0,0))
    screen.blit(redsquare,(x,0))
               

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/10份之一秒过后再次循环
    clock.tick(10)                   # set fps 10
 
pygame.quit()
"""the simple pygame program code,red square animation,bounce on edge.
   pygame实现最简单的图像移动代码。原理是不断填充背景,不断重画矩形。它碰到边缘会反弹。
   
"""
import random
import pygame
from pygame.locals import *           # 导入常量

width,height = 480,360

pygame.init() 
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame演示碰到边缘就反弹原理样本代码by李兴球")

redsquare = pygame.Surface((50,50)) # 新建方块图
redsquare.fill((255,0,0))           # 填充为红色
x = width//2
y = height//2
dx = random.randint(-5,5)           # 水平单位位移
dy = random.randint(-5,5)           # 垂直单位位移

running = True
clock = pygame.time.Clock()         # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == QUIT:running = False

    # 这里是游戏逻辑,如碰撞检测会改变个各图像的坐标
    if x <= 0 or x + 50 >= width: dx = -dx
    if y <= 0 or y + 50 >= height: dy = -dy
    
    x = x + dx
    y = y + dy

    # 渲染各个图像,一般首先渲染screen,它做为背景    
    screen.fill((0,0,0))
    screen.blit(redsquare,(x,y))               

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""the simple pygame program code,a square animation,bounce on edge.use rect object.
   pygame实现最简单的图像移动代码。原理是不断填充背景,不断重画矩形。它碰到边缘会反弹。
   使用矩形对象来代表方块的坐标与宽高,使用move_ip来移动矩形对象的位置。
   
"""
import random
import pygame
from pygame.locals import *           # 导入常量

width,height = 480,360

pygame.init() 
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame演示矩形对象by李兴球")

w,h = random.randint(25,100),random.randint(25,100)
square = pygame.Surface((w,h))     # 新建方块图
square.fill((0,255,255))           # 填充为青色
rect = square.get_rect()           # 获取矩形对象
rect.centerx = width//2            # 矩形对象中心点x坐标
rect.centery = height//2           # 矩形对象中心点y坐标
dx = random.randint(-5,5)          # 水平单位位移
dy = random.randint(-5,5)          # 垂直单位位移

running = True
clock = pygame.time.Clock()        # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == QUIT:running = False

    # 这里是游戏逻辑,如碰撞检测会改变个各图像的坐标
    if rect.left <= 0 or rect.right >= width: dx = -dx
    if rect.top <= 0 or rect.bottom >= height: dy = -dy
    
    rect.move_ip(dx,dy)            # 移动矩形对象

    # 渲染各个图像,一般首先渲染screen,它做为背景    
    screen.fill((0,0,0))
    screen.blit(square,rect)               

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""demo class use method。the simple pygame program code,a square animation,bounce on edge.use rect object and class,by lixingqiu
   pygame实现新建方块类来实例化图。本程序会生成不同颜色与大小的长方形,它们会移动,注意while循环的条件判断表达式。
   使用的是pygame.event.poll()来从事件队列中取一个事件,如果它的类型为QUIT,则退出while循环。
   
"""
import random
import pygame
from pygame.locals import *           # 导入常量

class Square:
    """方块类"""
    def __init__(self):
        """初始化"""
        w,h = random.randint(25,100),random.randint(25,100) # temp vars
        self.image = pygame.Surface((w,h))       # 方块要渲染的图像
        r,g,b = random.randint(0,255),random.randint(0,255),random.randint(0,255)
        self.image.fill((r,g,b))               #  填充颜色
        self.rect = self.image.get_rect()      # 方块的矩形对象
        self.rect.centerx = width//2           # x坐标移到屏幕中央
        self.rect.centery = height//2          # y坐标移到屏幕中央
        self.dx = random.randint(-5,5)         # 水平单位位移
        self.dy = random.randint(-5,5)         # 垂直单位位移
        
    def move(self):
        """移动矩形"""
        self.rect.move_ip(self.dx,self.dy)
        self.bounce_on_edge()

    def bounce_on_edge(self):
        """碰到边缘就反弹"""
        if self.rect.left <= 0 or self.rect.right >= width: self.dx = -self.dx
        if self.rect.top <= 0 or self.rect.bottom >= height: self.dy = -self.dy
        

width,height = 480,360                         # define screen'width and height

pygame.init()                                  # pygame初始化
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame演示类生成多个颜色方块by李兴球")
 
squares = [ Square() for i in range(10)]
 
clock = pygame.time.Clock()                    # 时钟对象

while pygame.event.poll().type != QUIT:        # 当事件类型不为退出时循环,否则退出     

    [ square.move()  for square in squares ]   # 移动每个方块
    
    # 渲染各个图像,一般首先渲染screen,它做为背景    
    screen.fill((0,0,0))
    [ screen.blit(square.image,square.rect)  for square in squares ]             

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""demo ontimer event use method。(Chinese english)
本程序演示pygame的定时器事件,在游戏循环中,会每隔1秒生成一个方块,方块进入屏幕后会自动从自己所在列表中移除。
   
"""
import random
import pygame
from pygame.locals import *           # 导入常量

class Square:
    """方块类"""
    def __init__(self,group):
        """初始化"""
        w,h = random.randint(25,100),random.randint(25,100) # temp vars
        self.image = pygame.Surface((w,h))       # 方块要渲染的图像
        r,g,b = random.randint(0,255),random.randint(0,255),random.randint(0,255)
        self.image.fill((r,g,b))               #  填充颜色
        self.rect = self.image.get_rect()      # 方块的矩形对象
        self.rect.centerx = width//2           # x坐标移到屏幕中央
        self.rect.centery = height//2          # y坐标移到屏幕中央
        self.dx = random.randint(-5,5)         # 水平单位位移
        self.dy = random.randint(-5,5)         # 垂直单位位移
        self.group = group
        self.group.append(self)                # 把自己添加到组中
        
    def move(self):
        """移动矩形"""
        self.rect.move_ip(self.dx,self.dy)
        self.vanish_on_edge()

    def vanish_on_edge(self):
        """到边缘消失"""
        if self.rect.right <= 0 or self.rect.left >= width or  \
           self.rect.bottom <= 0 or self.rect.top >= height: self.group.remove(self)
        

width,height = 480,360                         # define screen'width and height

pygame.init()                                  # pygame初始化
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame演示定时器事件by李兴球")
 
squares = [ ]

# 以下设置定时器事件
spawn_event  = USEREVENT + 1
pygame.time.set_timer(spawn_event,1000)

running = True
clock = pygame.time.Clock()                    # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == spawn_event: Square(squares)
        if event.type == QUIT: running = False            

    [ square.move()  for square in squares ]   # 移动每个方块
    
    # 渲染各个图像,一般首先渲染screen,它做为背景    
    screen.fill((0,0,0))
    [ screen.blit(square.image,square.rect)  for square in squares ]             

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""demo rect object collison.
本程序演示pygame矩形的碰撞检测,本程序设定一个固定矩形,然后在屏幕中央生成一些随机速度的矩形。
它们碰到固定矩形会反向移动。
   
"""
import random
import pygame
from pygame.locals import *           # 导入常量

class Square:
    """方块类"""
    def __init__(self,group,position=(0,0)):
        """初始化"""
        w,h = random.randint(25,100),random.randint(25,100) # temp vars
        self.image = pygame.Surface((w,h))       # 方块要渲染的图像
        r,g,b = random.randint(0,255),random.randint(0,255),random.randint(0,255)
        self.image.fill((r,g,b))               #  填充颜色
        self.rect = self.image.get_rect()      # 方块的矩形对象
        self.rect.center = (width//2,height//2)       
        self.group = group
        self.group.append(self)                # 把自己添加到组中
        
    def move(self):
        """移动矩形"""
        self.rect.move_ip(self.dx,self.dy)
        self.vanish_on_edge()

    def vanish_on_edge(self):
        """到边缘消失"""
        if self.rect.right <= 0 or self.rect.left >= width or  \
           self.rect.bottom <= 0 or self.rect.top >= height: self.group.remove(self)
        

width,height = 480,360                         # define screen'width and height
speed = [-5,-4,-3,-2,-1,1,2,3,4,5]

pygame.init()                                  # pygame初始化
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame演示矩形碰撞by李兴球")

squares = [ ]

fixed_square = Square(squares,(100,100))       # 固定不动的方块
fixed_square.dx = 0         # 水平单位位移
fixed_square.dy = 0         # 垂直单位位移
fixed_square.rect.center = (100,100)
    
# 以下设置定时器事件
spawn_event  = USEREVENT + 1
pygame.time.set_timer(spawn_event,1000)

running = True
clock = pygame.time.Clock()                    # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == spawn_event:
            q = Square(squares)
            q.dx = random.choice(speed)
            q.dy = random.choice(speed)
        if event.type == QUIT: running = False            

    [ square.move()  for square in squares ]   # 移动每个方块

    for square in squares:
        if square == fixed_square:continue
        if square.rect.colliderect(fixed_square.rect):   #  如果square碰到固定矩形          
            square.dy = -square.dy        
            square.dx = -square.dx
        
    
    # 渲染各个图像,一般首先渲染screen,它做为背景    
    screen.fill((0,0,0))
    [ screen.blit(square.image,square.rect)  for square in squares ]             

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""  demo pygame spriteclass。
本程序演示pygame的sprite类,新建了一个Square类,它继承自pygame.sprite.Sprite。
新建的squares不再是单纯的list了,而是一个 pygame.sprite.Group实例。这样可以对角色进行统一操作。
这前提是精灵要有image和rect属性。

   
"""
import random
import pygame
from pygame.locals import *           # 导入常量

class Square(pygame.sprite.Sprite):
    """方块类"""
    def __init__(self,group,position=(0,0)):
        """初始化"""
        pygame.sprite.Sprite.__init__(self)
        w,h = random.randint(25,100),random.randint(25,100) # temp vars
        self.image = pygame.Surface((w,h))       # 方块要渲染的图像
        r,g,b = random.randint(0,255),random.randint(0,255),random.randint(0,255)
        self.image.fill((r,g,b))                #  填充颜色
        self.rect = self.image.get_rect()       # 方块的矩形对象
        self.rect.center = (width//2,height//2)
        if group!=None:
            self.group = group
            self.group.add(self)                 # 把自己添加到组中

    def update(self):
        
        self.move()
        
    def move(self):
        """移动矩形"""
        self.rect.move_ip(self.dx,self.dy)
        self.vanish_on_edge()

    def vanish_on_edge(self):
        """到边缘消失"""
        if self.rect.right <= 0 or self.rect.left >= width or  \
           self.rect.bottom <= 0 or self.rect.top >= height: self.group.remove(self)
        

width,height = 480,360                         # define screen'width and height
speed = [-5,-4,-3,-2,-1,1,2,3,4,5]

pygame.init()                                  # pygame初始化
screen = pygame.display.set_mode((width,height))# 新建屏幕对象
pygame.display.set_caption("pygame演示继承继承类的矩形与组by李兴球")

squares = pygame.sprite.Group()                # 新建精灵组

fixed_square = Square(None,(100,100))          # 固定不动的方块,不添加到组中
fixed_square.dx = 0                            # 水平单位位移
fixed_square.dy = 0                            # 垂直单位位移
fixed_square.rect.center = (100,100)
    
# 以下设置定时器事件
spawn_event  = USEREVENT + 1
pygame.time.set_timer(spawn_event,1000)

running = True
clock = pygame.time.Clock()                    # 时钟对象

while running:
    for event in pygame.event.get():
        if event.type == spawn_event:
            q = Square(squares)
            q.dx = random.choice(speed)
            q.dy = random.choice(speed)
        if event.type == QUIT: running = False            

    squares.update()                           # 移动每个方块

    sprite = pygame.sprite.spritecollideany(fixed_square,squares)
    if sprite:
       sprite.dy = -sprite.dy        
       sprite.dx = -sprite.dx

    
    # 渲染各个图像,一般首先渲染screen,它做为背景    
    screen.fill((0,0,0))
    squares.draw(screen)             # 重画所有精灵
    screen.blit(fixed_square.image,fixed_square.rect) # 画固定方块

    # 渲染完后更新窗体的显示
    pygame.display.update()          # 更新显示

    # 等待1/60份之一秒过后再次循环
    clock.tick(60)                   # set fps 60
 
pygame.quit()
"""demo inherit sprite class example code.
本程序演示继承pygame的sprite类,这个类实例化后会不断地旋转。

   
"""
 
import pygame
from pygame.locals import *           # 导入常量

class Square(pygame.sprite.Sprite):
    """方块类"""
    def __init__(self,group,image,position=(0,0)):
        """初始化"""
        pygame.sprite.Sprite.__init__(self)
        self.position = position        
        self.raw_image = image                 # 记录原始图像,image是一个surface
        self.image = image        
        self.rect = self.image.get_rect()      # 方块的矩形对象
        self.rect.center = position
        self._angle = 0                        # 设定角度属性
        if group!=None:
            self.group = group
            self.group.add(self)               # 把自己添加到组中
            
    def update(self):
        
        self.rotate(1)
            
    def rotate(self,dangle):
        """旋转一定的角度"""
        self._angle += dangle
        self.image = pygame.transform.rotate(self.raw_image,self._angle)
        self.rect = self.image.get_rect()
        self.rect.center = self.position
 
def main():
    
    width,height = 800,600                         # define screen'width and height
    pygame.init()                                  # pygame初始化

    screen = pygame.display.set_mode((width,height))# 新建屏幕对象
    pygame.display.set_caption("pygame演示继承精灵类与角色旋转与缩放及by李兴球")

    image = pygame.image.load("lixingqiu.png").convert_alpha()
    image = pygame.transform.scale(image,(50,20))   # 缩放图像

    squares = pygame.sprite.Group()                # 新建精灵组

    for x in range(100,width,150):                 # 生成一些方块
        for y in range(50,height,150):
            Square(squares,image,(x,y))

    running = True
    clock = pygame.time.Clock()                    # 时钟对象

    while running:
        for event in pygame.event.get():        
            if event.type == QUIT: running = False            

        squares.update()                           # 移动每个方块
        
        # 渲染各个图像,一般首先渲染screen,它做为背景    
        screen.fill((0,0,0))
        squares.draw(screen)             # 重画所有方块 

        # 渲染完后更新窗体的显示
        pygame.display.update()          # 更新显示

        # 等待1/60份之一秒过后再次循环
        clock.tick(60)                   # set fps 60
     
    pygame.quit()

if __name__=="__main__":
    
    main()
    
"""demo onpress check,move a arrow like turtle in logo computer language
Pygame按键检测_实现简易海龟形式的移动

   
"""
import math
import pygame
from pygame.locals import *           # 导入常量

_turtle_point_list = [(0,25),(50,25),(40,15),(40,35),(50,25)]

class Turtle(pygame.sprite.Sprite):
    """方块类"""
    def __init__(self,position=(0,0)):
        """初始化"""
        pygame.sprite.Sprite.__init__(self)
        self.position = position        
        self.raw_image = pygame.Surface((50,50))
        pygame.draw.lines(self.raw_image,(0,255,255),False,_turtle_point_list)
        self.image = self.raw_image        
        self.rect = self.image.get_rect()      # 方块的矩形对象
        self.rect.center = position
        self._angle = 0                        # 设定角度属性(方向)
        
    def forward(self,distance):
        """朝自己的方向前进一定的距离"""
        dx = distance * math.cos(math.radians(self._angle)) 
        dy = -distance * math.sin(math.radians(self._angle))
        self.rect.centerx += dx
        self.rect.centery += dy        
  
            
    def rotate(self,dangle):
        """旋转一定的角度"""
        rotate_center = self.rect.center       # 记录旋转中心        
        self._angle += dangle
        pygame.display.set_caption(str(self._angle) + "_Pygame按键检测_实现简易海龟形式的移动by李兴球")
        self.image = pygame.transform.rotate(self.raw_image,self._angle)
        self.rect = self.image.get_rect()
        self.rect.center = rotate_center       # 定位到旋转中心 

        
def main():
    
    width,height = 800,600                         # define screen'width and height
    pygame.init()                                  # pygame初始化

    screen = pygame.display.set_mode((width,height))# 新建屏幕对象
    pygame.display.set_caption("Pygame按键检测_实现简易海龟形式的移动by李兴球")

    turtle = Turtle((width//2,height//2))
    running = True
    clock = pygame.time.Clock()                    # 时钟对象

    while running:
        for event in pygame.event.get():        
            if event.type == QUIT: running = False
##            if event.type == KEYDOWN:
##                if event.key == K_UP:turtle.forward(10)
##                if event.key == K_DOWN:turtle.forward(-10)
##                if event.key == K_LEFT:turtle.rotate(1)
##                if event.key == K_RIGHT:turtle.rotate(-1)               

        keys = pygame.key.get_pressed()            # 获取所有按键检测
        if keys[K_UP] : turtle.forward(10)
        if keys[K_DOWN] : turtle.forward(-10)
        if keys[K_LEFT] : turtle.rotate(2)
        if keys[K_RIGHT] : turtle.rotate(-2)        
        
        # 渲染各个图像,一般首先渲染screen,它做为背景    
        screen.fill((0,0,0))
        screen.blit(turtle.image,turtle.rect)
        
        # 渲染完后更新窗体的显示
        pygame.display.update()          # 更新显示

        # 等待1/60份之一秒过后再次循环
        clock.tick(60)                   # set fps 60
     
    pygame.quit()

if __name__=="__main__":
    
    main()