import pygame import sys from pygame.locals import * #初始化pygame pygame.init() size = width,height=600,400 speed=[-2,1] # rgb bg=(255,255,255) clock = pygame.time.Clock() #创建指定大小窗口 surface screen = pygame.display.set_mode(size) # 设置窗口标题 pygame.display.set_caption("初次见面,请多多关照") #加载图片 image = pygame.image.load("qq.png") #获取图像的位置矩形 position = image.get_rect() # 图像翻转 l_head = image # 图像翻转 r_head = pygame.transform.flip(image,True,False) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == KEYDOWN: if event.key==K_LEFT: image = l_head speed = [-1,0] if event.key==K_RIGHT: image = r_head speed = [1,0] if event.key==K_UP: speed = [0,-1] if event.key==K_DOWN: speed = [0,1] #移动图像 position = position.move(speed) if position.left < 0 or position.right>width: #翻转图像 flip(surface对象,是否水平翻转,是否垂直翻转) image = r_head #反方向移动 speed[0] = -speed[0] if position.top<0 or position.bottom > height: speed[1] = -speed[1] # 填充背景 screen.fill(bg) # 更新图像 screen.blit(image,position) # 更新界面 pygame.display.flip() #延迟10毫秒 # pygame.time.delay(10) clock.tick(20)