素材提取
链接:https://pan.baidu.com/s/1Kb9xRrbHTM7yTvLdESI6xg
提取码:dkqi
初识pygame
这是一个可控制的鸭子在画面中移动的例子:
import pygame
import sys
from pygame.locals import *
#初始化pygame
pygame.init()
size = width,height =800,500
speed = [-2 ,1]
bg = (255,255,255)
#创建指定大小的窗口
screen = pygame.display.set_mode(size)
#设置窗口标题
pygame.display.set_caption("这是我pygame的第一个尝试")
#加载图片
cat = pygame.image.load("duck.jpg")
#获取图像的位置矩形
position = cat.get_rect()
l_head = cat
r_head = pygame.transform.flip(cat,True,False)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
cat =l_head
speed = [-1,0]
if event.key == pygame.K_RIGHT:
cat = r_head
speed = [1,0]
if event.key == pygame.K_UP:
speed = [0,-1]
if event.key == pygame.K_DOWN:
speed = [0,1]
#移动图像
position = position.move(speed)
if position.left < 0 or position.right > width:
#翻转图像
cat = pygame.transform.flip(cat,True,False)
#反向移动
speed[0] = -speed[0]
if position.top < 0 or position.bottom > height:
speed[1] = -speed[1]
#填充背景
screen.fill(bg)
#更新图像
screen.blit(cat,position)
#更新界面
pygame.display.flip()
#延迟10毫秒
pygame.time.delay(10)
界面显示用户当前操作,并记录在文件中:
import pygame
import sys
#初始化pygame
pygame.init()
size = width,height =800,500
screen = pygame.display.set_mode(size)
pygame.display.set_caption("黑客帝国")
bg = (0,0,0)
position = 0
font = pygame.font.Font(None,20)
line_height = font.get_linesize()
screen.fill(bg)
f = open("record.txt","w")
while True:
for event in pygame.event.get():
f.write(str(event) + '\n')
if event.type == pygame.QUIT:
f.close()
sys.exit()
screen.blit(font.render(str(event),True,(0,255,0)),(0,position))
position += line_height
if position > height:
position = 0
screen.fill(bg)
pygame.display.flip