position=position.move(speed)
从这一句开始,后面的代码全部加一个Tab缩进
会大大提升效率
修改后代码:import pygame
import sys
from pygame.locals import *
pygame.init()
size=width,height=600,400
screen=pygame.display.set_mode(size) #这里如果不分2句写会报错
bg=(255,255,255)
pygame.display.set_caption("Turtle Go")
turtle=pygame.image.load(r"C:\Programstudy\Python\mytest\Pygamestudy\images\turtle.png")
clock=pygame.time.Clock()
position=turtle_rect=turtle.get_rect() #获得图像的位置矩形
# 小乌龟顺时针行走
speed=[5,0]
#先把旋转命令定义好
turtle_right=pygame.transform.rotate(turtle,90) #靠右走时图片逆时针转了90°
turtle_top=pygame.transform.rotate(turtle,180)
turtle_left=pygame.transform.rotate(turtle,270)
#turtle_bottom=pygame.transform.rotate(turtle,0)
turtle_bottom=turtle #这两句试验下来效果等同
#刚开始走顶部
turtle=turtle_top
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
position=position.move(speed)
if position.right>width:
turtle=turtle_right #旋转
position=turtle_rect=turtle.get_rect()
position.left=width-turtle_rect.width
speed=[0,5]
if position.bottom>height:
turtle=turtle_bottom
position=turtle_rect=turtle.get_rect()
position.top=height-turtle_rect.height
position.left=width-turtle_rect.width
speed=[-5,0]
if position.left<0:
turtle = turtle_left
position = turtle_rect = turtle.get_rect()
position.top = height-turtle_rect.height
speed = [0,-5]
if position.top<0:
turtle = turtle_top
position = turtle_rect = turtle.get_rect()
speed = [5,0]
screen.fill(bg)
screen.blit(turtle,position)
pygame.display.flip()
clock.tick(30)
|