|
发表于 2019-10-22 23:17:23
|
显示全部楼层
本帖最后由 月-空轨 于 2019-10-22 23:25 编辑
[code]#支持40-200帧率
import pygame
import sys
#导入所有常量名
from pygame.locals import *
#初始化pygame
pygame.init()
size = width,height=1000,600
#位移
speed = [-2,1]
bg = (255,255,255)#RGB颜色。这里白色
fullscreen = False
#设置帧率
clock = pygame.time.Clock()
#创建指定大小的窗口,返回一个Surface对象,RESIZABLE窗口可修改resizable
screen = pygame.display.set_mode(size,RESIZABLE)
#设置窗口标题
pygame.display.set_caption("初次见面,请大家多多关照!")
#设置放大缩小的比例
ratio = 1.0
#加载图片
otrail = pygame.image.load('turtle.png')
trail = otrail
otrail_rect = otrail.get_rect()
#获取图像的位置矩形
position = trail_rect = otrail_rect
#转头/向
l_head = trail
#(trail,True,False) (图像,左右翻转,上下翻转)
r_head = pygame.transform.flip(trail,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:
trail = l_head
speed = [-1,0]
if event.key == K_RIGHT:
trail = r_head
speed = [1,0]
if event.key == K_UP:
speed = [0,-1]
if event.key == K_DOWN:
speed = [0,1]
#全屏
if event.key == K_F11:
fullscreen = not fullscreen
if fullscreen:
#FULLSCREEN | HWSURFACE硬件加速hwsurface
screen = pygame.display.set_mode((1366,768),FULLSCREEN | HWSURFACE)
size = width,height = 1366,768
else:
size = width,height = 1000,600
screen = pygame.display.set_mode(size)
#放大缩小(=,-),空格键恢复尺寸
if event.key == K_EQUALS or event.key == K_MINUS or event.key == K_SPACE:
if event.key == K_EQUALS and ratio <2:
ratio +=0.1
if event.key == K_MINUS and ratio >0.2:
ratio -=0.1
if event.key == K_SPACE:
ratio = 1.0
trail = pygame.transform.smoothscale(otrail,\
(int(otrail_rect.width*ratio),\
int(otrail_rect.height*ratio)))
position = trail_rect = trail.get_rect()
#VIDEORESIZE用户调整窗口尺寸videoresize
if event.type == VIDEORESIZE:
size = event.size
width,height = size
print(size)
#创建指定大小的窗口,返回一个Surface对象,RESIZABLE窗口可修改resizable
screen = pygame.display.set_mode(size,RESIZABLE)
#移动图像
position = position.move(speed)
if position.right>width:
#trail_rect = trail.get_rect()
#position = trail_rect = trail.get_rect()
# 这里重新获取了 dog,即 left 和 top 又初始了0
print(position.left,position.right,position.top,position.bottom)
# 因此这里需要重新更新下 left 保证沿右边界运行
position.left = width - trail_rect.width
trail = pygame.transform.flip(trail,True,False)
speed[0]=-speed[0]
if position.left <0 :
#翻转图像
#(trail,True,False) (图像,左右翻转,上下翻转)
trail = pygame.transform.flip(trail,True,False)
#反方向移动 speed[0]=-(-2)
speed[0]=-speed[0]
if position.top<0:
speed[1] = -speed[1]
if position.bottom>height:
#trail_rect = trail.get_rect()
position.top = height - trail_rect.bottom
speed[1] = -speed[1]
#填充背景
screen.fill(bg)
#更新图像 blit 將一个图像画到另一个图像上
screen.blit(trail,position)
#更新界面
pygame.display.flip()
#延迟10毫秒
pygame.time.delay(10)
#一秒一帧
#clock.tick(1)
|
|